import pandas as pd
import os
import sys

scrape_results = ['Blog_Scrape_for_Android_Malware.xlsx', 'Blog_Scrape_for_Google_Malware.xlsx', 'Blog_Scrape_for_Play_Store_Malware.xlsx', 'Blog_Scrape_for_Playstore_Malware.xlsx']
sheets_to_merge = ['Malware Details (2016+2017)', 'Malware Details (2016+2017) - E', 'Malware Details (2019)']
blogs_already_done = ['Google_Or_Android_Malware.xlsx']

columns = ['title', 'date', 'blog_url', 'matches', 'company']
def main():
    main_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
    sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/..')

    blog_file_path = os.path.join(main_dir, 'temp', 'BlogSheet.xlsx')

    url_list = set()

    df = pd.DataFrame()
    for sheet in sheets_to_merge:
        sheet_df = pd.read_excel(blog_file_path, sheet_name=sheet)
        df = df.append(sheet_df, ignore_index = True)

    for url in df['child blog url'].values:
        url_list.add(url)

    urls_from_crawler = set()

    for root, dirs, files in os.walk(os.path.join(main_dir, 'temp', 'base_urls_for_keywords')):
        for file_name in files:
            if file_name.endswith('.txt'):
                with open(os.path.join(root, file_name)) as f:
                    content = f.readlines()
                    content = [x.strip() for x in content]

                    for line in content:
                        urls_from_crawler.add(line)

    for url in url_list:
        if url not in urls_from_crawler:
            print(url)

if __name__== "__main__":
    main()


import os
import time
import torch
from tqdm import tqdm

from experiment import Experiment
from data.data_loader import DistributedSampler
from apex import amp
from torch_npu.utils.profiler import Profile

def seed_everything(seed):
    os.environ['PYTHONHASHSEED'] = str(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

class AverageMeter(object):
    """Computes and stores the average and current value"""

    def __init__(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

class Trainer:
    def __init__(self, experiment: Experiment):
        self.experiment = experiment
        self.init_device()
        if self.experiment.train.data_loader.seed is not None:
            seed_everything(self.experiment.train.data_loader.seed)
        self.structure = experiment.structure
        self.logger = experiment.logger
        self.model_saver = experiment.train.model_saver

        # FIXME: Hack the save model path into logger path
        self.model_saver.dir_path = self.logger.save_dir(
            self.model_saver.dir_path)
        self.current_lr = 0
        self.total = 0

    def init_device(self):
        if torch.npu.is_available():
            self.device = torch.device(f'npu:{self.experiment.device_id}')
        else:
            self.device = torch.device('cpu')

    def init_model(self):
        model = self.structure.builder.build(
            self.device, self.experiment.distributed, self.experiment.local_rank)
        return model

    def update_learning_rate(self, optimizer, epoch, step):
        lr = self.experiment.train.scheduler.learning_rate.get_learning_rate(
            epoch, step)

        for group in optimizer.param_groups:
            group['lr'] = lr
        self.current_lr = lr

    def train(self, profiling, collect_start, collect_end):
        self.logger.report_time('Start')
        self.logger.args(self.experiment)
        model = self.init_model()
        train_data_loader = self.experiment.train.data_loader.train_loader
        if self.experiment.validation:
            validation_loaders = self.experiment.validation.data_loaders
        self.steps = 0
        epoch = 0
        if self.experiment.train.checkpoint:
            self.experiment.train.checkpoint.restore_model(
                model, self.device, self.logger)
            epoch, iter_delta = self.experiment.train.checkpoint.restore_counter()
            self.steps = epoch * self.total + iter_delta

        # Init start epoch and iter
        optimizer = self.experiment.train.scheduler.create_optimizer(
            model.parameters())
        if self.experiment.amp:
            amp.register_float_function(torch, "sigmoid")
            model, optimizer = amp.initialize(model, optimizer, opt_level="O1", loss_scale=1024, combine_grad=True)
        self.logger.report_time('Init')
        batch_time = AverageMeter()
        data_time = AverageMeter()
        losses = AverageMeter()
        model.train()
        end = time.time()
        while True:
            self.logger.info('Training epoch ' + str(epoch))
            self.logger.epoch(epoch)
            self.total = len(train_data_loader)
            profiler = Profile(start_step=int(os.getenv("PROFILE_START_STEP", 10)),
                               profile_type=os.getenv("PROFILE_TYPE"))
            for batch in train_data_loader:
                data_time.update((time.time() - end) * 1000)
                self.update_learning_rate(optimizer, epoch, self.steps)
                self.logger.report_time("Data loading")
                if self.experiment.validation and\
                        self.steps % self.experiment.validation.interval == 0 and\
                        self.steps > self.experiment.validation.exempt:
                    self.validate(validation_loaders, model, epoch, self.steps)
                self.logger.report_time('Validating ')
                if self.logger.verbose:
                    torch.npu.synchronize()
                profiler.start()
                loss_item = self.train_step(model, optimizer, batch,
                                epoch=epoch, step=self.steps)
                profiler.end()
                losses.update(loss_item)
                if self.logger.verbose:
                    torch.npu.synchronize()
                self.logger.report_time('Forwarding ')
                self.model_saver.maybe_save_model(
                    model, epoch, self.steps, self.logger)
                self.steps += 1
                if self.steps == 9:
                    batch_time.reset()
                    data_time.reset()
                if self.total > 0 and self.steps % self.total == 2:
                    batch_time.reset()
                batch_time.update((time.time() - end) * 1000)
                if self.steps % self.experiment.logger.log_interval == 0:
                    fps = self.experiment.train.data_loader.batch_size * 1000 / batch_time.val
                    step_count = (self.steps - 1) % self.total + 1
                    msg = 'Epoch: [{0}][{1}/{2}]\t' \
                        'Time {batch_time.val:.3f}ms ({batch_time.avg:.3f}ms)\t' \
                        'Data {data_time.val:.3f}ms ({data_time.avg:.3f}ms)\t' \
                        'Fps {fps:.3f}\t' \
                        'Loss {loss.val:.5f} ({loss.avg:.5f})\t'.format(
                        epoch, step_count, self.total, batch_time=batch_time,
                        data_time=data_time, fps=fps, loss=losses)
                    self.logger.info(msg)
                end = time.time()
            self.logger.info('npu id: {device_no:1d}' \
                  ' * FPS@all {fps:.3f}'.format(device_no=self.device.index, fps=self.experiment.train.data_loader.batch_size * 1000 / batch_time.avg))

            epoch += 1
            if epoch > self.experiment.train.epochs:
                if self.experiment.local_rank in [-1, 0]:
                    self.model_saver.save_checkpoint(model, 'final')
                    if self.experiment.validation:
                        self.validate(validation_loaders, model, epoch, self.steps)
                    self.logger.info('Training done')
                break
            iter_delta = 0

    def train_step(self, model, optimizer, batch, epoch, step, **kwards):
        # Temporary solution for huge memory usage by topk.
        # This should be deleted in future version.
        if step == 0 and epoch == 0:
            tmp = torch.rand(16, 16, 640, 640, dtype=torch.float32).npu()
            top, _ = torch.topk(tmp.view(-1).half(), 4000000)
            top, _ = torch.topk(tmp.view(-1).half(), 6000000)
        optimizer.zero_grad()
        results = model.forward(batch, training=True)
        if len(results) == 2:
            l, pred = results
            metrics = {}
        elif len(results) == 3:
            l, pred, metrics = results

        if isinstance(l, dict):
            line = []
            loss = torch.tensor(0.).npu()
            for key, l_val in l.items():
                loss += l_val.mean()
                line.append('loss_{0}:{1:.4f}'.format(key, l_val.mean()))
        else:
            loss = l
        if self.experiment.amp:
            with amp.scale_loss(loss, optimizer) as scaled_loss:
                scaled_loss.backward()
        else:
            loss.backward()
        optimizer.step()
        return loss.item()

    def validate(self, validation_loaders, model, epoch, step):
        all_matircs = {}
        model.eval()
        for name, loader in validation_loaders.items():
            if self.experiment.validation.visualize:
                metrics, vis_images = self.validate_step(
                    loader, model, True)
                self.logger.images(
                    os.path.join('vis', name), vis_images, step)
            else:
                metrics, vis_images = self.validate_step(loader, model, False)
            for _key, metric in metrics.items():
                key = name + '/' + _key
                if key in all_matircs:
                    all_matircs[key].update(metric.val, metric.count)
                else:
                    all_matircs[key] = metric

        for key, metric in all_matircs.items():
            self.logger.info('%s : %f (%d)' % (key, metric.avg, metric.count))
        self.logger.metrics(epoch, self.steps, all_matircs)
        model.train()
        return all_matircs

    def validate_step(self, data_loader, model, visualize=False):
        raw_metrics = []
        vis_images = dict()
        for i, batch in tqdm(enumerate(data_loader), total=len(data_loader)):
            pred = model.forward(batch, training=False)
            output = self.structure.representer.represent(batch, pred)
            raw_metric, interested = self.structure.measurer.validate_measure(
                batch, output)
            raw_metrics.append(raw_metric)

            if visualize and self.structure.visualizer:
                vis_image = self.structure.visualizer.visualize(
                    batch, output, interested)
                vis_images.update(vis_image)
        metrics = self.structure.measurer.gather_measure(
            raw_metrics, self.logger)
        return metrics, vis_images

    def to_np(self, x):
        return x.cpu().data.numpy()


from google.protobuf import message

from recipe_engine import recipe_api, recipe_test_api
from recipe_engine import util as recipe_util

from . import proto_codec

class ProtoOutputPlaceholder(recipe_util.OutputPlaceholder):
  def __init__(self, api, msg_class, codec, add_json_log, name,
               leak_to, decoding_kwargs):
    if codec is proto_codec.BINARY:
      self.raw = api.m.raw_io.output(codec.ext, leak_to=leak_to)
    else:
      self.raw = api.m.raw_io.output_text(codec.ext, leak_to=leak_to)
    self.add_json_log = add_json_log
    self._msg_class = msg_class
    self._codec = codec
    self._decoding_kwargs = decoding_kwargs
    super(ProtoOutputPlaceholder, self).__init__(name=name)

  @property
  def backing_file(self):
    return self.raw.backing_file

  def render(self, test):
    return self.raw.render(test)

  def result(self, presentation, test):
    # This is a bit silly, but we only have the codec information here, and
    # we don't want the user to redundantly provide it in the test.
    if test.enabled and isinstance(test.data, message.Message):
      # We replace the test object with one containing raw bytes for raw_io.
      test = recipe_test_api.PlaceholderTestData(
          data=ProtoApi.encode(test.data, self._codec),
          name=self.name)

    # Save name before self.raw.result() deletes it.
    backing_file = self.backing_file
    raw_data = self.raw.result(presentation, test)
    if raw_data is None:
      if self.add_json_log in (True, 'on_failure'):
        presentation.logs[self.label + ' (read error)'] = [
          'Proto file was missing or unreadable:',
          '  ' + backing_file,
        ]
      return None

    valid = False
    invalid_error = ''
    ret = None
    try:
      ret = ProtoApi.decode(
          raw_data, self._msg_class, self._codec, **self._decoding_kwargs)
      valid = True
    except Exception as ex:  # pragma: no cover
      invalid_error = str(ex)
      jsonErrPrefix = 'Failed to load JSON: '
      if test.enabled and invalid_error.startswith(jsonErrPrefix):
        invalid_error = (
            jsonErrPrefix +
            recipe_util.unify_json_load_err(invalid_error[len(jsonErrPrefix):]))

    if self.add_json_log is True or (
        self.add_json_log == 'on_failure' and presentation.status != 'SUCCESS'):
      if valid:
        jsonpb = ProtoApi.encode(ret, 'JSONPB', indent=2)
        presentation.logs[self.label] = jsonpb.splitlines()
      else:
        presentation.logs[self.label + ' (invalid)'] = raw_data.splitlines()
        presentation.logs[self.label + ' (exception)'] = (
          invalid_error.splitlines())

    return ret

class ProtoApi(recipe_api.RecipeApi):

  @recipe_util.returns_placeholder
  def input(self, proto_msg, codec, **encoding_kwargs):
    """A placeholder which will expand to a file path containing the encoded
    `proto_msg`.

    Example:
       proto_msg = MyMessage(field=10)
       api.step('step name', ['some_cmd', api.proto.input(proto_msg)])
       # some_cmd sees "/path/to/random.pb"

    Args:
      * proto_msg (message.Message) - The message data to encode.
      * codec ('BINARY'|'JSONPB'|'TEXTPB') - The encoder to use.
      * encoding_kwargs - Passed directly to the chosen encoder. See:
        - BINARY: google.protobuf.message.Message.SerializeToString
          * 'deterministic' defaults to True.
        - JSONPB: google.protobuf.json_format.MessageToJson
          * 'preserving_proto_field_name' defaults to True.
          * 'sort_keys' defaults to True.
          * 'indent' defaults to 0.
        - TEXTPB: google.protobuf.text_format.MessageToString

    Returns an InputPlaceholder.
    """
    codec = proto_codec.resolve(codec)
    encoded = self.encode(proto_msg, codec, **encoding_kwargs)
    suffix = '.%s' % (codec.ext,)
    if codec is proto_codec.BINARY:
      return self.m.raw_io.input(encoded, suffix=suffix)
    return self.m.raw_io.input_text(encoded, suffix=suffix)

  @recipe_util.returns_placeholder
  def output(self, msg_class, codec, add_json_log=True, name=None,
             leak_to=None, **decoding_kwargs):
    """A placeholder which expands to a file path and then reads an encoded
    proto back from that location when the step finishes.

    Args:
      * msg_class (protobuf Message subclass) - The message type to decode.
      * codec ('BINARY'|'JSONPB'|'TEXTPB') - The encoder to use.
      * add_json_log (True|False|'on_failure') - Log a copy of the parsed proto
        in JSONPB form to a step link named `name`. If this is 'on_failure',
        only create this log when the step has a non-SUCCESS status.
      * leak_to (Optional[Path]) - This path will be used in place of a random
        temporary file, and the file will not be deleted at the end of the step.
      * decoding_kwargs - Passed directly to the chosen decoder. See:
        - BINARY: google.protobuf.message.Message.Parse
        - JSONPB: google.protobuf.json_format.Parse
          * 'ignore_unknown_fields' defaults to True.
        - TEXTPB: google.protobuf.text_format.Parse
    """
    codec = proto_codec.resolve(codec)
    if not issubclass(msg_class, message.Message): # pragma: no cover
      raise ValueError('msg_class is unexpected type: %r' % (msg_class,))
    if add_json_log not in (True, False, 'on_failure'): # pragma: no cover
      raise ValueError(
          'unexpected value for add_json_log: %r' % (add_json_log,))

    return ProtoOutputPlaceholder(
        self, msg_class, codec, add_json_log, name, leak_to, decoding_kwargs)

  @staticmethod
  def encode(proto_msg, codec, **encoding_kwargs):
    """Encodes a proto message to a string.

    Args:
      * codec ('BINARY'|'JSONPB'|'TEXTPB') - The encoder to use.
      * encoding_kwargs - Passed directly to the chosen encoder. See output
        placeholder for details.

    Returns the encoded proto message.
    """
    if not isinstance(proto_msg, message.Message): # pragma: no cover
      raise ValueError('proto_msg had unexpected type: %s' % (type(proto_msg),))
    return proto_codec.do_enc(codec, proto_msg, **encoding_kwargs)

  @staticmethod
  def decode(data, msg_class, codec, **decoding_kwargs):
    """Decodes a proto message from a string.

    Args:
      * msg_class (protobuf Message subclass) - The message type to decode.
      * codec ('BINARY'|'JSONPB'|'TEXTPB') - The encoder to use.
      * decoding_kwargs - Passed directly to the chosen decoder. See input
        placeholder for details.

    Returns the decoded proto object.
    """
    if not issubclass(msg_class, message.Message): # pragma: no cover
      raise ValueError('msg_class is unexpected type: %r' % (msg_class,))
    return proto_codec.do_dec(data, msg_class, codec, **decoding_kwargs)


__version__ = "5.1.0"

ANSWERS_URL = "https://github.com/natenka/pyneng-tasks-solutions"
# needed for tasks/tests updates
TASKS_URL = "https://github.com/natenka/pynenguk-tasks"
TASKS_LOCAL_REPO = ".pynenguk-tasks"
LANG_TASKS_URL = {
    "uk": "https://github.com/natenka/pynenguk-tasks",
    "en": "https://github.com/natenka/pyneng-examples-exercises-en",
    "ru": "https://github.com/pyneng/pyneng-course-tasks",
}
LANG_TASKS_LOCAL_REPO = {
    "uk": ".pynenguk-tasks",
    "en": ".pyneng-examples-exercises-en",
    "ru": ".pyneng-course-tasks",
}
DEFAULT_BRANCH = "main"
TASK_DIRS = [
    "04_data_structures",
    "05_basic_scripts",
    "06_control_structures",
    "07_files",
    "09_functions",
    "11_modules",
    "12_useful_modules",
    "15_module_re",
    "17_serialization",
    "18_ssh_telnet",
    "19_concurrent_connections",
    "20_jinja2",
    "21_textfsm",
    "22_oop_basics",
    "23_oop_special_methods",
    "24_oop_inheritance",
    "25_db",
]
TASK_NUMBER_DIR_MAP = {
    4: "04_data_structures",
    5: "05_basic_scripts",
    6: "06_control_structures",
    7: "07_files",
    9: "09_functions",
    11: "11_modules",
    12: "12_useful_modules",
    15: "15_module_re",
    17: "17_serialization",
    18: "18_ssh_telnet",
    19: "19_concurrent_connections",
    20: "20_jinja2",
    21: "21_textfsm",
    22: "22_oop_basics",
    23: "23_oop_special_methods",
    24: "24_oop_inheritance",
    25: "25_db",
}

DB_TASK_DIRS = [
    "task_25_1",
    "task_25_2",
    "task_25_3",
    "task_25_4",
    "task_25_5",
    "task_25_5a",
    "task_25_6",
]


import logging
from django.views.generic import TemplateView

import uptrace

logger = logging.getLogger(__name__)

class IndexView(TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["trace_url"] = uptrace.trace_url()
        return context

class HelloView(TemplateView):
    template_name = "hello.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["trace_url"] = uptrace.trace_url()
        return context

class FailingView(TemplateView):
    template_name = "hello.html"

    def get_context_data(self, **kwargs):
        print(uptrace.trace_url())
        raise ValueError("something went wrong")


#  -*- coding: utf-8 -*-
'''
Created on 3/5/2015

@author: abrahan
'''
from py.una.pol.tava.model.mboxplot import BoxPlotModel as bpm

class BoxPlotFilterPresenter:
    def __init__(self, iview, test):
        self.iview = iview
        self.test = test
        self.InitUI()

    def InitUI(self):

        # inicialización para valores de variables
        bp = bpm().getBoxPlotByTestId(self.test.id)
        v_names = bp.name_variable
        columns = v_names.split(',')
        self.countColumn = len(columns)
        self.iview.var.AppendTextColumn('key', width=50)
        for name in columns:
            self.iview.var.AppendTextColumn(name, width=110)

        # inicialización para valores de objetivos
        o_names = bp.order_name_obj
        columns = o_names.split(',')
        self.countColumn = len(columns)
        self.iview.obj.AppendTextColumn('key', width=50)
        for name in columns:
            self.iview.obj.AppendTextColumn(name, width=150)

    def updateValuesList(self, ite_list):
        ite = ite_list[0]
        self.iview.deltePages()

        self.iview.InitUI()
        self.InitUI()

        # actualizacion de variables
        for var in bpm().getListVariables(ite):
            self.iview.var.AppendItem(var)

        # actualizacion de objetivos
        for obj in bpm().getListObjectives(ite):
            self.iview.obj.AppendItem(obj)

        # actualizacion de Objetivos
        # filtro las variables correspondientes
        vmin, vmax = bpm().getMinMaxObjective(ite)

        # obtengo los nombres
        bp = bpm().getBoxPlotByTestId(self.test.id)
        names = bp.order_name_obj.split(',')

        # creo los filtros
        self.values = []

        if len(names) == len(vmin):
            for index in range(len(names)):
                value = self.iview.addItemFil(vmin[index], vmax[index],
                                              names[index], vmin[index],
                                              vmax[index])
                self.values.append(value)
        # actualizo la vista
        self.iview.addSiserHere()
        self.updateBeforeValues()

    def updateBeforeValues(self):
        self.min_before = []
        self.max_before = []
        for value in self.values:
            self.min_before.append(value.getMinValue())
            self.max_before.append(value.getMaxValue())

    def isFilterModified(self):

        for index in range(len(self.values)):
            if self.values[index].getMinValue() != self.min_before[index]:
                return True
            if self.values[index].getMaxValue() != self.max_before[index]:
                return True
        return False

    def getListValues(self):

        max_list = []
        min_list = []
        for fil in self.values:
            max_list.append(str(fil.getMaxValue()))
            min_list.append(str(fil.getMinValue()))
        return ','.join(max_list), ','.join(min_list)


import os

import matplotlib.pyplot as plt

def plot_result(df, scenario_id):
    plt.figure()
    plt.title(f"Scenario {scenario_id}")
    plt.plot(df.s0, label='not_infected')
    plt.plot(df.s1, label="infected")
    plt.plot(df.s2, label="recovered")
    plt.plot(df.s3, label="dead")
    plt.xlabel("Step")
    plt.ylabel("Count")
    plt.legend()
    plt.savefig(
        os.path.join(
            os.path.join(os.path.dirname(os.path.dirname(__file__)), "data/output"),
            f"Mesa_PopulationInfection_S{scenario_id}" + ".png"
        ),
        dpi=200,
        format="PNG",
    )


import argparse
import json
import os
from collections import Counter

import numpy as np
from pandas.io.json import to_json
from sklearn.cluster import DBSCAN

from utils.dataset_utils import get_train_list, get_test_list
from utils.graph_similarity_utils import convert_graph_to_vector, get_feature_vector
from utils.graph_utils import get_removed_backed_graph, get_opcode_sequence
from utils.oep_utils import get_oep_dataset_2, get_preceding_oep

parser = argparse.ArgumentParser()
parser.add_argument('--mode', default="evaluation", type=str)
parser.add_argument('--packer_names', nargs="+", default=["upx"])
parser.add_argument('--file_name', default="accesschk.exe", type=str)
parser.add_argument('--sample_files', nargs="+",
                    default=["AccessEnum.exe", "Cacheset.exe", "ADInsight.exe", "ADExplorer.exe"])
parser.add_argument('--train_path', default="data/train.txt", type=str)
parser.add_argument('--first_k', default=3, type=int)
# Get the arguments
args = parser.parse_args()
data_folder_path = "data"
train_list = get_train_list() + get_test_list()
oep_dictionary_2 = get_oep_dataset_2()

def get_packer_name_and_filename(packer_name_file_name):
    packer_name_of_file, file_name = packer_name_file_name.strip().split("_")[0], "_".join(
        packer_name_file_name.strip().split("_")[1:])
    return packer_name_of_file, file_name

def frequency_feature_vecter_computation(packer_name, packed_files):
    print("Process packer: {}".format(packer_name))
    data = {}
    merged_unique_labels = []
    opcode_sequence = {}
    for packed_file in packed_files:
        packer_name_by_file, file_name = get_packer_name_and_filename(packed_file)
        packed_dot_file = os.path.join(data_folder_path, "asm_cfg", packer_name_by_file,
                                       "{}_model.dot".format(packed_file))
        oep_address = oep_dictionary_2[packed_file]
        print("packed_file = {}, oep_address = {}".format(packed_file, oep_address))
        preceding_oep, msg = get_preceding_oep(packed_dot_file, oep_address)
        if not preceding_oep:
            print("Packer: {}, file_name: {}, error: {}".format(packer_name_by_file, packed_file, msg))
            continue
        packed_graph = get_removed_backed_graph(packer_name_by_file, file_name)
        node_list_packed_file, node_labels_packed_file, original_labels_packed_file, _ = convert_graph_to_vector(
            packed_graph,
            address=preceding_oep)

        data[packed_file] = Counter(list(node_labels_packed_file.values()) + original_labels_packed_file)
        opcode_sequence[packed_file] = get_opcode_sequence(packed_graph, preceding_oep)
        merged_unique_labels = sorted(
            list(set(merged_unique_labels + list(node_labels_packed_file.values()) + original_labels_packed_file)))

    return data, opcode_sequence, merged_unique_labels

def standard_generation(packed_files, opcode_sequence, labels, X, merged_unique_labels, first_k=5):
    standard_feature_vectors = {}
    n_sample_of = {}
    opcode_sequence_of_label = {}

    # for packed_file in packed_files:
    #     _, file_name = get_packer_name_and_filename(packed_file)

    for idx in range(len(packed_files)):
        label = str(labels[idx])
        # print("label = {}".format(label))
        if label == "-1":
            continue
        # print("pass: {}".format(type(label)))
        if not label in opcode_sequence_of_label:
            opcode_sequence_of_label[label] = []

        _, file_name = get_packer_name_and_filename(packed_files[idx])
        opcode_sequence_of_label[label].append(opcode_sequence[packed_files[idx]])

        if label in n_sample_of:
            n_sample_of[label] += 1
        else:
            n_sample_of[label] = 1

        if not (label in standard_feature_vectors):
            standard_feature_vectors[label] = {}

        for idy, label_of_node in enumerate(merged_unique_labels):
            if not (label_of_node in standard_feature_vectors[label]):
                standard_feature_vectors[label][label_of_node] = 0.0
            standard_feature_vectors[label][label_of_node] += X[idx][idy]
    # Check condition opcode sequence in group have to have the same sequence > 0
    for cluster_id, opcode_sequences in opcode_sequence_of_label.items():
        for idx in range(len(opcode_sequences)):
            if opcode_sequences[idx][:first_k] != opcode_sequences[0][:first_k]:
                return standard_feature_vectors, opcode_sequence_of_label, None

    # for cluster_id in opcode_sequence_of_label.keys():
    #     for cluster_other_id in opcode_sequence_of_label.keys():
    #         if cluster_other_id != cluster_id:
    #             if opcode_sequence_of_label[cluster_other_id][0][:first_k] == opcode_sequence_of_label[cluster_id][0][
    #                                                                           :first_k]:
    #                 return standard_feature_vectors, opcode_sequence_of_label, 1
    # only check other groups

    return standard_feature_vectors, opcode_sequence_of_label, n_sample_of

def construct_standard_vector(packer_name, packed_files):
    print("Process packer: {}".format(packer_name))
    data, opcode_sequence, merged_unique_labels = frequency_feature_vecter_computation(packer_name, packed_files)
    print(opcode_sequence)
    X = []
    idx = 0
    packer_name_list = []
    for packed_file in packed_files:
        _, file_name = get_packer_name_and_filename(packed_file)

        try:
            feature_vector = get_feature_vector(data[packed_file], merged_unique_labels)

            print(feature_vector)
            X.append(feature_vector)
            packer_name_list.append(_)
            idx += 1
        except Exception as e:
            pass
    X = np.asarray(X)
    eps_default = 0.3
    while True:
        print("esp = {}".format(eps_default))
        if eps_default <= 0:
            break
        clustering = DBSCAN(eps=eps_default, min_samples=2, metric="cosine").fit(X)
        labels = clustering.labels_
        cluster_by_idx = {}
        for idx, packer_name_iter in enumerate(packer_name_list):
            print("packer name: {}, {}".format(packer_name_iter, labels[idx]))
            if not (labels[idx] in cluster_by_idx):
                cluster_by_idx[labels[idx]] = []
            cluster_by_idx[labels[idx]].append(packer_name_iter)

        not_cross = True

        nb_of_class = 0
        for key in cluster_by_idx.keys():
            if key == "-1" or key == -1:
                continue
            nb_of_class += 1
        for key, value in cluster_by_idx.items():
            if key == "-1" or key == -1:
                continue
            if len(set(value)) != 1:
                not_cross = False
                break
        print("eps = {}, not cross: {}, # of class = {}".format(eps_default, not_cross, nb_of_class))
        standard_feature_vectors, opcode_sequence_of_label, n_sample_of = standard_generation(packed_files,
                                                                                opcode_sequence,
                                                                                labels, X,
                                                                                merged_unique_labels)
        if n_sample_of is None:
            eps_default -= 0.01
        else:
            optimal_standard_feature_vectors = standard_feature_vectors
            optimal_opcode_sequence_of_label = opcode_sequence_of_label
            optimal_n_sample_of = n_sample_of
            break

    assert X.shape[0] == len(packed_files)
    for label in optimal_standard_feature_vectors.keys():
        for idx, label_of_node in enumerate(merged_unique_labels):
            optimal_standard_feature_vectors[label][label_of_node] /= optimal_n_sample_of[label]

    # Save end-of-sequence
    with open("configs/end_of_unpacking_sequence_mixpacker.txt", "a") as f:
        for label, opcode_sequences in optimal_opcode_sequence_of_label.items():
            print("label sequence = {}".format(label))
            for opcode_sequence in opcode_sequences:
                print(opcode_sequence)
            max_length = min([len(seq) for seq in opcode_sequences])
            is_diff = False
            for idx in range(0, max_length):
                opcode = opcode_sequences[0][idx]
                for opcode_sequence in opcode_sequences:
                    if opcode_sequence[idx] != opcode:
                        is_diff = True
                        break
                if is_diff:
                    line = "_".join(opcode_sequences[0][:idx])
                    f.writelines("{},{}\n".format(packer_name, line))
                    break
            if not is_diff:
                line = "_".join(opcode_sequences[0][:max_length])
                f.writelines("{},{}\n".format(packer_name, line))
    return optimal_standard_feature_vectors

def main():
    train_of = {}

    for line in train_list:
        packer_name_of_file, file_name = get_packer_name_and_filename(line.strip())
        if packer_name_of_file != "aspack":
            continue
        if not (packer_name_of_file in train_of):
            train_of[packer_name_of_file] = []
        train_of[packer_name_of_file].append(line.strip())

    packed_all = []
    for packer_name, packed_files in train_of.items():
        packed_all += packed_files
    print(len(packed_all))
    standard_feature_vectors = construct_standard_vector("all", packed_all)
    # print(standard_feature_vectors)
    # with open("configs/standard_feature_vectors_mixed/{}.json".format(packer_name), "w") as outfile:
    #     json.dump(standard_feature_vectors, outfile, indent=4)

if __name__ == '__main__':
    main()


from metric.recall_at_k import RecallAtK
from dataloader.mamo_dataset import MamoDataset
from validator import Validator
from torch.utils.data import DataLoader
from tests.integration.mocks.mock_models import MockAllZeros
from tests.integration.mocks.mock_models import MockNoChange
from tests.integration.mocks.mock_models import MockOpposite
from tests.integration.mocks.mock_models import MockShiftRightByOne
from tests.integration.mocks.mock_loss import MSELoss
import numpy as np

# Packages needed to run test:
# os
# numpy
# torch
# pytest

# Variables
# Mock dataset
input_data = np.array([[1, 0, 0, 0, 0, 0],
                       [0, 1, 0, 0, 0, 0],
                       [0, 0, 1, 0, 0, 0],
                       [0, 0, 0, 1, 0, 0],
                       [0, 0, 0, 0, 1, 0],
                       [0, 0, 0, 0, 0, 1]])
input_data = input_data.astype(float)

# Test demonstrating mock all zeros model to show missing
# metrics or missing objectives
def test_validator_mock_all_zeros_model():
    mock_dataset = MamoDataset(input_data, input_data.copy())
    mock_dataloader = DataLoader(mock_dataset, batch_size=1,
                                 shuffle=False, drop_last=False)
    v_all_zeros = Validator(MockAllZeros(), mock_dataloader,
                            [RecallAtK(1)], None)
    results = v_all_zeros.evaluate()
    assert isinstance(results, tuple)
    assert isinstance(results[0], list)
    assert(results[0][0] == 0)
    assert isinstance(results[1], list)
    assert(results[1] == [])
    v_all_zeros = Validator(MockAllZeros(), mock_dataloader,
                            None, [MSELoss()])
    results = v_all_zeros.evaluate()
    assert isinstance(results, tuple)
    assert isinstance(results[0], list)
    assert(results[0] == [])
    assert isinstance(results[1], list)
    mse = np.mean(input_data)
    assert(round(results[1][0], 2) == round(mse, 2))
    assert(round(v_all_zeros.combine_objectives(results[1]), 2)
           == round(mse, 2))

# Test demonstrating mock no change model
# Recall is 0 as we are recommending already chosen elements
def test_validator_mock_no_change_model():
    mock_dataset = MamoDataset(input_data, input_data.copy())
    mock_dataloader = DataLoader(mock_dataset, batch_size=1,
                                 shuffle=False, drop_last=False)
    v_no_change = Validator(MockNoChange(), mock_dataloader,
                            [RecallAtK(1)], [MSELoss()])
    results = v_no_change.evaluate()
    assert isinstance(results, tuple)
    assert isinstance(results[0], list)
    assert(results[0][0] == 0)
    assert isinstance(results[1], list)
    # Removing chosen elements -so:
    mse = np.mean(input_data)
    assert(round(results[1][0], 2) == round(mse, 2))
    assert(round(v_no_change.combine_objectives(results[1]), 2)
           == round(mse, 2))

# Test demonstrating mock opposite model
def test_validator_mock_opposite_model():
    mock_dataset = MamoDataset(input_data, input_data.copy())
    mock_dataloader = DataLoader(mock_dataset, batch_size=1,
                                 shuffle=False, drop_last=False)
    v_opposite = Validator(MockOpposite(), mock_dataloader,
                           [RecallAtK(1)], [MSELoss()])
    results = v_opposite.evaluate()
    assert isinstance(results, tuple)
    assert isinstance(results[0], list)
    assert(results[0][0] == 0)
    assert isinstance(results[1], list)
    assert(results[1][0] == 1)
    assert(v_opposite.combine_objectives(results[1]) == 1)

# Test demonstrating mock shift right by one model
def test_validator_mock_shift_right_by_one_model():
    mock_dataset = MamoDataset(input_data, np.roll(input_data.copy(),
                               shift=1, axis=1))
    mock_dataloader = DataLoader(mock_dataset, batch_size=1,
                                 shuffle=False, drop_last=False)
    v_shift_right = Validator(MockShiftRightByOne(), mock_dataloader,
                              [RecallAtK(1)], [MSELoss()])
    results = v_shift_right.evaluate()
    assert isinstance(results, tuple)
    assert isinstance(results[0], list)
    assert(results[0][0] == 1)
    assert isinstance(results[1], list)
    assert(results[1][0] == 0)
    assert(v_shift_right.combine_objectives(results[1]) == 0)


import discord
import os
import random
import youtube_module
import pyshorteners as sh
import harvester
import insta_follower
from django.core.validators import URLValidator
from dotenv import load_dotenv
from discord.ext.commands import Bot
from discord.ext import commands

load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
validator = URLValidator()
s = sh.Shortener()
client = discord.Client()
img = 'https://cdn.discordapp.com/avatars/743381002382082198/e7bbfd903534e2aecec7748e707c3626.webp?size=1024'

@client.event
async def on_ready():
    print(f"{client.user.name} has connected to Discord!")

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(f"Hi {member.name}, welcome to my Discord server!")

bot = commands.Bot(command_prefix="0")

@bot.command(name="yt")
async def youtube(ctx, url):
    await ctx.message.reply("W A I T . . .", delete_after=5)
    link = youtube_module.get_download_link(url)
    response = "link: {}".format(link)
    await ctx.message.reply(response)

@bot.command(name="cc")
@commands.has_role("admin")
async def create_channel(ctx, channel_name,category_name):
    guild = ctx.guild
    existing_channel = discord.utils.get(guild.channels, name=channel_name)
    if not existing_channel:
        print(f"Creating a new channel: {channel_name}")
        await guild.create_text_channel(channel_name)
        await ctx.message.reply("your channel created successfully", delete_after=5)

@bot.command(name="ig")
async def gain_data(ctx, url):
    await ctx.message.reply("its maybe take a moment...", delete_after=5)
    data = harvester.datas(url)
    await ctx.send(file=discord.File('result.txt'))

@bot.command(name="fn")
async def get_insta(ctx, insta_id):
    await ctx.message.reply("W A I T . . .", delete_after=5)
    numbers = insta_follower.get_follower(insta_id)
    response = "Your follower numbers: {}".format(f'{numbers:,}')
    await ctx.message.reply(response)

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.errors.CheckFailure):
        await ctx.send("You do not have the required role for this command.")

bot.run(TOKEN)


from mv import unit
from . import mv_closet_defaults as props_closet

USE_DADO_FOR_LOCK_SHELF = False
USE_DOWELS_FOR_LOCK_SHELF = False
USE_SCREWS_FOR_LOCK_SHELF = False
USE_CAMS_FOR_LOCK_SHELF = True

USE_DADO_FOR_DIVISION = False
USE_DOWELS_FOR_DIVISION = True
USE_SCREWS_FOR_DIVISION = False
USE_CAMS_FOR_DIVISION = False

CORNERNOTCH_TOOL= "101"
CHAMFER_TOOL= "101"

ROUTER_LEAD = unit.inch(.25)
DADO_WIDTH_GAP = unit.inch(.01)
DADO_DEPTH_GAP = unit.inch(.125)
DADO_PANEL_PENETRATION = unit.inch(.25)

ADJ_SHELF_BORE_DEPTH = unit.inch(.5)
ADJ_SHELF_BORE_DIA = 5

DOWEL_DIM_TO_FIRST_AND_LAST_HOLE = unit.inch(1)
DOWEL_DRILL_FACE_DIA = 5
DOWEL_DRILL_FACE_DEPTH = unit.inch(.5)
DOWEL_DRILL_EDGE_DIA = 5
DOWEL_DRILL_EDGE_DEPTH = unit.inch(.5)
DOWEL_DISTANCE_BETWEEN_HOLES = unit.inch(5)

SCREW_DIM_TO_FIRST_AND_LAST_HOLE = unit.inch(1)
SCREW_DRILL_FACE_DIA = 5
SCREW_DRILL_FACE_DEPTH = unit.inch(.5)
SCREW_DRILL_EDGE_DIA = 5
SCREW_DRILL_EDGE_DEPTH = unit.inch(.5)
SCREW_DISTANCE_BETWEEN_HOLES = unit.inch(5)

CAM_EDGE_BORE_DIA = 5
CAM_EDGE_BORE_DEPTH = unit.inch(.5)
CAM_FACE_BORE_DIA = 5
CAM_FACE_BORE_DIA_2 = 20
CAM_FACE_BORE_DEPTH = unit.inch(.5)
CAM_FACE_BORE_DEPTH_2 = unit.inch(.5)
CAM_BACKSET = unit.inch(.354)
CAM_SETBACK_FROM_FRONT_AND_REAR = unit.inch(1)

def add_shelf_machining(shelf,product=None,index=1,cam_face='5'):
    default_props = props_closet.get_scene_props().closet_defaults
    machining = default_props.machining_defaults

    if machining.add_machining:
        if machining.use_associative_drilling:
            if machining.use_cams:
                add_cams(shelf)
            if machining.use_dowels:
                add_dowel_drilling(shelf)
        else:
            add_32mm_shelf_machining(shelf)

def add_associative_cams_for_shelves(part,cam_face='5'):
    default_props = props_closet.get_scene_props().closet_defaults
    machining_props = default_props.machining_defaults

    Width = part.get_var('dim_y','Width')

    tokens = []
    tokens.append(part.add_machine_token('Left Cam Drilling' ,'CAMLOCK','3'))
    tokens.append(part.add_machine_token('Right Cam Drilling' ,'CAMLOCK','4'))

    for token in tokens:
        token[1].hole_locations[0] = machining_props.dim_to_first_hole
        token[1].add_driver(token[0],'hole_locations','fabs(Width)-' + str(machining_props.dim_to_last_hole),[Width],index=1)
        token[1].edge_bore_depth = machining_props.cam_bore_edge_depth
        token[1].edge_bore_dia = machining_props.cam_bore_edge_dia
        token[1].face_bore_depth = machining_props.cam_bore_face_depth
        token[1].face_bore_dia = machining_props.cam_bore_face_dia
        token[1].face_bore_depth_2 = machining_props.cam_depth
        token[1].face_bore_dia_2 = machining_props.cam_dia
        token[1].backset = machining_props.cam_backset
        token[1].cam_face = cam_face

def add_division_machining(division):
    if USE_DADO_FOR_DIVISION:
        add_dado(division)
    if USE_DOWELS_FOR_DIVISION:
        add_dowel_drilling(division)
    if USE_SCREWS_FOR_DIVISION:
        add_screw_drilling(division)
    if USE_CAMS_FOR_DIVISION:
        add_cams(division)

def add_dado(part):

    Part_Thickness = part.get_var('dim_z','Part_Thickness')

    tokens = []
    tokens.append(part.add_machine_token('Left Dado' ,'DADO','3'))
    tokens.append(part.add_machine_token('Right Dado' ,'DADO','4'))

    for token in tokens:
        token[1].lead_in = ROUTER_LEAD
        token[1].lead_out = ROUTER_LEAD
        token[1].beginning_depth = DADO_PANEL_PENETRATION + DADO_DEPTH_GAP
        token[1].add_driver(token[0],'double_pass','Part_Thickness+' + str(DADO_WIDTH_GAP),[Part_Thickness])
        token[1].panel_penetration = DADO_PANEL_PENETRATION

def add_drawer_bottom_dado(part):

    Part_Thickness = part.get_var('dim_z','Part_Thickness')

    tokens = []
    tokens.append(part.add_machine_token('Left Dado' ,'DADO','3'))
    tokens.append(part.add_machine_token('Right Dado' ,'DADO','4'))
    tokens.append(part.add_machine_token('Front Dado' ,'DADO','1'))
    tokens.append(part.add_machine_token('Back Dado' ,'DADO','2'))

    for token in tokens:
        token[1].lead_in = ROUTER_LEAD
        token[1].lead_out = ROUTER_LEAD
        token[1].beginning_depth = DADO_PANEL_PENETRATION + DADO_DEPTH_GAP
        token[1].add_driver(token[0],'double_pass','Part_Thickness+' + str(DADO_WIDTH_GAP),[Part_Thickness])
        token[1].panel_penetration = DADO_PANEL_PENETRATION

def add_cams(part,cam_face='5'):
    Width = part.get_var('dim_y','Width')

    tokens = []
    tokens.append(part.add_machine_token('Left Cam Drilling' ,'CAMLOCK','3'))
    tokens.append(part.add_machine_token('Right Cam Drilling' ,'CAMLOCK','4'))

    for token in tokens:
        token[1].hole_locations[0] = CAM_SETBACK_FROM_FRONT_AND_REAR
        token[1].add_driver(token[0],'hole_locations','fabs(Width)-' + str(CAM_SETBACK_FROM_FRONT_AND_REAR),[Width],index=1)
        token[1].edge_bore_depth = CAM_EDGE_BORE_DEPTH
        token[1].edge_bore_dia = CAM_EDGE_BORE_DIA
        token[1].face_bore_depth = CAM_FACE_BORE_DEPTH
        token[1].face_bore_dia = CAM_FACE_BORE_DIA
        token[1].face_bore_depth_2 = CAM_FACE_BORE_DEPTH_2
        token[1].face_bore_dia_2 = CAM_FACE_BORE_DIA_2
        token[1].backset = CAM_BACKSET
        token[1].cam_face = cam_face

def add_adj_shelf_machining(part,insert):

#     Width = insert.get_var('dim_x','Width')
    Height = insert.get_var('dim_z','Height')
#     Depth = insert.get_var('dim_y','Depth')
    Part_Width = part.get_var('dim_y','Part_Width')
    Part_Z_Loc = part.get_var('loc_z','Part_Z_Loc')
#     Adj_Shelf_Setback = insert.get_var("Adj Shelf Setback")
    Space_From_Front = insert.get_var("Space From Front")
    Space_From_Rear = insert.get_var("Space From Rear")
    Space_From_Top = insert.get_var("Space From Top")
    Space_From_Bottom = insert.get_var("Space From Bottom")
    Shelf_Hole_Spacing = insert.get_var("Shelf Hole Spacing")
    Shelf_Clip_Gap = insert.get_var("Shelf Clip Gap")
#     Adj_Shelf_Qty = insert.get_var("Adj Shelf Qty")

    tokens = []
    tokens.append(part.add_machine_token('Left Shelf Drilling' ,'SHELF','3'))
    tokens.append(part.add_machine_token('Right Shelf Drilling' ,'SHELF','4'))

    for token in tokens:
        token[1].add_driver(token[0],'space_from_bottom','Part_Z_Loc-Space_From_Bottom',[Part_Z_Loc,Space_From_Bottom])
        token[1].add_driver(token[0],'dim_to_first_row','Space_From_Front',[Space_From_Front])
        token[1].face_bore_depth = ADJ_SHELF_BORE_DEPTH
        token[1].add_driver(token[0],'space_from_top','Height-Part_Z_Loc-Space_From_Top',[Height,Part_Z_Loc,Space_From_Top])
        token[1].add_driver(token[0],'dim_to_second_row','fabs(Part_Width)-Space_From_Rear',[Part_Width,Space_From_Rear])
        token[1].face_bore_dia = ADJ_SHELF_BORE_DIA
        token[1].add_driver(token[0],'shelf_hole_spacing','Shelf_Hole_Spacing',[Shelf_Hole_Spacing])
        token[1].add_driver(token[0],'shelf_clip_gap','Shelf_Clip_Gap',[Shelf_Clip_Gap])
        token[1].reverse_direction = False

def add_32mm_shelf_machining(part):
    default_props = props_closet.get_scene_props().closet_defaults
    machining = default_props.machining_defaults

    Width = part.get_var('dim_y','Width')
    Length = part.get_var('dim_x','Length')
    Is_Locked_Shelf = part.get_var('Is Locked Shelf')
    Drill_On_Top = part.get_var('Drill On Top')
    Remove_Left_Holes = part.get_var('Remove Left Holes')
    Remove_Right_Holes = part.get_var('Remove Right Holes')

    obj, left_token = part.add_machine_token('Left Drilling' ,'BORE','5')
    left_token.add_driver(obj,'is_disabled','IF(Is_Locked_Shelf,IF(Remove_Left_Holes,True,False),True)',[Is_Locked_Shelf,Remove_Left_Holes])
    left_token.add_driver(obj,'face','IF(Drill_On_Top,5,4)',[Drill_On_Top])
    left_token.dim_in_x = machining.cam_backset
    left_token.dim_in_y = machining.dim_to_first_hole
    left_token.dim_in_z = machining.cam_depth
    left_token.face_bore_dia = machining.cam_dia
    left_token.end_dim_in_x  = machining.cam_backset
    left_token.add_driver(obj,'end_dim_in_y','fabs(Width)-' + str(machining.dim_to_last_hole),[Width])
    left_token.add_driver(obj,'distance_between_holes','fabs(Width)-(' + str(machining.dim_to_first_hole+machining.dim_to_last_hole) + ')',[Width])
    left_token.associative_dia = 0
    left_token.associative_depth = 0

    obj, right_token = part.add_machine_token('Right Drilling' ,'BORE','5')
    right_token.add_driver(obj,'is_disabled','IF(Is_Locked_Shelf,IF(Remove_Right_Holes,True,False),True)',[Is_Locked_Shelf,Remove_Right_Holes])
    right_token.add_driver(obj,'face','IF(Drill_On_Top,5,4)',[Drill_On_Top])
    right_token.add_driver(obj,'dim_in_x','Length-' + str(machining.cam_backset),[Length])
    right_token.dim_in_z = machining.cam_depth
    right_token.dim_in_y = machining.dim_to_first_hole
    right_token.face_bore_dia = machining.cam_dia
    right_token.add_driver(obj,'end_dim_in_x','Length-' + str(machining.cam_backset),[Length])
    right_token.add_driver(obj,'end_dim_in_y','fabs(Width)-' + str(machining.dim_to_last_hole),[Width])
    right_token.add_driver(obj,'distance_between_holes','fabs(Width)-(' + str(machining.dim_to_first_hole+machining.dim_to_last_hole) + ')',[Width])
    right_token.associative_dia = 0
    right_token.associative_depth = 0

def add_dowel_drilling(part):
    Width = part.get_var('dim_y','Width')

    tokens = []
    tokens.append(part.add_machine_token('Left Dado Drilling' ,'CONST','3'))
    tokens.append(part.add_machine_token('Right Dado Drilling' ,'CONST','4'))

    for token in tokens:
        token[1].dim_to_first_const_hole = DOWEL_DIM_TO_FIRST_AND_LAST_HOLE
        token[1].add_driver(token[0],'dim_to_last_const_hole','fabs(Width)-' + str(DOWEL_DIM_TO_FIRST_AND_LAST_HOLE),[Width])
        token[1].edge_bore_depth = DOWEL_DRILL_EDGE_DEPTH
        token[1].edge_bore_dia = DOWEL_DRILL_EDGE_DIA
        token[1].face_bore_depth = DOWEL_DRILL_FACE_DEPTH
        token[1].face_bore_dia = DOWEL_DRILL_FACE_DIA
        token[1].distance_between_holes = DOWEL_DISTANCE_BETWEEN_HOLES

def add_screw_drilling(part):
    Width = part.get_var('dim_y','Width')

    tokens = []
    tokens.append(part.add_machine_token('Left Screw Drilling' ,'CONST','3'))
    tokens.append(part.add_machine_token('Right Screw Drilling' ,'CONST','4'))

    for token in tokens:
        token[1].dim_to_first_const_hole = SCREW_DIM_TO_FIRST_AND_LAST_HOLE
        token[1].add_driver(token[0],'dim_to_last_const_hole','fabs(Width)-' + str(SCREW_DIM_TO_FIRST_AND_LAST_HOLE),[Width])
        token[1].edge_bore_depth = SCREW_DRILL_EDGE_DEPTH
        token[1].edge_bore_dia = SCREW_DRILL_EDGE_DIA
        token[1].face_bore_depth = SCREW_DRILL_FACE_DEPTH
        token[1].face_bore_dia = SCREW_DRILL_FACE_DIA
        token[1].distance_between_holes = SCREW_DISTANCE_BETWEEN_HOLES

def add_rear_notches(part,product):
    loc_z = part.get_var("loc_z")
    First_Rear_Notch_Height = product.get_var('First Rear Notch Height')
    First_Rear_Notch_Depth = product.get_var('First Rear Notch Depth')
    Second_Rear_Notch_Height = product.get_var('Second Rear Notch Height')
    Second_Rear_Notch_Depth = product.get_var('Second Rear Notch Depth')
    Panel_Thickness = product.get_var('Panel Thickness')

    first_notch = part.add_machine_token('First Rear Notch' ,'CORNERNOTCH','5','3')
    first_notch[1].add_driver(first_notch[0],'is_disabled','IF(OR(First_Rear_Notch_Height==0,loc_z>INCH(1)),True,False)',[First_Rear_Notch_Height,loc_z])
    first_notch[1].add_driver(first_notch[0],'dim_in_x','First_Rear_Notch_Height',[First_Rear_Notch_Height])
    first_notch[1].add_driver(first_notch[0],'dim_in_y','First_Rear_Notch_Depth',[First_Rear_Notch_Depth])
    first_notch[1].add_driver(first_notch[0],'dim_in_z','Panel_Thickness',[Panel_Thickness])
    first_notch[1].lead_in = ROUTER_LEAD
    first_notch[1].tool_number = CORNERNOTCH_TOOL

    second_notch = part.add_machine_token('Second Rear Notch' ,'CORNERNOTCH','5','3')
    second_notch[1].add_driver(second_notch[0],'is_disabled','IF(OR(Second_Rear_Notch_Height==0,loc_z>INCH(1)),True,False)',[Second_Rear_Notch_Height,loc_z])
    second_notch[1].add_driver(second_notch[0],'dim_in_x','Second_Rear_Notch_Height',[Second_Rear_Notch_Height])
    second_notch[1].add_driver(second_notch[0],'dim_in_y','First_Rear_Notch_Depth+Second_Rear_Notch_Depth',[First_Rear_Notch_Depth,Second_Rear_Notch_Depth])
    second_notch[1].add_driver(second_notch[0],'dim_in_z','Panel_Thickness',[Panel_Thickness])
    second_notch[1].lead_in = ROUTER_LEAD
    second_notch[1].tool_number = CORNERNOTCH_TOOL

def add_top_chamfers(part,product):
    Front_Angle_Height = product.get_var('Front Angle Height')
    Front_Angle_Depth = product.get_var('Front Angle Depth')
    Rear_Angle_Height = product.get_var('Rear Angle Height')
    Rear_Angle_Depth = product.get_var('Rear Angle Depth')
    Panel_Thickness = product.get_var('Panel Thickness')

    front_chamfer = part.add_machine_token('Front Chamfer' ,'CHAMFER','5','7')
    front_chamfer[1].add_driver(front_chamfer[0],'is_disabled','IF(Front_Angle_Height==0,True,False)',[Front_Angle_Height])
    front_chamfer[1].add_driver(front_chamfer[0],'dim_in_x','Front_Angle_Height',[Front_Angle_Height])
    front_chamfer[1].add_driver(front_chamfer[0],'dim_in_y','Front_Angle_Depth',[Front_Angle_Depth])
    front_chamfer[1].add_driver(front_chamfer[0],'dim_in_z','Panel_Thickness',[Panel_Thickness])
    front_chamfer[1].lead_in = ROUTER_LEAD
    front_chamfer[1].tool_number = CHAMFER_TOOL

    rear_chamfer = part.add_machine_token('Rear Chamfer' ,'CHAMFER','5','5')
    rear_chamfer[1].add_driver(rear_chamfer[0],'is_disabled','IF(Rear_Angle_Height==0,True,False)',[Rear_Angle_Height])
    rear_chamfer[1].add_driver(rear_chamfer[0],'dim_in_x','Rear_Angle_Height',[Rear_Angle_Height])
    rear_chamfer[1].add_driver(rear_chamfer[0],'dim_in_y','Rear_Angle_Depth',[Rear_Angle_Depth])
    rear_chamfer[1].add_driver(rear_chamfer[0],'dim_in_z','Panel_Thickness',[Panel_Thickness])
    rear_chamfer[1].lead_in = ROUTER_LEAD
    rear_chamfer[1].tool_number = CHAMFER_TOOL


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

import os

import pandas as pd

from patstat import csv_files_querying as cfq
from patstat import dtypes_patstat_declaration as types

# directory where the files are
DATA_PATH = os.getenv('MOUNTED_VOLUME_TEST')

COL = {"patent_appln_columns": ["appln_id", "appln_kind", "earliest_filing_year", "ipr_type", 'earliest_publn_year'],
       "person_columns": ["person_id", "person_ctry_code"],
       "usecols": ["appln_id", "docdb_family_id"]}

DICT = {
    "tls201_post2010": {'sep': ',', 'chunksize': 20000000, 'usecols': COL.get("patent_appln_columns"),
                        'dtype': types.tls201_types},
    "tls206_french_person_id": {'sep': ',', 'chunksize': 5000000, 'usecols': COL.get("person_columns"),
                                'dtype': types.tls206_types},
    "tls207_get_scope_applications": {'sep': ',', 'chunksize': 20000000, 'dtype': types.tls207_types},
    "tls201_families_from_set_patent": {'sep': ',', 'chunksize': 20000000, 'dtype': types.tls201_types,
                                        'usecols': COL.get("usecols")},
    "tls201_patent_from_set_family": {'sep': ',', 'chunksize': 2000000, 'dtype': types.tls201_types}
}

# tls 201 : get ID from only patent post 2010 (9999 is for missing date)
def get_patent_post2010_appln_id(t201directory: str) -> pd.DataFrame:
    """
    :param t201directory: takes directory where tls201 files are
    :return: filtered dataframe with only one column "appln_id"
    """
    print("Start get ID patent post 2010")
    dict_param_load = DICT.get("tls201_post2010")

    def query_patent_applications_t201(chunk_t201: pd.DataFrame) -> pd.DataFrame:
        """
        :param chunk_t201: a chunk from CSV
        :return: dataframe with filtered "appln_id"
        """
        patent_applications_query = chunk_t201[(chunk_t201['appln_kind'].isin(['A ', 'W ', 'P '])) &
                                               (chunk_t201['earliest_filing_year'] < 9999) &
                                               (chunk_t201['earliest_publn_year'] < 9999) &
                                               (chunk_t201['earliest_filing_year'] > 2009) &
                                               (chunk_t201['ipr_type'] == "PI")][['appln_id']]
        return patent_applications_query

    patent_appln_chunk = cfq.multi_csv_files_querying(t201directory, query_patent_applications_t201, dict_param_load)
    print("End get ID patent post 2010")
    return patent_appln_chunk

# tls 206 : ne garde que les ID des personnes "françaises"
def get_french_person_id(t206directory: str) -> pd.DataFrame:
    """
    :param t206directory: directory where tls206 files are
    :return: a dataframe with only one column "person_id"
    """
    print("Start get French person ID")
    dict_param_load = DICT.get("tls206_french_person_id")

    def query_french_persons_t206(chunk_t206: pd.DataFrame) -> pd.DataFrame:
        """
        :param chunk_t206: a chunk of read_csv and list of codes fro France in Patstat
        :return: only the rows of the dataframe with French codes
        """
        # liste des pays français avec DOM-TOM
        list_french_codes = ["FR", "GP", "GF", "MQ", "RE", "YT", "PM", "MF", "BL", "WF", "TF", "NC", "PF"]
        french_query = chunk_t206.loc[
            chunk_t206['person_ctry_code'].isin(list_french_codes), ['person_id']].drop_duplicates()
        return french_query

    french_chunk = cfq.multi_csv_files_querying(t206directory, query_french_persons_t206, dict_param_load)
    french_chunk = french_chunk[["person_id"]]
    print("End get French person ID")
    return french_chunk

# tls 207 : charge les applications et ne garde que celles dont l'application des personnes qui demandent le brevet

def get_scope_applications(t207directory: str, patent_app_id: pd.DataFrame, french_id: pd.DataFrame) -> pd.DataFrame:
    """
    :param t207directory: directory where tls 207 files are
    :param patent_app_id: result from get_patent_post2010_appln_id - only patent post 2010
    :param french_id: result from get_french_person_id - only French patent
    :return: a dataframe with patent ID post 2010 from only French persons
    """
    print("Start get scope applications")

    def chunk_query(chunk: pd.DataFrame) -> pd.DataFrame:
        """
        :param chunk: a chunk from CSV
        :return: a dataframe with only applicants, not inventors or others...
        """
        chunk_trie = chunk[(chunk['applt_seq_nr'] > 0)]
        return chunk_trie

    dict_param_load = DICT.get("tls207_get_scope_applications")
    _scope_app = cfq.multi_csv_files_querying(t207directory, chunk_query, dict_param_load)
    _scope_app = _scope_app[["person_id", "appln_id"]]
    scope_patent = pd.merge(patent_app_id, _scope_app, how="inner", on="appln_id", sort=False,
                            validate="1:m")
    _scope_applications = pd.merge(french_id, scope_patent, how="inner", on="person_id", sort=False,
                                   validate="1:m")
    print("End get scope applications")
    return _scope_applications

# tls 201
def get_families_from_set_patent(t201directory: str, _set_application: list) -> pd.DataFrame:
    """
    :param t201directory: directory where tls 201 files are
    :param _set_application: application ID from get_scope_applications
    :return: a dataframe with families for the application ID
    """
    print("Start get families from set patent")

    def chunk_query(chunk: pd.DataFrame) -> pd.DataFrame:
        """
        :param chunk: a chunk from CSV
        :return: a dataframe with only one column docdb family ID which correspond to application ID
        """
        chunk_trie = chunk[(chunk['appln_id'].isin(_set_application))][
            ['docdb_family_id']].drop_duplicates()
        return chunk_trie

    dict_param_load = DICT.get("tls201_families_from_set_patent")
    _family_scope = cfq.multi_csv_files_querying(t201directory, chunk_query, dict_param_load)
    print("End get families from set patent")
    return _family_scope

def get_patent_from_set_family(t201directory: str, fam_sc: pd.DataFrame, colfilter: str,
                               dict_param_load: dict) -> pd.DataFrame:
    """

    :param t201directory: directory where tls 201 files are
    :param fam_sc: df where filtering info are
    :param colfilter: column which serves as a filter
    :param dict_param_load: dictionary with loading parameters
    :return: load table with filtered values
    """

    print("Start get patent from set family")

    _patent_scope = cfq.filtering(t201directory, fam_sc, colfilter, dict_param_load)

    print("End get patent from set family")
    return _patent_scope

def get_patentscope():
    # set working directory
    os.chdir(DATA_PATH)

    patent_appln_id = get_patent_post2010_appln_id("tls201")
    french_person_id = get_french_person_id("tls206")
    scope_applications = get_scope_applications("tls207", patent_appln_id, french_person_id)
    family_scope = get_families_from_set_patent("tls201", scope_applications['appln_id'])
    family_scope.to_csv("docdb_family_scope.csv", sep='|', index=False)
    patent_scope = get_patent_from_set_family("tls201", family_scope, "docdb_family_id",
                                              DICT.get("tls201_patent_from_set_family"))
    patent_scope["key_appln_nr"] = patent_scope["appln_auth"] + patent_scope["appln_nr"] + \
                                   patent_scope["appln_kind"] + patent_scope["receiving_office"]
    patent_scope.to_csv("patent_scope.csv", sep='|', index=False)


# This code is for experimental purpose.
# DO NOT USE THIS IN PRODUCTION.
# pylint: disable=C0103

import sys
import math
from Crypto.Util import number

def xy_to_zw(mo: int, point: tuple[int, int]) -> tuple[int, int]:
    (x, y) = point
    w = number.inverse(-y, mo)
    z = x * w % mo
    return (z, w)

class ECZW:
    def __init__(self, mo: int, a1: int, a2: int, a3: int, a4: int, a6: int):
        """y^2 + a1 * x * y + a3 * y = x^3 + a2 * x^2 + a4 * x + a6
        w = z^3 + a1 * z * w + a2 * z^2 * w + a3 * w^2 + a4 * z * w^2 + a6 * w^3
        """
        self.mo = mo
        self.a1 = a1
        self.a2 = a2
        self.a3 = a3
        self.a4 = a4
        self.a6 = a6

    @staticmethod
    def simplified(mo: int, a: int, b: int):
        """Simplified form: y^2 = x^3 + a * x + b
        w = z^3 + a * z * w^2 + b * w^3
        """
        return ECZW(mo, 0, 0, 0, a, b)

    def is_on(self, point: tuple[int, int]) -> bool:
        return self.g(point) == 0

    def g(self, point: tuple[int, int]) -> bool:
        mo = self.mo
        a1 = self.a1
        a2 = self.a2
        a3 = self.a3
        a4 = self.a4
        a6 = self.a6
        (z, w) = point
        rhs = z * z * z + a1 * z * w + a2 * z * z * w + a3 * w * w + a4 * z * w * w + a6 * w * w * w
        return (rhs - w) % mo

    def g_z(self, point: tuple[int, int]) -> int:
        """∂g/∂z(point)
        """
        (z, w) = point
        mo = self.mo
        a1 = self.a1
        a2 = self.a2
        a4 = self.a4
        return (3 * z * z + a1 * w + 2 * a2 * z * w + a4 * w * w) % mo

    def g_w(self, point: tuple[int, int]) -> int:
        """∂g/∂w(point)
        """
        (z, w) = point
        mo = self.mo
        a1 = self.a1
        a2 = self.a2
        a3 = self.a3
        a4 = self.a4
        a6 = self.a6
        return (a1 * z + a2 * z * z + 2 * a3 * w + 2 * a4 * z * w + 3 * a6 * w * w - 1) % mo

    def inv(self, p: tuple[int, int]) -> tuple[int, int]:
        """Computes -p
        """
        mo = self.mo
        a1 = self.a1
        a3 = self.a3
        (z, w) = p
        invden = number.inverse(a1 * z + a3 * w - 1, mo)
        return (z * invden % mo, w * invden % mo)

    def add(self, p1: tuple[int, int], p2: tuple[int, int]) -> tuple[int, int]:
        """Computes p1 + p2
        """
        mo = self.mo
        a1 = self.a1
        a2 = self.a2
        a3 = self.a3
        a4 = self.a4
        a6 = self.a6
        (z1, w1) = p1
        (z2, w2) = p2
        lam = None
        invlam = None
        if z1 == z2 and w1 == w2:
            nom = self.g_z(p1)
            den = -self.g_w(p1) % mo
            if math.gcd(den, mo) != 1:
                invlam = den * number.inverse(nom, mo) % mo
            else:
                lam = nom * number.inverse(den, mo) % mo
        elif math.gcd(abs(z2 - z1), mo) != 1:
            invlam = (z2 - z1) * number.inverse(w2 - w1, mo) % mo
        else:
            lam = (w2 - w1) * number.inverse(z2 - z1, mo) % mo
        if lam is not None:
            nu = (w1 - z1 * lam) % mo
            zsum = -(a1 * lam + a2 * nu + a3 * lam * lam + 2 * a4 * lam * nu + 3 * a6 * lam * lam * nu) \
                * number.inverse(1 + lam * (a2 + lam * (a4 + a6 * lam)), mo)
            z3 = -(z1 + z2 - zsum) % mo
            w3 = (lam * z3 + nu) % mo
        elif invlam is not None:
            mu = (z1 - invlam * w1) % mo
            wsum = -number.inverse(a6 + invlam * (a4 + invlam * (a2 + invlam)), mo) \
                * (a3 + mu * (a4 + 2 * a2 * invlam) + a1 * invlam + 3 * invlam * invlam * mu)
            w3 = -(w1 + w2 - wsum)
            w3 %= mo
            z3 = (invlam * w3 + mu) % mo
        else:
            z = z1
            z3 = z
            # TODO: a6 != 0 must hold
            wsum = (a3 + a4 * z) * number.inverse(-a6, mo) % mo
            w3 = (wsum - w1 - w2) % mo
        return self.inv((z3, w3))

    def mul(self, x: int, p: tuple[int, int]) -> tuple[int, int]:
        """Computes x * p
        """
        result = (0, 0)
        cur = p
        while x > 0:
            if x % 2 == 1:
                result = self.add(result, cur)
            cur = self.add(cur, cur)
            x //= 2
        return result

    def lift(self, less_mo: int, p: tuple[int, int]) -> tuple[int, int]:
        """Hensel lifting to mod less_mo^2
        """
        assert less_mo * less_mo == self.mo
        mo = self.mo
        g_z = self.g_z(p)
        g_w = self.g_w(p)
        (z, w) = p
        if g_z % less_mo != 0:
            newz = (z - self.g(p) * number.inverse(g_z, mo)) % mo
            assert self.is_on((newz, w))
            return (newz, w)
        neww = (w - self.g(p) * number.inverse(g_w, mo)) % mo
        assert self.is_on((z, neww))
        return (z, neww)

def test():
    # y^2 = x^3 + 3 (mod 7), order = 13
    ec = ECZW.simplified(7, 0, 3)
    p = xy_to_zw(7, (1, 2))
    assert ec.mul(13, p) == (0, 0)
    c = (0, 0)
    for i in range(13):
        c = ec.add(c, p)
        assert ec.is_on(c)
    assert c == (0, 0)
    # An example found in https://iacr.org/cryptodb/data/paper.php?pubkey=14320
    mo = 43
    ec = ECZW(mo, 0, -4, 0, -128, -432)
    order = 0
    for i in range(43):
        for j in range(43):
            if ec.is_on((i, j)):
                order += 1
    assert order == 43
    p = xy_to_zw(mo, (0, 16))
    assert ec.is_on(p)
    assert ec.mul(43, p) == (0, 0)
    c = (0, 0)
    for i in range(43):
        c = ec.add(c, p)
        assert ec.is_on(c)

    # Testing of Smart's attack
    mo = 43 * 43
    ec = ECZW(mo, 0, -4, 0, -128, -432) # EC mod p^2
    ec_red = ECZW(43, 0, -4, 0, -128, -432) # reduced mod p
    p = xy_to_zw(43, (0, 16))
    lp = ec.lift(43, p)
    assert ec.is_on(lp)
    for r in range(10, 43):
        q = ec_red.mul(r, p)
        lq = ec.lift(43, q)
        plp = ec.mul(43, lp)
        plq = ec.mul(43, lq)
        v1 = plp[0] // 43
        v2 = plq[0] // 43
        disclog = v2 * number.inverse(v1, 43) % 43
        assert disclog == r

def main():
    if len(sys.argv) >= 2 and sys.argv[1] == "test":
        test()
        return

    mo = 43 * 43
    ec = ECZW(mo, 0, -4, 0, -128, -432) # EC mod p^2
    ec_red = ECZW(43, 0, -4, 0, -128, -432) # reduced mod p
    p = xy_to_zw(43, (0, 16))
    lp = ec.lift(43, p)
    assert ec.is_on(lp)
    q = xy_to_zw(43, (12, 1))
    lq = ec.lift(43, q)
    assert ec.is_on(lq)
    plp = ec.mul(43, lp)
    plq = ec.mul(43, lq)
    v1 = plp[0] // 43
    v2 = plq[0] // 43
    disclog = v2 * number.inverse(v1, 43) % 43
    print(f"discrete log = {disclog}")
    assert ec_red.mul(disclog, p) == q

if __name__ == "__main__":
    main()


from tkinter import Tk, IntVar, Label, PhotoImage, Radiobutton, Button
from random import randint, shuffle

def configure_window():
	window.geometry("800x600")
	window.configure(background='#b3ffff')
	window.title("M A T H   Q U I Z")

def calculate_answer(num1, num2, operator):
	if operator == 0:
		return num1+num2
	elif operator == 1:
		return num1-num2
	else:
		return num1*num2

def add_incorrect_answers(answer):
	answers = []
	answers.append(answer)
	for i in range(4):
		while True:
			r = randint(-6,6)
			ans = answer + r
			if ans not in answers:
				answers.append(ans)
				break
	return answers

def create_ans_radiobutton(answers):
	ans = []
	for i in range(len(answers)):
		ans.append(Radiobutton(window, text=answers[i],
										value=answers[i],
										font=("Arial Bold", 50),
										indicatoron=0,
										variable=user_answer,
										bg="#ffcccc",
										selectcolor="#99ff99",
										width=4))

		padding = Label(window, text=" ", font=("Monospace", 25), background="#b3ffff")
		padding.grid(column=1, row=3)
		shuffle(ans)
		for i in range(len(ans)):
			ans[i].grid(column=i+2, row=3)
		padding.grid(column=1, row=4)

def clicked(answer):
	if (user_answer.get() == answer):
		btn.configure(text=" Correct ")
		ans_label = Label(window, image=correct)
		global current_score
		current_score += 10
		score.config(text="Score: " + str(current_score))
	else:
		ans_label = Label(window, image=incorrect)
		btn.configure(text=" Incorrect ")
	ans_label.grid(column=1, row=8, columnspan=2)
	window.after(1000, game_loop)

def create_ans_button(answer):
	global btn
	btn = Button(window, text="Check Answer", command=lambda:clicked(answer), background='#ffff4d', font=("Monospace",50))
	btn.grid(column=0, row=5, columnspan=7)

def game_loop():
	num1 = randint(1,20)
	num2 = randint(1,20)
	operator = randint(0,2)
	display_question(num1, num2, operator)
	answer = calculate_answer(num1, num2, operator)
	answers = add_incorrect_answers(answer)
	create_ans_radiobutton(answers)
	create_ans_button(answer)

def display_question(num1, num2, operator):
	operators = ["+", "x", "-"]
	question = str(num1) + " " + operators[operator] + " " + str(num2) + " ="
	question = Label(window, text=question, font=("Monospace", 50), background="#b3ffff")
	question.grid(column=1, row=1, columnspan=6, sticky="W")

window = Tk()
configure_window()

user_answer = IntVar()
btn = None
current_score = 0

score = Label(window, text="Score: 0", font=("Monospace",50), background="#b3ffff")
score.grid(column=2, row=8, columnspan=4, sticky='E')

correct = PhotoImage(file="correct.png")
incorrect = PhotoImage(file="incorrect.png")

game_loop()

window.mainloop()

print("hello there")


import torch
import numpy as np

import time

from THHyperIBLT import THHyperIBLT
from fedIBLT import HyperIBLT

def _get_prime(n: int):
    def _is_prime(x):
        for i in range(2, int(np.sqrt(x)) + 1):
            if x % i == 0:
                return False
        return True

    while not _is_prime(n):
        n += 1
    return n

def test_encode_decode(numel):
    device = "cuda" if torch.cuda.is_available() else "cpu"

    NUM_ROW: int = 3
    NUM_COL: int = _get_prime(int(1.25 * numel/NUM_ROW))

    print(f"size of HyperIBLT : num_row = {NUM_ROW}, num_col = {NUM_COL}")

    NUMEL: int = numel
    NUM_BLOCK: int = 20
    MODULO: int = 114514

    tensor = torch.randn(numel, dtype=torch.float32).to(device)

#    index = torch.nonzero(tensor).view(-1)
#    values = tensor[index]
#    index = index.type(torch.int32)

    index = torch.arange(numel, dtype=torch.int32).to(device)
    values = tensor

    encode_table = THHyperIBLT(NUM_ROW, NUM_COL, NUMEL, NUM_BLOCK)

    print("Start of encode")
    start_time = time.perf_counter()
    encode_table.encode(index, values)
    end_time = time.perf_counter()
    print("End of encode")

    print(f"Encode time = {end_time - start_time}")

    results = np.zeros((NUMEL,), dtype=np.float32)
    key_sum = encode_table.key_sum.numpy().astype(np.uint32)
    value_sum = encode_table.value_sum.numpy().astype(np.float32)
    counter = encode_table.counter.numpy().astype(np.uint32)
    hash_bucket = encode_table.hash_bucket.numpy().astype(np.uint32)

    decode_table = HyperIBLT(
      NUM_ROW,
      NUM_COL,
      NUMEL,
      MODULO,
      key_sum,
      value_sum,
      counter,
      hash_bucket
    )

    start_time = time.perf_counter()
    decode_table.decode(results)
    end_time = time.perf_counter()
    print(f"Decode time = {end_time - start_time}")

    print(f"origin tensor = {tensor}")
    print(f"results = {results}")

if __name__ == "__main__":
    test_encode_decode(10_000_000)


# ###############################################################
#                                                               #
# Dean Johnson                                                  #
# ECE351                                                        #
# Lab 3                                                         #
# 2/8/2022                                                      #
#                                                               #
#                                                               #
#################################################################

#Initial code from previous lab with ramp and step functions as well as import scipy and math
import math
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sig
steps = 1e-2 # Define step size
t = np . arange (0 , 20 + steps , steps ) # Add a step size to make sure the
                                         # plot includes 5.0. Since np. arange () only
                                         # goes up to , but doesn ’t include the
                                         # value of the second argument
#Ramp function
t = np.arange(0, 10 + .1, .1)
def ramp(t):
    y = np.zeros(t.shape)

    for i in range(len(t)):
        if t[i] < 0:
            y[i] = 0
        else:
            y[i] = t[i]
    return y

y = ramp(t)

#Step Function
t = np.arange(0, 10 + steps, steps)
def step(t):
    y = np.zeros(t.shape)

    for i in range(len(t)):
        if t[i] < 0:
            y[i] = 0
        else:
            y[i] = 1
    return y

y = step(t)
######## Part 1 #########

#Task 1

#f1(t)=u(t-2)-u(t-9)
t = np . arange (0 , 20 + steps , steps )
def f1(t):
    y=step(t-2)-step(t-9)
    return y
a = f1(t)

#f2(t) =(e^-t)*u(t)
def f2(t):
    y=np.exp(-t)*step(t)
    return y
b=f2(t)

#f3(t) = r(t-2)[u(t-2)-u(t-3)]+r(4-t)[u(t-3)-u(t-4)]
def f3(t):
    y = ramp(t-2)*(step(t-2)-step(t-2))+ramp(4-t)*(step(t-3)-step(t-4))
    return y
c=f3(t)

steps = .1
t = np.arange(0,20+steps,steps)

a = f1(t)
b = f2(t)
c = f3(t)

myFigSize = (20,6)
plt.figure(figsize=myFigSize)

plt.subplot(1,3,1)
plt.plot(t,a,'b')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('f1(t)')

plt.subplot(1,3,2)
plt.plot(t,b,'r')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('f2(t)')

plt.subplot(1,3,3)
plt.plot(t,c, 'g')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('f(t)')
plt.show()

###### Part 2 ####
#Task 1 - user defined convolution function

def convolve(f,h):
    len_f = np.size(f) #size of forcing function
    len_h = np.size(h) #size of impulse response

    #since functions share a commmon start the total length is 1 les than the sum

    sum = np.zeros(len_f+len_h - 1)

    for i in np.arange(len_f):         #at given time in forcing function
        for j in np.arange(len_h):     #at same time in impulse function
            sum[i+j] = sum[i+j] + f[i]*h[j]   #the total sum of previous time with the current time
    return sum

#setting the range
steps = .1
t = np.arange(0,20+steps,steps)
NN = len(t)
tExtended = np.arange(0, 2*t[NN-1]+steps, steps)

a = f1(t)
b = f2(t)
c = f3(t)

#Task 2 - convolution of f1 and f2
conv1 = convolve(a,b)
#verification using scipy.signal.convolve()
verify1 = sig.convolve(a,b)

myFigSize = (20,5)
plt.figure(figsize=myFigSize)
plt.subplot(1,2,1)
plt.plot(tExtended,conv1,'b')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('Task 2 - Convolution of f1 and f2.')

plt.subplot(1,2,2)
plt.plot(tExtended,verify1,'r')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('Verification of f1 and f2.')

#Task 3
conv2 = convolve(b,c)
#verification using scipy.signal.convolve()
verify2 = sig.convolve(b,c)

myFigSize = (20,5)
plt.figure(figsize=myFigSize)
plt.subplot(1,2,1)
plt.plot(tExtended,conv2,'b')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('Task 3 - Convolution of f2 and f3.')

plt.subplot(1,2,2)
plt.plot(tExtended,verify2,'r')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('Verification of f2 and f3.')

#Task 4
conv3 = convolve(a,c)

#verification using scipy.signal.convolve()
verify3 = sig.convolve(a,c)

myFigSize = (20,5)
plt.figure(figsize=myFigSize)
plt.subplot(1,2,1)
plt.plot(tExtended,conv3,'b')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('Task 4 - Convolution of f1 and f3.')

plt.subplot(1,2,2)
plt.plot(tExtended,verify3,'r')
plt.grid(True)
plt.xlabel('time')
plt.ylabel('y')
plt.title('Verification of f1 and f3.')


# -*- coding: utf-8 -*-
#
#  Copyright (c) 2013-present, Anoop Kunchukuttan
#  All rights reserved.
#
#  This source code is licensed under the MIT license found in the
#  LICENSE file in the root directory of this source tree.
#

#Program to transliterate acronyms from one Latin script to Indic languages
#
# @author Anoop Kunchukuttan
#

from indicnlp.transliterate.unicode_transliterate import UnicodeIndicTransliterator
import string
import random

class LatinToIndicAcronymTransliterator(object):

    LATIN_TO_DEVANAGARI_TRANSTABLE = str.maketrans({
        'a':'ए',
        'b':'बी',
        'c':'सी',
        'd':'डी',
        'e':'ई',
        'f':'एफ',
        'g':'जी',
        'h':'एच',
        'i':'आई',
        'j':'जे',
        'k':'के',
        'l':'एल',
        'm':'एम',
        'n':'एन',
        'o':'ओ',
        'p':'पी',
        'q':'क्यू',
        'r':'आर',
        's':'एस',
        't':'टी',
        'u':'यू',
        'v':'वी',
        'w':'डब्ल्यू',
        'x':'एक्स',
        'y':'वाय',
        'z':'जेड',
    })

    # a_unichr=ord('a')
    # alphabet = [ chr(a_unichr+n) for n in range(26) ]
    LATIN_ALPHABET = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    @staticmethod
    def get_transtable():
        return LatinToIndicAcronymTransliterator.LATIN_TO_DEVANAGARI_TRANSTABLE

    @staticmethod
    def transliterate(w,lang):
        return UnicodeIndicTransliterator.transliterate(w.lower().translate(LatinToIndicAcronymTransliterator.LATIN_TO_DEVANAGARI_TRANSTABLE),'hi',lang)

    @staticmethod
    def generate_latin_acronyms(num_acronyms, min_len=2, max_len=6, strategy='random'):
        """
            generate Latin acronyms in lower case
        """

        def sample_acronym(strategy='random'):
            if strategy=='random':
                slen=random.randint(min_len,max_len)
                return ''.join(random.choices(LatinToIndicAcronymTransliterator.LATIN_ALPHABET,k=slen))

        return [ sample_acronym(strategy) for i in range(num_acronyms) ]


import fractions
#Project Euler question 5
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

#gets the solution very slowly (brute force)
def pEQuestion5():
    isDivisible = False
    num = 2
    while isDivisible is False:
        for i in range(1,21):
            if num%i==0 and i == 20:
               return num
            num+=1
            print(num)
    return num

#My alt cuts time in half of thee intial solultion
def alt():
    div =1
    isDivisible = False
    while isDivisible is False:
        for i in range(1,21):
            if (20*div)%i != 0:
                break
            else:
                print(div,i)
        div +=1
    return 20*div

#found this soultion at https://www.geeksforgeeks.org/smallest-number-divisible-first-n-numbers/
#This soultion is very fast
def opt():
    div = 1
    for i in range(1,21):
        div = (div*i)/fractions.gcd(div,i)
    return div

print(opt())
#print(alt())
#print(pEQuestion5())


from collections import deque

d = deque()

for i in range(int(input())):
    s = input().split()
    if s[0] == 'append':
        d.append(s[1])
    elif s[0] == 'appendleft':
        d.appendleft(s[1])
    elif s[0] == 'pop':
        d.pop()
    elif s[0] == 'popleft':
        d.popleft()
for j in d:
    print(j,end=' ')


import os
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
import math
import matplotlib
#指定默认字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.family']='sans-serif' #解决负号'-'显示为方块的问题
matplotlib.rcParams['axes.unicode_minus'] = False

class backtest:
    def __init__(self, res_path, source_path, policy_type):
        self.res_path = res_path  # 结果文件位置
        self.hold_num = 20  # 持仓数
        self.adj_turn = 0.001  # 千分之一手续费
        self.st_money = 1000000  # 初始资金
        self.all_money = 1000000  # 现金流
        self.count_days = 0  # 计数当前是第几个交易日
        self.source_path = source_path  # 历史行情数据文件
        self.hold = pd.DataFrame(columns=['kdcode', 'hold'])
        self.policy_type = policy_type

    # 载入历史行情数据
    def load_history(self):
        df = pd.read_csv(self.source_path)
        df = df[['kdcode', 'dt', 'close']]
        return df

    # 查找一个元素在数组里面的位置，如果不存在，则返回-1
    def indexOf(e, a):
        for i in range(0, len(a)):
            if e == a[i]:
                return i
        return -1

    # 获取需要买入的股票代码
    def get_tobuy(self, best_stock, now_stock, max_count):
        count = 0
        toBuy = []
        for i in range(0, len(best_stock)):
            flag = 0
            for j in range(0, len(now_stock)):
                if best_stock[i] == now_stock[j]:
                    flag = 1
                    break;
            if flag == 0:
                toBuy.append(best_stock[i])
                count += 1
                if count >= max_count:
                    return toBuy
        return toBuy

    # 获取需要卖出的股票代码
    def get_tosell(self, now_price, now_stock, max_count):
        df = now_price[now_price['kdcode'].isin(now_stock)]
        #         print(df)
        df = df.sort_values(by=['close'], ascending=True)
        df = df.head(max_count)
        toSell = df['kdcode'].values
        return toSell

    # 模拟交易
    def trading(self, files, now_price):
        now_stock = self.hold['kdcode'].values
        best_stock = self.get_rank(self.res_path + '/' + files)
        best_stock = best_stock['kdcode'].values
        toBuy = best_stock
        toSell = now_stock
        # 现有策略，所有股票等金额
        if self.policy_type == 't3':
            max_count = 10
        if self.policy_type == 't5':
            max_count = 5
        if self.policy_type == 't10':
            max_count = 2
        if self.count_days == 0:
            max_count = 20
        toBuy = self.get_tobuy(best_stock, now_stock, max_count)
        max_count = len(toBuy)
        toSell = self.get_tosell(now_price, now_stock, max_count)
        self.sell(toSell, now_price)
        self.buy(toBuy, now_price)
        return self

    # 对于不在持仓列表的股票  卖出
    def sell(self, toSell, now_price):
        hold = self.hold  # 持仓份额
        for i in range(len(toSell)):
            if now_price[now_price['kdcode'] == toSell[i]].empty:  # 部分股票当日停牌
                code_price = 0.0
            else:
                code_price = 1.0 * now_price[now_price['kdcode'] == toSell[i]]['close'].values
                code_count = 1.0 * hold[hold['kdcode'] == toSell[i]]['hold'].values
                hold.drop(hold.index[hold['kdcode'] == toSell[i]], inplace=True)
            self.all_money += code_price[0] * code_count[0] * (1 - self.adj_turn)
        self.hold = hold
        return self

    # 对于需要持仓的股票  买入
    def buy(self, toBuy, now_price):
        sum_price = self.all_money / len(toBuy)  # 均分到每只股票的金额
        for i in range(len(toBuy)):
            price = 1.0 * now_price[now_price['kdcode'] == toBuy[i]]['close'].values
            hold = sum_price / (price * (1 + self.adj_turn))
            self.hold = self.hold.append({'kdcode': toBuy[i], 'hold': hold}, ignore_index=True)
        self.all_money = 0.0
        return self

    #     # 对于不在持仓列表的股票  卖出
    #     def sell_2(self, toSell, now_price):
    #         for i in range(len(toSell)):
    #             if now_price[now_price['kdcode']==toSell[i]].empty: # 部分股票当日停牌
    #                 code_price = 0.0
    #             else :
    #                 code_price = 1.0*now_price[now_price['kdcode']==toSell[i]]['close'].values
    #             self.all_money += code_price*self.counts*(1+self.adj_turn)

    #         return self

    #     # 对于需要持仓的股票  买入
    #     def buy_2(self, toBuy, now_price):
    #         sum_price = 0.00 # 需要买的股票的总价
    #         for i in range(len(toBuy)):
    #             sum_price += 1.0*now_price[now_price['kdcode']==toBuy[i]]['close'].values
    #         tmp = 0.0
    #         if sum_price:
    #             tmp = self.all_money/sum_price
    #         self.counts = int(tmp*1.0) # 股票份额 下取整
    #         self.all_money -= sum_price*self.counts*(1+self.adj_turn) # 剩余资产-现金流
    #         return self

    # 主函数 遍历所有交易日
    def my_run(self):
        pred_files = os.listdir(self.res_path)  # 获取所有的预测文件
        pred_files.sort()  # 按日期排序
        asset_list = []  # 记录总资产变化
        print("开始交易: ")
        price = self.load_history()
        for files in pred_files:
            today = files.split('.')[0]
            today_price = price[price['dt'] == today]
            self.trading(files, today_price)
            self.count_days += 1
            my_money = self.sum_money(today_price)
            print(my_money)
            asset_list.append(my_money)
        return asset_list

    # 计算当前资产总额--现金+股票
    def sum_money(self, today_price):
        now_stock = self.hold['kdcode'].values  # 获取当前持仓股票
        hold = self.hold
        s_m = self.all_money * 1.0
        for i in range(len(now_stock)):
            if today_price[today_price['kdcode'] == now_stock[i]].empty:  # 部分股票当日停牌
                code_price = 0.0
                s_m += 0
            else:
                code_price = 1.0 * today_price[today_price['kdcode'] == now_stock[i]]['close'].values
                code_count = 1.0 * hold[hold['kdcode'] == now_stock[i]]['hold'].values
                s_m += code_price[0] * code_count[0]
        return s_m

    # 对当日股票进行排序
    def get_rank(self, file_path):
        stock = pd.read_csv(file_path)
        stock = stock.sort_values(by="score", ascending=False)
        stock = stock[0:20].reset_index(drop=True)
        stock = stock[['kdcode', 'dt']]
        return stock

    # 评估函数
    def evaluate(self):
        asset_list = self.my_run()
        print(asset_list)
        print("年化利率： ")
        print(self.evaluate_AnnualizedReturn(asset_list))
        print("夏普率： ")
        print(self.evaluate_SharpeRatio(asset_list))
        print("年化波动： ")
        print(self.evaluate_Volatility(asset_list))
        print("最大回撤: ")
        print(self.evaluate_MaxDrawDown(asset_list))

    # 年化利率
    def evaluate_AnnualizedReturn(self, asset_list):
        test_return = (asset_list[-1] - asset_list[0]) / asset_list[0]
        test_days = len(asset_list) - 1
        ar = (test_return + 1) ** (365 / test_days) - 1
        return ar

    # 夏普率
    def evaluate_SharpeRatio(self, asset_list):
        ar = self.evaluate_AnnualizedReturn(asset_list)
        v = self.evaluate_Volatility(asset_list)
        return ar / v

    # 年化波动
    def evaluate_Volatility(self, asset_list):
        daily_return = [(i - j) / j for i, j in zip(asset_list[1:], asset_list[:-1])]
        daily_return = [i * 365 for i in daily_return]
        erp = sum(daily_return) / len(daily_return)
        v = sum((i - erp) * (i - erp) for i in daily_return)
        v = math.sqrt(v / len(daily_return))
        return v

    # 最大回撤
    def evaluate_MaxDrawDown(self, asset_list):
        min_asset = asset_list.copy()
        for i in range(len(min_asset) - 2, -1, -1):
            min_asset[i] = min(min_asset[i], min_asset[i + 1])
        mdd = max(-(min_asset[i] - asset_list[i]) / asset_list[i] for i in range(len(min_asset)))
        return mdd


import os
import validator
import datetime
time = datetime.datetime.now()

data_path = 'C:/Users/Niki/Documents/Programming Projects/Data/user_record/'
auth_path = 'C:/Users/Niki/Documents/Programming Projects/Data/auth_session/'

def create(accountNumber, first_name, last_name, email, password):

    user_data = str(accountNumber) + ',' + first_name + "," + last_name + "," + email + "," + password + "," + str(0)
    if does_account_number_exist(accountNumber): #returns false if acct # already exists
        return False

    if does_email_exist(email): #returns false if email already exists in existing acct
        print('User already exists')
        return False

    completion_state = False

    try:
        f = open(data_path + str(accountNumber) + ".txt", "x")

    except FileExistsError:
        does_file_contain_data = read(data_path + str(accountNumber) + ".txt")
        if not does_file_contain_data:
            delete(accountNumber)
    else:
        f.write(str(user_data))
        completion_state = True
    finally:
        f.close()
        return completion_state

def delete(accountNumber):
    is_delete_successful = False
    if os.path.exists(data_path + str(accountNumber) + ".txt"):
        try:
            os.remove(data_path + str(accountNumber) + ".txt")
            is_delete_successful = True
        except FileNotFoundError:
            print('User not found')
        finally:
            return is_delete_successful

def read(accountNumber):
    is_valid_account_number = validator.accountNumberValidator(accountNumber) #if validator returns true it gets saved here
    try:
        if is_valid_account_number: #if previous line returned true, then it opens the file that matches the acct #, else does the same without the .txt
            f = open(data_path + str(accountNumber) + ".txt", "r")
        else:
            f = open(data_path + str(accountNumber), "r")
    except FileNotFoundError:
        print('User not found')
    except FileExistsError:
        print("User doesn't exist")
    else:
        return f.readline()
    return False

def does_email_exist(email):
    all_users = os.listdir(data_path)
    for user in all_users:
        user_list = str.split(read(user), ',')
        if email in user_list:
            return True
        else:
            return False

def does_account_number_exist(accountNumber):
    all_users = os.listdir(data_path) # lists all files in folder 'user_record' and assigns to list
    for user in all_users: # checks to see if inside the all_users list there is a file name that matches the accnt number entered by the user
        if user == str(accountNumber) + ".txt":
            return True
        else:
            return False

def auth_user(accountNumber, password):
    if does_account_number_exist(accountNumber): # goes does_account_number_exist function to see if acct # is already in use
        user = str.split(read(accountNumber), ',') # creates list from auth files and then searches for password inside list
        if password == user[4]:
            return user
    else:
        return False

def account_balance(user):
    f = open(data_path + (user[0]) + ".txt", "w")
    user_str = str(user[0]) + ',' + user[1] + "," + user[2] + "," + user[3] + "," + user[4] + "," + str(user[5])
    try:
        f.write(str(user_str))

    finally:
        f.close()

def login_session_stamp(user):
    try:
        f = open(auth_path + (user[1]) + ".txt", "x")
        f.write('User logged in at ' + str(time))
    except FileExistsError:
        os.remove(auth_path + (user[1]) + ".txt",)
        f = open(auth_path + (user[1]) + ".txt", "x")
        f.write('User logged in at ' + str(time))

def logout_stamp_delete(user):
    os.remove(auth_path + (user[1]) + ".txt",)


import turtle
from PIL import Image
from turtle import Screen, Turtle
import cv2
polygon = Turtle()
forw = .001

turt = turtle. Turtle(visible=False)
turt.pencolor((0, 0, 100))
turt.pensize(.1)
turt.speed(0)

screen = turtle.Screen()
screen.bgcolor('black')

# turt.begin_fill()
# time.sleep(5)
# turtle.done()

while True:
    turt.forward(forw)
    turt.left(13)
    # turt.left(200)
    forw += .01
    polygon.hideturtle()
    # time.sleep(2)
    ts = screen.getcanvas().postscript(file="w.eps", colormode='color')
    inFile = Image.open("w.eps")
    outFile = "static/1.jpg"
    inFile.save(outFile)


def decrypt(encr_message: str, instructions: list):
    operation = instructions[0]
    if operation == 'Move':
        num_of_letters = int(instructions[1])
        decr_message = f'{encr_message[num_of_letters:]}{encr_message[:num_of_letters]}'
    elif operation == 'Insert':
        i = int(instructions[1])
        v = instructions[2]
        decr_message = f'{encr_message[:i]}{v}{encr_message[i:]}'
    else:
        substr = instructions[1]
        replacement_txt = instructions[2]
        decr_message = encr_message.replace(substr, replacement_txt)
    return decr_message

message =input()

command = input()
while command != 'Decode':
    command = command.split('|')
    message = decrypt(message, command)

    command = input()

print(f'The decrypted message is: {message}')


from register import *
import tkMessageBox
import sqlite3
from login_page import *
from request_pizza import *
from menu import *

def welcome():

        root=Tk()
        root.geometry("1600x800+0+0")
        root.title("Pizza Delivery system")
        root.configure(bg="white")

        Tops=Frame(root, width=1600, height=50, bg="white")
        Tops.pack(side=TOP)

        f1=Frame(root, width=800, height=700, bg="white")
        f1.pack(side=TOP)

        lblinfo = Label(Tops, font=('arial', 50 , 'bold' ), text="PIZZA DELIVERY SYSTEM" , fg="blue",bg="yellow", bd=10,anchor='w')
        lblinfo.grid(row=0,column=0)

        lab=Label(f1,text="\n\n\n\n\n\n\n\n",bg="white")
        lab.grid(row=0,column=0)
        L1 = Label(f1, text="WELCOME USER!!!",font=('arial',15,'bold'),fg="blue",bg="white")
        L1.grid(row=1,column=1)

        lab=Label(f1,text="\t\t\t",bg="white")
        lab.grid(row=2,column=1)

        B4=Button(f1,text="Order",width=20,height=4,bd=5,font=('arial',10,'bold'),fg="white",bg="blue",relief="raised",command=order)
        B4.grid(row=3,column=1)

        lab=Label(f1,text="\t\t\t",bg="white")
        lab.grid(row=3,column=2)

        B5=Button(f1,text="PIZZA MENU",width=20,height=4,bd=5,font=('arial',10,'bold'),fg="white",bg="blue",relief="raised",command=pizza_menu)
        B5.grid(row=5,column=1)

        lab=Label(f1,text="\t\t\t",bg="white")
        lab.grid(row=4,column=2)

        root.mainloop()

if __name__=="__main__":
        login()


# 포인터와 이분탐색을 활용한 문제
# 양쪽 지점을 시작점으로 잡고 합이 k에 근접한가 판단
# 합한 수가 k와 비교했을 때 크냐, 작냐로 left, right이동을 판단

t = int(input())
for i in range(t):
    n, k = map(int, input().split())
    numLst = list(map(int, input().split()))
    numLst.sort()
    cnt = 0
    left = 0
    right = n-1
    maxV = 2*(10**8)
    while left < right:
        val = numLst[right] + numLst[left]
        if maxV > abs(k - val):
            cnt = 1
            maxV = abs(k - val)
        elif maxV == abs(k - val):
            cnt += 1
        if k > val:
            left += 1
        else:
            right -= 1
    print(cnt)


# Добавление элементов
# Мы научились создавать множества, элементы которых известны на этапе создания. Следующий шаг – научиться добавлять
# элементы в уже существующие множества.

# Метод add()
# Для добавления нового элемента в множество используется метод add().
numbers = {1, 1, 2, 3, 5, 8, 3}  # создаем множество
numbers.add(21)  # добавляем число 21 в множество
numbers.add(34)  # добавляем число 34 в множество
print(numbers)   # {1, 2, 3, 34, 5, 8, 21}

# Не забывайте, что порядок элементов при выводе множества абсолютно произвольный.

# Обратите внимание, для использования метода add() требуется предварительно созданное множество, при этом оно может
# быть пустым.
numbers = set()  # создаем пустое множество
numbers.add(1)
numbers.add(2)
numbers.add(3)
numbers.add(1)
print(numbers)  # {1, 2, 3}

# Если требуется внести несколько значений в множество, то можно воспользоваться циклом for.
numbers = set()  # создаем пустое множество
for i in range(10):
    numbers.add(i*i + 1)
print(numbers)  # {1, 2, 65, 5, 37, 10, 17, 50, 82, 26}

# Удаление элемента
# Для удаления элементов из множества используются методы:
#     remove();
#     discard();
#     pop().

# Метод remove()
# Метод remove() — удаляет элемент из множества с генерацией исключения (ошибки) в случае, если такого элемента нет.
numbers = {1, 2, 3, 4, 5}
numbers.remove(3)
print(numbers)      # {1, 2, 4, 5}

# numbers = {1, 2, 3, 4, 5}
# numbers.remove(10)  # приводит к возникновению ошибки KeyError
# print(numbers)

# Метод discard()
# Метод discard() — удаляет элемент из множества без генерации исключения (ошибки), если элемент отсутствует.
numbers = {1, 2, 3, 4, 5}
numbers.discard(3)
print(numbers)      # {1, 2, 4, 5}

# Метод pop()
# Метод pop() — удаляет и возвращает случайный элемент из множества с генерацией исключения (ошибки) при попытке
# удаления из пустого множества.
numbers = {1, 2, 3, 4, 5}
print('до удаления:', numbers)      # до удаления: {1, 2, 3, 4, 5}
num = numbers.pop()                 # удаляет случайный элемент множества, возвращая его
print('удалённый элемент:', num)    # удалённый элемент: 1
print('после удаления:', numbers)   # после удаления: {2, 3, 4, 5}

# Метод pop() можно воспринимать как неконтролируемый способ удаления элементов по одному из множества.

# Метод clear()
# Метод clear() удаляет все элементы из множества.
numbers = {1, 2, 3, 4, 5}
numbers.clear()
print(numbers)   # set()

# Обратите внимание на то, что пустое множество выводится как set(), а не как {}. С помощью {} выводится пустой словарь.

# Примечания
# Примечание 1. Если мы не изменяли множество, порядок обхода элементов при помощи цикла for не изменится.

# Примечание 2. После изменения множества (методы add(), remove(), и т.д.) порядок элементов может измениться
# произвольным образом.