# -*- coding: utf-8 -*-
"""
Created on Mon May 27 15:16:45 2019
@author: weiho
"""
import os
'''
#Uses GPU 0
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
'''
import csv
import keras
from keras.applications import VGG16, ResNet50, InceptionV3
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.models import Sequential, load_model, Model
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Input, Dense, Activation, Flatten, Dropout, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import multi_gpu_model
from keras import regularizers, optimizers
from keras import backend as K
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import sys
import tensorflow as tf

from generators import categorical_generator, make_batch, test_generator
from aux_func import numImgs, allImgs, get_freq_dict

#model_type = vgg16, resnet, inception
#y_classes = categories used during training
#Trains a model on data from train_df_path, cross-validating with val_df_path
#Saves model at experiment_path/model_save_name.h5, class indices at experiment_path/model_save_name:indices.txt
#Accuracy at experiment_path/accuracy.png, loss at experiment_path/loss.png
def train_categorical(gpus, experiment_path, train_df_path, train_image_path, val_df_path, val_image_path, y_name, y_classes, augment_number,
                      model_type, model_save_name, epoch_number, learning_rate, decay, regularization, batch_size=32, img_height=224, img_width=224):

    checkpoint = ModelCheckpoint(os.path.join(experiment_path, model_save_name+'.h5'), monitor='val_loss', verbose=1, save_best_only=False, save_weights_only=False, mode='auto', period=25)
    callbacks = [checkpoint]

    #Session variables
    traindf = pd.read_csv(train_df_path)
    valdf = pd.read_csv(val_df_path)

    freq_dict = get_freq_dict(traindf, y_name, y_classes)
    num_labels = len(y_classes)

    numTrainImgs = numImgs(traindf, y_name, y_classes)
    numValImgs = numImgs(valdf, y_name, y_classes)

    class_weight = list(map(lambda x: 1/freq_dict[x], y_classes))

    #Generators
    train_generator = make_batch(generator='categorical',
                                 dataframe=traindf,
                                 image_path=train_image_path,
                                 y_name=y_name,
                                 y_classes=y_classes,
                                 batch_size=batch_size,
                                 augment_number=augment_number,
                                 height=img_height,
                                 width=img_width,
                                 forTrain=True
                                 )

    val_generator = make_batch(generator='categorical',
                               dataframe=valdf,
                               image_path=val_image_path,
                               y_name=y_name,
                               y_classes=y_classes,
                               batch_size=batch_size,
                               height=img_height,
                               width=img_width,
                               forTrain=False
                               )

    #Model
    if model_type == 'vgg16':

        net_input = Input(shape=(img_height, img_width, 3))
        conv_base = VGG16(
            weights='imagenet',
            include_top=False,
            input_shape=(img_height, img_width, 3))(net_input)
        conv_base.trainable = False
        flatten1 = Flatten()(conv_base)
        dropout1 = Dropout(0.5)(flatten1)
        dense1 = Dense(
            num_labels,
            activation='softmax',
            kernel_regularizer=regularizers.l2(regularization))(dropout1)
        with tf.device('/cpu:0'):
            model = Model(inputs=net_input, outputs=dense1)

    elif model_type == 'resnet':

        net_input = Input(shape=(img_height, img_width, 3))
        conv_base = ResNet50(
            weights='imagenet',
            include_top=False,
            input_shape=(img_height, img_width, 3))(net_input)
        conv_base.trainable = False
        flatten1 = Flatten()(conv_base)
        dropout1 = Dropout(0.5)(flatten1)
        dense1 = Dense(
            num_labels,
            activation='softmax',
            kernel_regularizer=regularizers.l2(regularization))(dropout1)
        with tf.device('/cpu:0'):
            model = Model(inputs=net_input, outputs=dense1)

    elif model_type == 'inception':

        net_input = Input(shape=(img_height, img_width, 3))
        conv_base = InceptionV3(
            weights='imagenet',
            include_top=False,
            input_shape=(img_height, img_width, 3))(net_input)
        conv_base.trainable = False
        flatten1 = Flatten()(conv_base)
        dropout1 = Dropout(0.5)(flatten1)
        dense1 = Dense(
            num_labels,
            activation='softmax',
            kernel_regularizer=regularizers.l2(regularization))(dropout1)
        with tf.device('/cpu:0'):
            model = Model(inputs=net_input, outputs=dense1)

    else:
        print('\nError in train_categorical: invalid model type\n')

    multi_model = multi_gpu_model(model, gpus=gpus)
    model.summary()

    #Train
    multi_model.compile(optimizers.RMSprop(lr=learning_rate, decay=decay), loss='categorical_crossentropy', metrics=['accuracy'])

    history = multi_model.fit_generator(generator=train_generator,
                                        steps_per_epoch=numTrainImgs//batch_size,
                                        validation_data=val_generator,
                                        validation_steps=numValImgs,
                                        class_weight=class_weight,
                                        epochs=epoch_number,
                                        verbose=1,
                                        callbacks=callbacks
                                        )

    #Save model parameters
    model.save(os.path.join(experiment_path, model_save_name+'.h5'))

    #Save model index meanings
    with open(os.path.join(experiment_path, model_save_name+':indices.txt'), mode='w', encoding='utf-8') as filewrite:
        csv_writer = csv.writer(filewrite, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        csv_writer.writerow(['class', 'frequency', 'index'])
        for i in range(len(y_classes)):
            csv_writer.writerow([y_classes[i], freq_dict[y_classes[i]], i])

    #Plots
    acc = history.history['acc']
    val_acc = history.history['val_acc']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    epochs = range(len(acc))

    plt.figure()
    plt.plot(epochs, acc, 'bo', label='Training accuracy')
    plt.plot(epochs, val_acc, 'r*', label='Validation accuracy')
    plt.title('Training and validation accuracy')
    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend()
    plt.savefig(os.path.join(experiment_path, 'accuracy.png'))

    plt.figure()
    plt.plot(epochs, loss, 'bo', label='Training loss')
    plt.plot(epochs, val_loss, 'r*', label='Validation loss')
    plt.title('Training and validation loss')
    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend()
    plt.savefig(os.path.join(experiment_path, 'loss.png'))

#experiment_path/model_test_name/model_test_name.h5 = model being evaluated, experiment_path/model_test_name/model_test_name:indices.txt = class indices
#Evaluates performance of model_test_name on test_df_path
#Creates test results file at experiment_path/model_test_name/model_test_name:test_results.txt
#Creates summary of test results at experiment_path/model_test_name/model_test_name:test_summary.txt
#Returns accuracies by class
def eval_categorical(experiment_path, test_df_path, test_image_path, y_name, model_test_name, height=224, width=224):

    #Session variables
    testdf = pd.read_csv(test_df_path)
    labelindices = pd.read_csv(os.path.join(experiment_path, model_test_name+':indices.txt'))
    y_classes = list(labelindices.loc[:, 'class'])
    print('Classes in model ' + model_test_name + ': ' + str(y_classes))
    freq_dict = get_freq_dict(testdf, y_name, y_classes)

    #PictureIDs, objectID, categoryNames, and true labels by image
    objpics = np.empty([0, 4], dtype=np.int32)
    for i in range(len(testdf)):
        if testdf.iloc[i].loc[y_name] in y_classes:
            for pic in testdf.iloc[i].loc['picIDs'].split(','):
                objpics = np.append(objpics, [[pic, testdf.iloc[i].loc['objectID'], testdf.iloc[i].loc['categoryName'], testdf.iloc[i].loc[y_name]]], axis=0)
    objpicsdf = pd.DataFrame(objpics, columns=['picID', 'objectID', 'categoryName', 'truth'], index=None)

    #Load model
    model = load_model(os.path.join(experiment_path, model_test_name+'.h5'))

    #Test generator
    eval_generator = test_generator(dataframe=testdf,
                                    image_path=test_image_path,
                                    y_name=y_name,
                                    y_classes=y_classes,
                                    include_NA=False,
                                    height=height,
                                    width=width
                                    )

    labeledExamples = numImgs(testdf, y_name, y_classes=y_classes)

    testresults = model.predict_generator(generator=eval_generator,
                                          steps=labeledExamples,
                                          verbose=1)

    #Probabilities of each class by image
    guessprobs = pd.DataFrame(testresults, index=None)
    guessprobs.columns = y_classes

    #Highest probability class by image
    guessesdf = np.argmax(testresults, axis=1)
    guessesdf = pd.DataFrame(guessesdf, columns=['pred'], index=None)

    #Test results file
    resultsdf = objpicsdf.join(guessesdf.join(guessprobs))
    resultsdf.to_csv(os.path.join(experiment_path, model_test_name+':test_results.txt'), encoding='utf-8', index=None, na_rep='NA')

    #Top k-accuracies by individual image
    k_accuracies = np.zeros(len(y_classes))

    #Confusion matrix
    #[i, j] = n : label j is the nth most likely label given by the model to images with true label i
    confusion_matrix = np.zeros((len(y_classes), len(y_classes)))

    for i in range(len(resultsdf)):
        pic_truth = resultsdf.iloc[i].loc['truth']
        truthindex = y_classes.index(pic_truth)
        guessprob = list(guessprobs.iloc[i])
        rankguesses = list(map(lambda x : guessprob.index(x), sorted(guessprob, reverse=True)))
        for guess in range(len(rankguesses)):
            confusion_matrix[truthindex, rankguesses[guess]] += guess+1
        for k in range(1, len(y_classes)+1):
            if y_classes.index(pic_truth) in rankguesses[:k]:
                k_accuracies[k-1] += 1

    k_accuracies /= labeledExamples
    for i in range(confusion_matrix.shape[0]):
        confusion_matrix[i] /= freq_dict[y_classes[i]]

    #Write summary of test results
    with open(os.path.join(experiment_path, model_test_name+':test_summary.txt'), 'w') as summary_writefile:
        #k-accuracies per image
        summary_writefile.write('k-accuracies per image: \n')
        for k in range(len(k_accuracies)):
            summary_writefile.write(str(k+1) + '-accuracy: ' + str(k_accuracies[k]) + '\n')
        summary_writefile.write('\n')

        #Confusion matrix
        summary_writefile.write('Confusion matrix: nth most likely label to be assigned\n')
        summary_writefile.write('Classes: ' + str(y_classes) + '\n')
        for i in range(confusion_matrix.shape[0]):
            summary_writefile.write(y_classes[i] + ': ' + str(confusion_matrix[i]) + '\n')
        summary_writefile.write('\n')

    #Return accuracies by class
    return k_accuracies

#experiment_path/model_test_name/model_test_name.h5 = model being evaluated, experiment_path/model_test_name/model_test_name:indices.txt = class indices
#Uses model_test_name to predict classes of images in test_df_path
#Creates test results file at experiment_path/model_test_name/model_test_name:results_save_name.txt
#Returns accuracies by class
def predict_categorical(experiment_path, test_df_path, test_image_path, model_test_name, results_save_name, height=224, width=224):

    #Session variables
    testdf = pd.read_csv(test_df_path)
    labelindices = pd.read_csv(os.path.join(experiment_path, model_test_name+':indices.txt'))
    y_classes = list(labelindices.loc[:, 'class'])
    print('Classes in model ' + model_test_name + ': ' + str(y_classes))

    #PictureIDs and objectID for each image
    objpics = np.empty([0, 2], dtype=np.int32)
    for i in range(len(testdf)):
        for pic in testdf.iloc[i].loc['picIDs'].split(','):
            objpics = np.append(objpics, [[pic, testdf.iloc[i].loc['objectID']]], axis=0)
    objpicsdf = pd.DataFrame(objpics, columns=['picID', 'objectID'], index=None)

    #Load model
    model = load_model(os.path.join(experiment_path, model_test_name+'.h5'))

    #Test generator
    predict_generator = test_generator(dataframe=testdf,
                                    image_path=test_image_path,
                                    y_name=None,
                                    y_classes=None,
                                    include_NA=True,
                                    height=height,
                                    width=width
                                    )

    totalExamples = allImgs(testdf, y_name=None, include_NA=True)

    testresults = model.predict_generator(generator=predict_generator,
                                          steps=totalExamples,
                                          verbose=1)

    #Probabilities of each class by image
    guessprobs = pd.DataFrame(testresults, index=None)
    guessprobs.columns = y_classes

    #Highest probability class by image
    guessesdf = np.argmax(testresults, axis=1)
    guessesdf = pd.DataFrame(guessesdf, columns=['pred'], index=None)

    #Predict results file
    resultsdf = objpicsdf.join(guessesdf.join(guessprobs))
    resultsdf.to_csv(os.path.join(experiment_path, model_test_name+':' + results_save_name + '.txt'), encoding='utf-8', index=None, na_rep='NA')


from PySide2 import QtWidgets, QtGui, QtCore
from pygears.conf import Inject, inject
from .node import NodeItem
from .pipe import Pipe
from .main_window import Shortcut
from functools import partial

snipe_shortcuts = []

def sniper():
    Sniper()

class SnipeCodeItem(QtWidgets.QGraphicsTextItem):
    def __init__(self, text, parent=None):
        super().__init__(text, parent=parent)
        f = self.font()
        f.setPointSize(12)
        f.setBold(True)
        self.setFont(f)

        # self.font().setPointSize(16)
        # self.font().setBold(True)
        # # self.setFont(self.font())
        # self.setFont(QtGui.QFont("Source Code Pro", 16))

    def paint(self, painter, option, widget):
        painter.setBrush(QtCore.Qt.white)
        painter.drawRect(self.boundingRect())
        super().paint(painter, option, widget)

class Sniper:
    @inject
    def __init__(self,
                 main=Inject('gearbox/main/inst')):

        Shortcut('graph', QtCore.Qt.Key_F, self.snipe_select)
        Shortcut('graph', QtCore.Qt.CTRL + QtCore.Qt.Key_F,
                 self.snipe_select_nodes)
        Shortcut('graph', QtCore.Qt.SHIFT + QtCore.Qt.Key_F,
                 self.snipe_select_pipes)

        self.main = main

    @inject
    def snipe_cancel(self, graph=Inject('gearbox/graph')):
        self.main.key_cancel.disconnect(self.snipe_cancel)
        for text, s in snipe_shortcuts:
            s.setParent(None)
            graph.scene().removeItem(text)

        self.main.change_domain('graph')
        snipe_shortcuts.clear()

    @inject
    def snipe_shot(self, pipe, graph=Inject('gearbox/graph')):
        graph.select(pipe)
        self.snipe_cancel()

    @inject
    def snipe_shot_prefix(self, prefix, graph=Inject('gearbox/graph')):
        import pdb
        pdb.set_trace()
        for text, s in snipe_shortcuts:
            if text.toPlainText().startswith(prefix):
                continue

            s.setParent(None)
            graph.scene().removeItem(text)

    def snipe_shot_prefix_test(self):
        print("Ambiguous")

    def get_visible_objs(self, node, objtype):
        if (objtype is None) or (objtype is NodeItem):
            for n in node._nodes:
                yield n
                if not n.collapsed:
                    yield from self.get_visible_objs(n, objtype)

        if (objtype is None) or (objtype is Pipe):
            for p in node.pipes:
                yield p

    def snipe_select_nodes(self):
        self.snipe_select(objtype=NodeItem)

    def snipe_select_pipes(self):
        self.snipe_select(objtype=Pipe)

    @inject
    def snipe_select(self, objtype=None, graph=Inject('gearbox/graph')):
        self.main.key_cancel.connect(self.snipe_cancel)

        nodes = graph.selected_nodes()

        nodes = [
            node.parent if node.collapsed else node for node in nodes
        ]

        if not nodes:
            pipes = graph.selected_pipes()
            if not pipes:
                nodes = [graph.top]
            else:
                nodes = [pipe.parent for pipe in pipes]

        keys = [6]

        for n in nodes:
            if n.collapsed:
                continue

            for i, obj in enumerate(self.get_visible_objs(n, objtype=objtype)):
                key_codes = [key + ord('A') for key in reversed(keys)]
                snipe_text = ''.join([chr(key).upper() for key in key_codes])
                text = SnipeCodeItem(snipe_text)

                text.setZValue(100)
                graph.scene().addItem(text)

                if isinstance(obj, NodeItem):
                    text.setPos(
                        obj.mapToScene((obj.boundingRect().bottomLeft() + obj.
                                        boundingRect().bottomRight()) / 2) -
                        QtCore.QPointF(text.boundingRect().width() / 2,
                                       text.boundingRect().height()))
                else:
                    text.setPos(
                        obj.mapToScene(obj.path().pointAtPercent(0.5)) -
                        QtCore.QPointF(text.boundingRect().width(),
                                       text.boundingRect().height()) / 2)

                self.main.change_domain('_snipe')
                shortcut = QtWidgets.QShortcut(
                    QtGui.QKeySequence(*key_codes), self.main)

                shortcut.activated.connect(partial(self.snipe_shot, obj))

                # if len(keys) > 0:
                #     shortcut.activatedAmbiguously.connect(
                #         self.snipe_shot_prefix_test)
                # shortcut.activatedAmbiguously.connect(
                #     partial(
                #         self.snipe_shot_prefix, prefix=snipe_text[:-1]))

                snipe_shortcuts.append((text, shortcut))

                for pos in range(len(keys) + 1):
                    if pos == len(keys):
                        keys.insert(0, 0)
                        break

                    keys[pos] += 1

                    if keys[pos] < 25:
                        break
                    else:
                        keys[pos] = 0


import glob
import time
from evdev import InputDevice, categorize, ecodes
from pishowerutils import logger

class UsbRfidReader:
    """
    Class for reading out RFID transponders via USB HID readers

    Opens USB HID devices like simple RFID readers for EM4100 and
    Mifare NFC transponders and reads the received transponder
    serial number.

    Supported are Linux systems and any card/code readers registered
    as HID devices under /dev/input/event[0..n].

    WARNING:
    File read permissions to the devices are needed - check your
    user's groups! (e.g. for membership of group 'input')
    """

    __inputDevice = None
    __inputDevicePath = ''
    __deviceOpenRetries = 0
    __minCodeLength = 8
    __scancodes = {
        # Scancode: ASCIICode
        0: None, 1: u'ESC', 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5',
        7: u'6', 8: u'7', 9: u'8', 10: u'9', 11: u'0', 12: u'-', 13: u'=',
        14: u'BKSP', 15: u'TAB', 16: u'Q', 17: u'W', 18: u'E', 19: u'R',
        20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'[',
        27: u']', 28: u'CRLF', 29: u'LCTRL', 30: u'A', 31: u'S', 32: u'D',
        33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u';',
        40: u'"', 41: u'`', 42: u'LSHFT', 43: u'\\', 44: u'Z', 45: u'X',
        46: u'C', 47: u'V', 48: u'B', 49: u'N', 50: u'M', 51: u',', 52: u'.',
        53: u'/', 54: u'RSHFT', 56: u'LALT', 100: u'RALT'
    }

    def __init__(self, devicePath='', minCodeLength=8):
        """
        Init the input device object

        Parameter 'devicePath' for input event device like
        '/dev/input/event0' is optional. If empty all available
        input devices are tried.
        """
        self.__minCodeLength = minCodeLength
        self.__inputDevicePath = devicePath
        self.open()

    def __del__(self):
        """ Destroy class and handle for input device """
        self.close()

    def open(self):
        """
        Open an input event device for reading

        Tries to open the device path given to the constructor
        or search for all available input event devices.
        """
        device_paths = []
        if len(self.__inputDevicePath):
            device_paths = ["{0}".format(self.__inputDevicePath)]
        else:
            device_paths = glob.glob('/dev/input/event*')  # search all available devices
        for path in device_paths:
            try:
                self.close()
                self.__inputDevice = InputDevice(path)
                self.__deviceOpenRetries = 0
                self.__inputDevicePath = path
                logger.debug('Opened RFID reader device \'{0}\''.format(path))
                time.sleep(1.0)  # prevent timing issues
                return
            except:
                if self.__deviceOpenRetries < 1:
                    logger.error('Unable to open USB RFID reader \'{0}\'!'.format(path))
                self.__inputDevice = None
                self.__deviceOpenRetries += 1

    def close(self):
        """ Close the input device and wait 1 second """
        try:
            if self.__inputDevice is not None:
                self.__inputDevice.close()
                self.__inputDevice = None
                logger.debug('RFID input device closed')
                time.sleep(1.0)  # prevent timing issues
        except:
            logger.warning('Error while closing RFID input device!')

    def is_open(self):
        """ Returns True, if connection to RFID reader is open """
        return self.__inputDevice is not None

    def readline(self):
        """ Try reading a code from the input device and return it as string """
        if self.__inputDevice is None:
            self.open()
            if self.__inputDevice is None:
                return None
        line = ''
        try:
            while True:
                event = self.__inputDevice.read_one()
                if event is None and line == '':
                    # There are blank events in between characters, so we don't want
                    # to break if we've started reading them
                    break  # start a new read.
                if event is None or event.type != ecodes.EV_KEY:
                    continue
                data = categorize(event)
                # catch only keyup, and not Enter
                if data.keystate == 0 and data.scancode != 42:
                    if data.scancode == 28:
                        # looking return key to be pressed
                        if len(line) < self.__minCodeLength:
                            logger.warning('ignoring to small code: {0}'.format(line))
                            break
                        else:
                            logger.debug('code read: \'{0}\''.format(line))
                            return line
                    else:
                        line += self.__scancodes[data.scancode]
        except:
            logger.error('Parsing input stream failed!')
            self.close()
        return None

# command line execution
if __name__ == '__main__':
    rfidReader = UsbRfidReader('/dev/input/event2', 10)
    while True:
        try:
            code = rfidReader.readline()
            if code is not None:
                logger.debug('found a code: \'{0}\''.format(code))
            time.sleep(0.5)
        except KeyboardInterrupt:
            logger.debug('Key pressed - finishing now...')
            break
        except:
            logger.error('Unknown error received. Reading aborted!')
            break


x=int(input("Enter Number to check prime or Not"))
count=0;
for i in range(2,x//2 + 1):
    if i%2==0:
        count=count+1
if count==1:

    print("Not-Prime")
else:
    print("Prime")


import logging
import os

import youtube_dl
from telegram import ChatAction
from telegram.error import NetworkError
from telegram.ext import CommandHandler

from utils.decorators import handle_empty_arg, send_recording_action
from utils.utils import send_message_to_admin

logger = logging.getLogger(__name__)

FILENAME = 'Audio_Cuervot'
VLC_LINK = 'https://play.google.com/store/apps/details?id=org.videolan.vlc'

@send_recording_action
@handle_empty_arg(required_params=('args',), error_message='Y la url del video? `/yttomp3 <url>`',
                  parse_mode='markdown')
def youtube_to_mp3(bot, update, args):
    video_url = args[0]

    def ext(f):
        return f'bestaudio[ext={f}]'

    def format_extensions(extens):
        return '/'.join(map(ext, extens))

    try:
        extensions = ('mp3', '3gp', 'aac', 'wav', 'flac', 'm4a')
        ydl_opts = {
            'format': format_extensions(extensions),
            'outtmpl': f'{FILENAME}.%(ext)s',
        }
        logger.info(f'Starting download of {video_url}..')
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([video_url])
        logger.info(f'Video downloaded.')

    except Exception:
        logger.error('Audio not downloaded.', exc_info=True)
        update.message.reply_text(f'No audio found for {video_url}')
        return

    # Download was successful, now we must open the audio file
    try:
        logger.info('Reading audio file from local storage')
        file, filename = get_audio_file(extensions)
        update.message.reply_text(f'âœ… Archivo descargado. Enviando...')
        bot.send_chat_action(chat_id=update.message.chat_id, action=ChatAction.UPLOAD_AUDIO)
        logger.info(f'Filename: {filename}')
        if file:
            logger.info('Sending file to user')
            update.message.reply_document(document=file)
            update.message.reply_text(f'ðŸ’¬ Tip: PodÃ©s usar [VLC]({VLC_LINK}) para reproducir el audio ðŸŽ¶',
                                      parse_mode='markdown', disable_web_page_preview=True)
            file.close()
            logger.info('File sent successfully')
    except NetworkError:
        logger.error('A network error occurred.', exc_info=True)
        update.message.reply_text(text='ðŸš€ Hay problemas de conexiÃ³n en estos momentos. IntentÃ¡ mas tarde..')
        send_message_to_admin(bot, f'Error mandando {video_url}, {filename}')

    except Exception:
        msg = 'Error uploading file to telegram servers'
        logger.exception(msg), send_message_to_admin(bot, msg)
        update.message.reply_text(text=msg)

    else:
        if filename:
            try:
                # Remove the file we just sent, as the name is hardcoded.
                logger.info(f"Removing file '{filename}'")
                os.remove(filename)
                logger.info('File removed')
            except FileNotFoundError:
                msg = f'Error removing audio file. File not found {filename}'
                logger.error(msg), send_message_to_admin(bot, msg)
            except Exception:
                msg = f"UnknownError removing audio file. '{filename}'"
                logger.error(msg), send_message_to_admin(bot, msg)

def get_audio_file(exts):
    """Youtube-dl does not return file data on success, so we must guess the file extension"""
    possible_filenames = (f"{FILENAME}.{ext}" for ext in exts)
    for filename in possible_filenames:
        try:
            return open(filename, 'rb'), filename
        except FileNotFoundError:
            continue

    return None, None

yt_handler = CommandHandler('yttomp3', youtube_to_mp3, pass_args=True)
yt_handler_alt = CommandHandler('y', youtube_to_mp3, pass_args=True)


import pytest
import requests

from quark.utils.output import output_parent_function_table
from quark.Objects.quark import Quark

APK_SOURCE = (
    "https://github.com/quark-engine/apk-malware-samples"
    "/raw/master/14d9f1a92dd984d6040cc41ed06e273e.apk"
)
APK_FILENAME = "14d9f1a92dd984d6040cc41ed06e273e.apk"

@pytest.fixture()
def quark_obj(scope="function"):
    r = requests.get(APK_SOURCE, allow_redirects=True)
    open(APK_FILENAME, "wb").write(r.content)

    return Quark(APK_FILENAME)

def test_output_parent_function_table(capsys, quark_obj):
    method_obj = quark_obj.apkinfo.find_method(
        "Lcom/google/progress/WifiCheckTask;", "goConnectNetwork", "()V"
    )

    call_graph_analysis_list = (
        {"crime": "The Crime", "parent": method_obj},
        {"crime": "The Crime", "parent": method_obj},
        {"crime": "Another Crime", "parent": method_obj},
    )

    # Test one crime
    output_parent_function_table([call_graph_analysis_list[0]])

    output = capsys.readouterr().out
    assert output.count("Lcom/google/progress/WifiCheckTask;goConnectNetwork") == 1
    assert output.count("The Crime") == 1

    # Test crimes with duplicated description
    output_parent_function_table(call_graph_analysis_list)

    output = capsys.readouterr().out
    print(output)
    assert output.count("Lcom/google/progress/WifiCheckTask;goConnectNetwork") == 1
    assert output.count("The Crime") == 1
    assert output.count("Another Crime") == 1


class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        dic = {'(': ')', '[': ']', '{': '}'}
        for c in s:
            if stack and stack[-1] in "([{" and dic[stack[-1]] == c:
                stack.pop()
            else:
                stack.append(c)
        return not stack


import cv2
import numpy as np

# 步骤1: 加载图像并分割为红绿蓝通道
image = cv2.imread('1.jpg')
blue, green, red = cv2.split(image)

# 步骤2: 显示原始绿通道图像
cv2.imshow('Original Green Channel', green)

# 步骤3: 克隆绿通道图像两次
clone1 = green.copy()
clone2 = green.copy()

# 步骤4: 计算绿通道的最小值和最大值
min_value = np.min(green)
max_value = np.max(green)

# 步骤5: 将clone1的所有元素赋值为(thresh/2)
thresh = (max_value - min_value) / 2.0
clone1[:] = thresh

# 步骤6: 将clone2的所有元素赋值为0
clone2[:] = 0

# 步骤7: 使用cv2.compare比较图像
comparison_result = cv2.compare(green, clone1, cv2.CMP_GE)

# 步骤8: 使用cv2.subtract进行减法操作
processed_green = cv2.subtract(green, thresh / 2, green, comparison_result)

# 显示处理后的绿通道图像
cv2.imshow('Processed Green Channel', processed_green)

# 等待用户按下任意键，然后关闭所有窗口
cv2.waitKey(0)
cv2.destroyAllWindows()


import os
import webbrowser
from functools import cache

import imageio
from reportlab.graphics import renderPM
from svglib.svglib import svg2rlg
from utils import Log
from utils.xmlx import _

from hbd.core import bbox_utils
from hbd.draw.draw_line import DrawLine
from hbd.draw.draw_node import DrawNode

log = Log(__name__)

class Draw(DrawNode, DrawLine):
    def __init__(self, config, styler):
        self.config = config
        self.styler = styler

    @cache
    def get_t(self):
        return bbox_utils.get_t(self.styler, self.config.loc_list)

    def draw_nodes(self):
        t = self.get_t()
        nodes = []
        for label, (x, y) in self.config.node_idx.items():
            nodes.append(self.draw_node(label, x, y, t))
        return nodes

    def draw_lines(self):
        t = self.get_t()
        lines = []
        for line in self.config.line_idx.values():
            lines.append(self.draw_line(line, t))
        return lines

    def draw_rect_border(self):
        return _('rect', None, self.styler.rect_border)

    def draw_title(self):
        self.config.title
        return _('text', self.config.title, self.styler.text_title)

    def draw_subtitle(self):
        return _('text', self.config.subtitle, self.styler.text_subtitle)

    def draw_footer_text(self):
        footer_text = self.config.footer_text
        font_size = min(
            self.styler.text_footer_text['font_size'],
            self.styler.svg['width'] / len(footer_text),
        )
        return _(
            'text',
            footer_text,
            self.styler.text_footer_text | dict(font_size=font_size),
        )

    def draw_watermark(self):
        return _(
            'text',
            '@nuuuwan',
            self.styler.text_watermark,
        )

    def draw(self, png_path, do_open=True):
        svg = _(
            'svg',
            [
                self.draw_watermark(),
                self.draw_title(),
                self.draw_subtitle(),
                self.draw_footer_text(),
            ]
            + self.draw_lines()
            + self.draw_nodes(),
            self.styler.svg,
        )
        svg_path = png_path[:-3] + 'svg'
        svg.store(svg_path)
        log.debug(f'Saved {svg_path}')

        png_path = Draw.convert_svg_to_png(svg_path)
        if do_open:
            webbrowser.open(os.path.abspath(png_path))
        return png_path

    @staticmethod
    def convert_svg_to_png(svg_path):
        png_path = svg_path[:-3] + 'png'

        drawing = svg2rlg(svg_path)
        renderPM.drawToFile(drawing, png_path, fmt="PNG")
        log.info(f'Saved {png_path}')

        return png_path

    @staticmethod
    def build_animated_gif(png_path_list, gif_path):
        png_path_list.sort()
        last_png_path = png_path_list[-1]
        for i in range(0, 5):
            png_path_list.append(last_png_path)

        images = []
        for png_path in png_path_list:
            images.append(imageio.imread(png_path))
        DURATION = 55.70 / 24
        imageio.mimwrite(gif_path, images, duration=DURATION)
        log.info(f'Built {gif_path} (from {len(png_path_list)} png files)')
        webbrowser.open(os.path.abspath(gif_path))


from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QFont, QPixmap
import sys
import edit_section
import freeway_window
import home as primary
import section_vector

class Vehicle(QLabel):
    """
    Vehicle object is a QLabel that is clickable
    All vehicles shown on the map in GUI are of type Vehicle
    """
    def __init__(self,lane,lead,gap,model,r,g,b,parent=None):
        super(Vehicle, self).__init__(parent)
        self.parent_window = parent
        self.lane = lane
        self.lead = lead
        self.gap = gap
        self.model = model
        self.color_r = r
        self.color_g = g
        self.color_b = b
        self.position = -1
        self.initUI()

    def initUI(self):

        #set dimensions and style
        self.length = primary.height/22
        self.width = primary.width/65
        self.setMinimumHeight(primary.height/22)
        self.setMinimumWidth(primary.width/65)
        self.setMaximumHeight(primary.height/22)
        self.setMaximumWidth(primary.width/65)
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.setFrameStyle(1)

        #calculate luminance to have border and text the correct color
        luminance = 0.2126 * int(self.color_r) + 0.7152 * int(self.color_g) + 0.0722 * int(self.color_b)
        text_color = "white"
        if luminance > 128:
            text_color = "black"

        #set font and style
        self.setFont(QFont("Arial",12))
        self.setStyleSheet("background:rgb({},{},{}); color:{};".format(self.color_r,self.color_g,self.color_b,text_color))

    #allow clickable
    clicked=pyqtSignal()
    def mouseReleaseEvent(self, ev):
        self.clicked.emit()

    def change_color(self,r,g,b):
        """
        connected: none
        function: Changes the vehicles color to the specified rgb values. This function is used in multiple files to change vehicle color
        """
        luminance = 0.2126 * int(r) + 0.7152 * int(g) + 0.0722 * int(b)
        text_color = "white"
        if luminance > 128:
            text_color = "black"
        self.setStyleSheet("background:rgb({},{},{}); color:{};".format(r,g,b,text_color))

def main():
    primary.main()

if __name__ == "__main__":
    main()


from fastapi import FastAPI
from repository import scrappy_data
from modules import CityModel

app = FastAPI()

@app.get('/')
def index():
    return {'log':'weather[API]'}

@app.post('/get_city_weather')
def get_city_weather(city: str) -> CityModel:
    data = scrappy_data(city=city)
    city = CityModel(nome = data['location'], date=data['time'], statu=data['info'], temperatur=data['weather'])
    return city


class Solution:
    def backspaceCompare(self, S, T):
        """
        :type S: str
        :type T: str
        :rtype: bool
        """
        def backward_iter(str):  # A iterator resembles stack
            skip = 0
            for c in reversed(str):
                if c == '#':
                    skip += 1
                elif skip:  # c is not '#' and skip > 0
                    skip -= 1
                else:
                    yield c  # Only yield c when skip <= 0

        return all(x == y for x, y in
                   itertools.zip_longest(backward_iter(S), backward_iter(T)))


from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import csv
import seaborn as sns

directory = '/Users/kylecox/Documents/UT/SDS 379R/beyondbinary/Percentage by Depth/'
plt.style.use('fivethirtyeight')

def plot_pct_vs_vol_over_time():
	# data from basketball reference
	season = np.array([i for i in range(2000, 2022)])
	pct = np.array([.353, .354, .354, .349, .347, .356, .358, .358, .362, .367, .355, .358, .349, .359, .360, .350, .354, .358, .362, .355, .358, .367])
	vol = np.array([13.7, 13.7, 14.7, 14.7, 14.9, 15.8, 16, 16.9, 18.1, 18.1, 18.1, 18.0, 18.4, 20, 21.5, 22.4, 24.1, 27.0, 29.0, 32.0, 34.1, 34.6])
	plt.plot(season, pct)
	plt.xlabel('Season', fontsize=15)
	plt.ylabel('Three-Point Percentage', fontsize=15)
	plt.ylim(0, .5)
	plt.subplots_adjust(bottom=0.15)
	plt.subplots_adjust(left=.15)
	plt.savefig('viz/three-point-pct-over-time.png')
	plt.clf()

	plt.plot(season, vol)
	plt.xlabel('Season', fontsize=15)
	plt.ylabel('Mean Three-Point Attempts per Game', fontsize=15)
	plt.ylim(0, 40)
	plt.subplots_adjust(bottom=0.15)
	plt.subplots_adjust(left=.15)
	plt.savefig('viz/three-point-attempts-per-game.png')
	plt.clf()

def plot_best_rim_depth_by_angle():
	# fig = plt.figure(figsize=(40, 40))
	# columns = 5
	# rows = 3
	angles = []
	best_depth = []
	for angle in range(38, 52 + 1):
		angles.append(angle)
		res = {}
		# i = angle - 38 + 1
		filename = directory + str(angle) + '.csv'
		with open(filename, 'r') as f:
			reader = csv.reader(f)
			next(reader, None)
			for row in reader:
				res[row[1]] = float(row[2])
			max_key = float(max(res, key=res.get))
			best_depth.append(round(max_key,1))
	print(angles)
	print(best_depth)
	plt.scatter(np.array(angles), np.array(best_depth))
	plt.xlabel('Arc Angle (degrees)', fontsize=15)
	plt.ylabel('Rim Depth (in.)', fontsize=15)
	plt.title('Ideal Rim Depth from Launch Angle', fontsize=15)
	plt.subplots_adjust(bottom=.15)
	plt.subplots_adjust(left=.15)
	plt.savefig('viz/best-rim-depth-by-angle.png')
	plt.clf()

def grid_heatplots():
	for angle in [38, 42, 46, 50]:
		print(angle)
		# i = angle - 38 + 1
		data = []
		df = pd.read_csv('kernel_smooth_2d/' + str(angle) + '.csv', names = [str(i) for i in range(-20, 20+1)] )
		df.index = [str(i) for i in range(-20, 20 + 1)]
		# df = df.iloc[::-1]

		small_df = df[[str(i) for i in range(-10, 10 + 1)]]
		small_df = small_df.loc[[str(i) for i in range(-10, 10 + 1)]]

		plt.figure(figsize=(10*6273/5500,10), dpi=1000)
		ax = sns.heatmap(small_df, linewidth=0.5, annot=False)
		plt.gca().invert_yaxis()
		plt.xlabel('Rim Left-Right (in.)', fontsize=15)
		plt.ylabel('Rim Depth (in.)', fontsize=15)
		# add circle with radius 9 to plot
		plt.gca().add_artist(plt.Circle((0 + 10.5, 0 + 10.5), radius=9, color='orange', fill=False, linewidth=2))
		plt.title('Probability Make by x-y Placement, Angle: ' + str(angle) + ' degrees', fontsize=15)
		plt.subplots_adjust(bottom=.15)
		plt.subplots_adjust(left=.15)
		plt.savefig('viz/kernel-smooth-2d-2/' + str(angle) + '.png')
		plt.clf()

	df = pd.read_csv('threedata_shotscore_2.csv')
	# plot a histogram of arcAngle in the df
	plt.hist(df['arcAngle'], bins=100)
	plt.xlim([30, 60])
	plt.xlabel('Shot Angle (degrees)')
	plt.ylabel('Frequency')
	plt.savefig('viz/arc_angle_histogram.png')

# plot average shot score per year and average outcome per year on same axis
def plot_shooting_percentage_and_shotscore_over_seasons(df):
	seasons = [i for i in range(2012, 2020)]
	pct_series = []
	ss_series = []
	for season in seasons:
		pct_series.append(df[df['season'] == season]['outcome'].mean())
		ss_series.append(df[df['season'] == season]['shotScore'].mean())
	## format ss_series as percentage
	ss_series = [i*100 for i in ss_series]
	# format pct_series as percentage
	pct_series = [i*100 for i in pct_series]
	# plot pct_series and ss_series on seasons axis
	plt.plot(seasons, pct_series, label='Shooting Percentage')
	plt.plot(seasons, ss_series, label='Shot Score')
	# make y-axis a percentage
	plt.ylim(30, 40)
	plt.title('Shooting Percentage and Shot Score (* 100) Over Seasons')
	plt.xlabel('Season')
	plt.ylabel('Shot Score * 100 /Three-Point Percentage')
	plt.legend()
	plt.savefig('viz/shot-score-and-pct-over-seasons.png')
	plt.show()
	plt.clf()

def main():
	df = pd.read_csv('threedata_shotscore_2.csv')
	plot_shooting_percentage_and_shotscore_over_seasons(df)

if __name__ == '__main__':
	main()


'''*****************************************************************************
Purpose: To extract insider trading data from sec website
This program extracts insider trading data from the sec website and stores it in
excel file.
Usage:
Enter a ticker (ex: 'AAPL, MSFT') or type 'all' to search thru all the tickers in file:

Here you can enter either single ticker or separate multiple tickers by comma or
type 'all' to go thru all the tickers in fName = 'ticker and cik.csv' (default name)

Enter the starting date (Ex: 2020-MM-DD): # enter date in this format no error checking

Would you like to extract data to excel file (Press enter for no OR enter filename):
Here either enter file name or press enter if you don't want to save the data.
By default the program doesn't display any data on shell, but you can add
print(all_df) or print(symbol_df) to print the data

Error checking:
I have implemented some error checking:
1.) If user enters incorrect ticker name ex: 'appl, msft, amzn, wrongone' in this
case program will skip 'appl' and 'wrongone' it will print out error msg with ticker
name and will continue to get insider data and save it to file for rest of the tickers.

2.) Let's say you are pulling the data for short period of time and there isn't much
info to calculate avg_purch/avg_sale and buy to sell ratio it will append rest
of the data to excel file.

-------------------------------------------------------------------
****************************************************************************'''
import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime
import csv

fName = 'ticker and cik.csv'    # set the ticker/CIK file name

data_dict, symbols = {}, []
with open(fName, 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        data_dict[row[0]] = row[1]   # creating a dict ex. format: 'msft': '789019'
        symbols.append(row[0])

'''taking user input'''
# ticker
ticker = input("Enter a ticker (ex: 'AAPL, MSFT') or type 'all' to search thru all the tickers in file: ").replace(" ", "")
ticker = ticker.lower()
if ticker == 'all': symbols = symbols
else:
    tickers = ticker.split(",")
    symbols = tickers

# date
start = input("Enter the starting date (Ex: 2020-MM-DD): ")
start2 = datetime.datetime(int(start[:4]),int(start[5:7]),int(start[8:]))
end_date = datetime.date.today()

# extract to excel
extract = input("Would you like to extract data to excel file (Press enter for no OR enter filename): ")
print()

def transaction(url):
    '''gets the transaction report from url
    Parameter:    url: string
                       url for data extraction
    Return: trans_report: soup object
                       transaction report
    '''
    response = requests.get(url)
    web = response.content
    soup = BeautifulSoup(web, 'html.parser')
    trans_report = soup.find('table', {'id':'transaction-report'})
    return trans_report

def insiders(all_data, cik):
    '''gets the insider info of given cik number
    Parameter:    all_data: list
                       empty list to add data
                  cik: string
                       cik number
    Return:       all_data: list
                       list of all the data
                  headers: list
                       list of the headers "Acquistion or Disposition...."
    '''
    num = 0
    url = f'https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK={cik}&type=&dateb=&owner=include&start={num}'

    urls, c = [], 0
    urls.append(url)
    for url in urls:
        c2, headers, data = 0, [], []
        report = transaction(url)
        for i in report.children:
            if i != '\n':
                collection = i.get_text().split('\n')
                c2 += 1
                for x in collection:
                    if x!= '':          # takng out empty data
                        if len(headers) != 12:  # 12 headers
                            headers.append(x)
                        else:
                            x = x.replace('$','')
                            # checking date boundary
                            if c == 1 and start > x:     # @ c==1, x is date
                                return  all_data, headers
                            elif (x == 'A' or x == 'D'):    # start of new row
                                if c != 0:
                                    all_data.append(data)
                                data, c = [], 0        # new row: clear data
                                data.append(x)
                                c += 1
                            else:
                                data.append(x)
                                c += 1

        if c2 == 81:
            all_data.append(data)
            num += 1
            url = f'https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK={cik}&type=&dateb=&owner=include&start={num*80}'
            urls.append(url)
    return  all_data, headers

def data_df(all_df):
    '''gets the insider info of given cik number
    Parameter:    all_df: list
                       list of all the data frame
    Return:       None
    '''
    done = 0
    for symbol in symbols:
        all_data = []

        # key error handling
        try: cik = data_dict[symbol]
        except Exception as e:
            print(f"The symbol {e} is not valid, rest of the data will be saved to excel file (if available)")
            if symbol == symbols[-1]: break
            else: continue
        all_data, headers = insiders(all_data, cik)

        # adding to data frame
        df = pd.DataFrame.from_records(all_data, columns=headers)
        done += 1
        print(f"Finished extracting {symbol.upper()} insider data from {start} till {end_date}.")
        print(f"Finished: {done}/{len(symbols)} symbols.")

        df['Purchchase'] = pd.to_numeric(df['Acquistion or Disposition'].apply(lambda x: 1 if x == 'A' else 0) * df['Number of Securities Transacted'])
        df['Sale'] = pd.to_numeric(df['Acquistion or Disposition'].apply(lambda x: 1 if x == 'D' else 0) * df['Number of Securities Transacted'])

        name = 'Transaction Type'
        sell = df['Transaction Type'].str.count("S-Sale").sum()
        buy = df['Transaction Type'].str.count("P-Purchase").sum()

        sale = df['Acquistion or Disposition'] == 'D'
        purch = df['Acquistion or Disposition'] == 'A'
        num_purch = len(df[purch])
        num_sale = len(df[sale])
        total_sale = int(df['Sale'].sum(skipna=True))
        total_purch = int(df['Purchchase'].sum(skipna=True))

        # adding data to separate df for excel
        symbol_df = pd.DataFrame({'Symbol': symbol.upper(),
                                           '# of Purchases': num_purch,
                                           '# of Sales': num_sale,
                                           'Total Bought': f'{total_purch:,}',
                                           'Total Sold': f'{total_sale:,}',
                                           'S-Sale count': f'{sell}',
                                           'P-Purchase count': f'{buy}'},
                                            index = [1])

        # handling division by zero error/adding data to separate df for excel
        try:
            avg_sale = int(total_sale/num_sale)
            avg_purch = int(total_purch/num_purch)
            ratio = round(num_purch/num_sale, 2)    # purchase to sell ratio

        except ZeroDivisionError as e:
            print(f"\n{e} error for '{symbol}' there isn't much data available to calculate avg sale/purch & ratio, data will be added to excel without these metrics")

        else:
            symbol_df.insert(3, 'Buy/Sell Ratio', ratio)
            symbol_df.insert(6, 'Avg Shares Bought', avg_purch)
            symbol_df.insert(7, 'Avg Shares Sold', avg_sale)

        symbol_df.set_index('Symbol', inplace=True)
        all_df.append(symbol_df)

def excel(all_df):
    '''adds the data to excel sheet, data is saved in same floder as this file
    Parameter:    all_df: list
                       list of all the data frame
    Return:       None
    '''
    try:
        if len(extract) != 0:
            pd.concat(all_df).to_excel(extract +'.xlsx', index = True)
            print(f"Extracted the data to {extract}.xlsx\n")
    except Exception as e: print(e)

if __name__ == '__main__':
    all_df = []
    data_df(all_df)
    excel(all_df)


import requests
import json
import execjs  # 必须，需要先用pip 安装，用来执行js脚本
from urllib.parse import quote

# 用来判断是否需要打印日志
debug = False

class Py4Js:

    def __init__(self):
        self.ctx = execjs.compile("""
            function TL(a) {
                var k = "";
                var b = 406644;
                var b1 = 3293161072;
                var jd = ".";
                var $b = "+-a^+6";
                var Zb = "+-3^+b+-f";
                for (var e = [], f = 0, g = 0; g  m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023),
                    e[f++] = m >> 18 | 240,
                    e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,
                    e[f++] = m >> 6 & 63 | 128),
                    e[f++] = m & 63 | 128)
                }
                a = b;
                for (f = 0; f < e.length; f++) a += e[f],
                a = RL(a, $b);
                a = RL(a, Zb);
                a ^= b1 || 0;
                0 > a && (a = (a & 2147483647) + 2147483648);
                a %= 1E6;
                return a.toString() + jd + (a ^ b)
            };
            function RL(a, b) {
                var t = "a";
                var Yb = "+";
                for (var c = 0; c = t ? d.charCodeAt(0) - 87 : Number(d),
                    d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
                    a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
                }
                return a
            }
        """)

    def get_tk(self, text):
        return self.ctx.call("TL", text)

def build_url(text, tk, tl='zh-CN'):
    """
    需要用转URLEncoder
    :param text:
    :param tk:
    :param tl:
    :return:
    """
    return 'https://translate.google.cn/translate_a/single?client=webapp&sl=auto&tl=' + tl + '&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&source=btn&ssel=0&tsel=0&kc=0&tk=' \
           + str(tk) + '&q=' + quote(text, encoding='utf-8')

def translate(js, text, tl='zh-CN'):
    """
    tl为要翻译的语言
    de：德语
    ja：日语
    sv：瑞典语
    nl：荷兰语
    ar：阿拉伯语
    ko：韩语
    pt：葡萄牙语
    zh-CN：中文简体
    zh-TW：中文繁体
    """

    header = {
        'authority': 'translate.google.cn',
        'method': 'GET',
        'path': '',
        'scheme': 'https',
        'accept': '*/*',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9,ja;q=0.8',
        # 'cookie': '_ga=GA1.3.110668007.1547438795; _gid=GA1.3.791931751.1548053917; 1P_JAR=2019-1-23-1; NID=156=biJbQQ3j2gPAJVBfdgBjWHjpC5m9vPqwJ6n6gxTvY8n1eyM8LY5tkYDRsYvacEnWNtMh3ux0-lUJr439QFquSoqEIByw7al6n_yrHqhFNnb5fKyIWMewmqoOJ2fyNaZWrCwl7MA8P_qqPDM5uRIm9SAc5ybSGZijsjalN8YDkxQ',
        'cookie': '_ga=GA1.3.110668007.1547438795; _gid=GA1.3.1522575542.1548327032; 1P_JAR=2019-1-24-10; NID=156=ELGmtJHel1YG9Q3RxRI4HTgAc3l1n7Y6PAxGwvecTJDJ2ScgW2p-CXdvh88XFb9dTbYEBkoayWb-2vjJbB-Rhf6auRj-M-2QRUKdZG04lt7ybh8GgffGtepoA4oPN9OO9TeAoWDY0HJHDWCUwCpYzlaQK-gKCh5aVC4HVMeoppI',
        # 'cookie': '',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',
        'x-client-data': 'CKi1yQEIhrbJAQijtskBCMG2yQEIqZ3KAQioo8oBCL+nygEI7KfKAQjiqMoBGPmlygE='
    }
    url = build_url(text, js.get_tk(text), tl)
    res = []
    try:
        r = requests.get(url, headers=header)
        result = json.loads(r.text)
        r.encoding = "UTF-8"
        if debug:
            print(r.url)
            print(r.headers)
            print(r.request.headers)
            print(result)

        res = result[0]
        if res is None:
            if result[7] is not None:
                # 如果我们文本输错，提示你是不是要找xxx的话，那么重新把xxx正确的翻译之后返回
                try:
                    correct_text = result[7][0].replace('', ' ').replace('', '')
                    if debug:
                        print(correct_text)
                    correct_url = build_url(correct_text, js.get_tk(correct_text), tl)
                    correct_response = requests.get(correct_url)
                    correct_result = json.loads(correct_response.text)
                    res = correct_result[0]
                except Exception as e:
                    if debug:
                        print(e)
                    res = []

    except Exception as e:
        res = []
        if debug:
            print(url)
            print("翻译" + text + "失败")
            print("错误信息:")
            print(e)
    finally:
        return res

def get_translate(word, tl='zh-CN'):
    js = Py4Js()
    translate_result = translate(js, word, tl)

    if debug:
        print("word== %s, tl== %s" % (word, tl))
        print(translate_result)
    return translate_result

if __name__ == '__main__':
    debug = True
    translate_text = '3.Hear voice prompt \"start configuration mode\". click \"reset successfully\" button\n'
    results = get_translate(translate_text, 'zh-CN')
    translate_result = ""

    if "." in translate_text or "?" in translate_text:
        for result in results:
            if result[0]:
                translate_result += result[0]
    else:
        result_translate = results[0]

    if debug:
        print("translate_result:" + translate_result)


from enum import Enum
from machination.helpers import accepts
from machination.exceptions import InvalidArgumentValue

class StringifiedEnum(Enum):
    def __str__(self):
        return str(self.value)

class Architecture(StringifiedEnum):
    i386 = "i386"
    x64 = "x64"

    @staticmethod
    @accepts(str)
    def fromString(val):
        vals = {
                "i386" : Architecture.i386,
                "x64" : Architecture.x64
                }
        if val in vals:
            return vals[val]
        else:
            raise InvalidArgumentValue("Unknown architecture")


# 1546 : 평균
import sys
input = sys.stdin.readline

n = int(input())
score = list(map(int, input().split()))

max = max(score)
sum = 0

for i in range(n):
    score[i] = score[i] / max * 100
    sum += score[i]

print(sum / n)


t = int(input())
c = 0
for _ in range(t):
    x, y = map(int, input().split())
    if x >= 3 and y >= 3 and x + y >= 15:
        c += 1
if c * 2 >= t:
    print('Genius')
else:
    print('Not Genius Yet')


import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

alpha=0.05
x1=np.array([56, 60, 62, 55, 71, 67, 59, 58, 64, 67])
x2=np.array([57, 58, 69, 48, 72, 70, 68, 71, 50, 53])
x3=np.array([57, 67, 49, 48, 47, 55, 66, 51, 54])
d = stats.kruskal(x1,x2,x3)
print('\n>>> Statistics = %.2f \n>>> Р-value = %.3f' % (d))
s, p = stats.kruskal(x1,x2,x3)
if p > alpha:
    print('>>> Cтатистически значимых различий нет, нулевая гипотеза '
          'не отвергается, время на дистанцию одинаковое.')
else:
    print('>>> Cтатистически значимые различия присутствуют, нулевую '
          'гипотезу отвергаем, время на дистанцию не одинаковое')


# -*- coding: utf-8 -*-
"""
Created on Tue Sep  5 17:12:20 2023

@author: jorji
"""

import folium

# Create a Folium map centered on the US
m = folium.Map(location=[37.0902, -95.7129], zoom_start=4)

# Add GeoJSON data with population density information
folium.Choropleth(
    geo_data=geojson_path,
    name='Population Density',
    data=gdf,
    columns=['GEOID', 'Population_Density'],
    key_on='feature.properties.GEOID',
    fill_color='YlOrRd',
    fill_opacity=0.7,
    line_opacity=0.2,
    legend_name='Population Density (people per square kilometer)',
).add_to(m)

# Add tooltips
style_function = lambda x: {'fillColor': 'white', 'color': 'black', 'fillOpacity': 0.1, 'weight': 0.1}
highlight_function = lambda x: {'fillColor': 'blue', 'color': 'blue', 'fillOpacity': 0.50, 'weight': 0.1}
g = folium.GeoJson(
    geojson_path,
    style_function=style_function,
    control=False,
    highlight_function=highlight_function,
    tooltip=folium.features.GeoJsonTooltip(
        fields=['NAME', 'Population_Density', 'POPULATION', 'ALAND'],
        aliases=['County:', 'Population Density:', 'Population:', 'Land Area:'],
        localize=True,
    ),
)
g.add_to(m)

# Add a layer control
folium.LayerControl().add_to(m)

# Save the map as an HTML file
m.save('population_density_map.html')

# Display the map
m


""" quick sort """

from random import randint

def quicksort(s_list):
    """ iterable quick sort """

    n = len(s_list)
    if n < 2:
        return s_list

    parts = [[0, n - 1]]
    while len(parts):
        part = parts.pop()
        start, finish = part
        base_index = randint(start, finish)
        base = s_list[base_index]
        s_list[base_index], s_list[start] = s_list[start], s_list[base_index]

        item_index = start
        first = start + 1
        last = finish

        while first <= last:
            if s_list[first] < base:
                result = -1
            elif s_list[last] > base:
                result = 1
            else:
                result = 0

            if result < 0:
                item_index = first
            else:
                while last > first:
                    if s_list[last] < base:
                        result = -1
                    elif s_list[last] > base:
                        result = 1
                    else:
                        result = 0

                    if result < 0:
                        item_index = first
                        s_list[last], s_list[first] = s_list[first], s_list[last]
                        last -= 1
                        break

                    last -= 1
            first += 1

        s_list[start], s_list[item_index] = s_list[item_index], s_list[start]

        if start < item_index - 1:
            parts.append([start, item_index - 1])

        if item_index + 1 < finish:
            parts.append([item_index + 1, finish])

    return s_list


__doc__ = """
Media
-----
Element to insert audio or video files into the web page. Uses HTML 5 media and audio tags
and the browser's default player.
"""

from nive.i18n import _
from nive.definitions import StagPageElement, ObjectConf, FieldConf
from nive.components.objects.base import PageElementFileBase

class media(PageElementFileBase):

    def IsVideo(self):
        return self.data.get("player")==u"video"

    def IsAudio(self):
        return self.data.get("player")==u"audio"

# media type definition ------------------------------------------------------------------
#@nive_module
configuration = ObjectConf(
    id = "media",
    name = _(u"Media"),
    dbparam = "mediafile",
    context = "nive.cms.media.media",
    template = "media.pt",
    selectTag = StagPageElement,
    icon = "nive.cms.cmsview:static/images/types/media.png",
    description = _(u"Element to insert audio or video files into the web page. Uses HTML 5 media"
                    u"and audio tags and the browser's default player.")
)

player = [{"id": u"video", "name": _(u"Video player")},
          {"id": u"audio", "name": _(u"Audio player")}]

configuration.data = [
    FieldConf(id="media", datatype="file", size=0, default=u"", name=_(u"Mediafile"), description=u""),
    FieldConf(id="mediaalt", datatype="file", size=0, default=u"",
              name=_(u"Alternative format"), description=_(u"To support all browsers you need to provide two different file formats.")),
    FieldConf(id="player", datatype="list", size=10, listItems=player, default=u"", name=_(u"Player"), description=u""),
    FieldConf(id="textblock", datatype="htext", size=10000, default=u"", fulltext=1, name=_(u"Text"), description=u"")
]

fields = ["title", "media", "mediaalt", "player", "textblock", "pool_groups"]
configuration.forms = {"create": {"fields":fields}, "edit": {"fields":fields}}

configuration.views = []


n, k, a = map(int, input().split())
cnt = 0
while cnt < k:
    cnt += 1
    #print(str(cnt)+'枚目： 人'+str(a))
    if a == n:
        a = 0
    if cnt != k-1:
        a += 1
print(a)
print((k % n)+1)


import cv2
import numpy as np
import argparse
from imutils.video import VideoStream

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", required=True,
    help="path to output video file")
# ap.add_argument("-p", "--picamera", type=int, default=-1,
#   help="whether or not the Raspberry Pi camera should be used")
ap.add_argument("-f", "--fps", type=int, default=20,
    help="FPS of output video")
ap.add_argument("-c", "--codec", type=str, default="MJPG",
    help="codec of output video")
args = vars(ap.parse_args())

# intalize the video writer and output options.
fourcc = cv2.VideoWriter_fourcc(*args["codec"])
writer = None
(h, w) = (None, None)
zeros = None

cap = cv2.VideoCapture("data_source/vtest.avi")

ret, frame1 = cap.read()
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[...,1] = 255

while(1):
    ret, frame2 = cap.read()
    next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)

    # check if the writer is None
    if writer is None:
        # store the image dimensions, initialzie the video writer,
        # and construct the zeros array
        (h, w) = frame1.shape[:2]
        writer = cv2.VideoWriter(args["output"], fourcc, args["fps"],
        (w , h ), True)
        zeros = np.zeros((h, w), dtype="uint8")

    flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.5, 3, 15, 3, 5, 1.2, 0)

    mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
    hsv[...,0] = ang*180/np.pi/2
    hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)
    rgb = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)

    cv2.imshow('frame2',rgb)
    writer.write(rgb)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
    elif k == ord('s'):
        cv2.imwrite('opticalfb.png',frame2)
        cv2.imwrite('opticalhsv.png',rgb)
    prvs = next

cap.release()
cv2.destroyAllWindows()
writer.release()


import json
from django.http import HttpResponse
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient

from ..models import State, StateTransition
from ..serializers import StateSerializer, StateTransitionSerializer

ID_RANGE = (1, 2**32 - 1)

class StateTest(TestCase):
    fixtures = ['test_state']

    def test_get_state_list(self):
        client = APIClient()
        response = client.get(reverse('state-list'), format='json')
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response, HttpResponse)

        data = json.loads(response.content)
        states_serializer = StateSerializer(data=data, many=True)
        self.assertTrue(states_serializer.is_valid())

    def test_get_state_list_for_room(self):
        ROOM_ID = 1

        client = APIClient()
        response = client.get(
            reverse('state-list'), {'room': ROOM_ID}, format='json'
        )
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response, HttpResponse)

        data = json.loads(response.content)
        states_serializer = StateSerializer(data=data, many=True)
        self.assertTrue(states_serializer.is_valid())

        for state_data in states_serializer.validated_data:
            state = State(**state_data)
            self.assertEqual(state.room_id, ROOM_ID)

    def test_get_statetransition(self):
        client = APIClient()
        response = client.get(reverse('statetransition-list'), format='json')
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response, HttpResponse)

        data = json.loads(response.content)
        statetransitions = StateTransitionSerializer(data=data, many=True)
        self.assertTrue(statetransitions.is_valid())

    def test_get_statetransition_for_room(self):
        ROOM_ID = 1

        client = APIClient()
        response = client.get(
            reverse('statetransition-list'), {'room': ROOM_ID}, format='json'
        )
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response, HttpResponse)

        data = json.loads(response.content)
        statetransitions_serializer = StateTransitionSerializer(
            data=data, many=True
        )
        self.assertTrue(statetransitions_serializer.is_valid())

        for statetransition_data in statetransitions_serializer.validated_data:
            statetransition = StateTransition(**statetransition_data)
            self.assertTrue(
                statetransition.from_state.room_id == ROOM_ID or
                statetransition.to_state.room_id == ROOM_ID
            )

    def test_post_new_state_and_new_statetransition(self):
        NEW_STATE = dict(
            name='c',
            room=1,
            is_entrypoint=False,
            x=24,
            y=2,
        )

        client = APIClient()
        response = client.post(reverse('state-list'), NEW_STATE, format='json')
        data = json.loads(response.content)
        states_serializer = StateSerializer(data=data, many=False)
        self.assertTrue(states_serializer.is_valid())
        state = State(**states_serializer.validated_data)
        self.assertIsNotNone(state.id)

        NEW_STATETRANSITION = dict(
            src=2,
            dest=state.id,
        )

        response = client.post(
            reverse('statetransition-list'), NEW_STATETRANSITION, format='json'
        )
        data = json.loads(response.content)
        statetransitions_serializer = StateTransitionSerializer(
            data=data, many=False
        )
        statetransitions_serializer.is_valid()
        self.assertTrue(statetransitions_serializer.is_valid())
        statetransition = StateTransition(
            **statetransitions_serializer.validated_data
        )
        self.assertIsNotNone(statetransition.id)


from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal

def format_version(n_version):
    if n_version % 100 == 0:
        return "%d.%d.%d" % (n_version/1000000, (n_version / 10000) % 100, (n_version / 100) % 100)
    else:
        return "%d.%d.%d.%d" % (n_version / 1000000, (n_version / 10000) % 100, (n_version / 100) % 100, n_version % 100)

def format_sub_version(name, n_client_version, comments):
    ss = '/%s:%s' % (name, format_version(n_client_version))
    if len(comments) > 0:
        ss += '('
        for i in range(len(comments)):
            if i > 0:
                ss += "; "
            ss += comments[i]
        ss += ')'
    ss += '/'
    return ss

class UacommentTest(BitcoinTestFramework):
    def set_test_params(self):
        self.num_nodes = 1
        self.setup_clean_chain = True

    def run_test(self):
        self.log.info("test multiple -uacomment")
        test_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-12:-1]
        assert_equal(test_uacomment, "(testnode0)")

        self.restart_node(0, ["-uacomment=foo"])
        foo_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-17:-1]
        assert_equal(foo_uacomment, "(testnode0; foo)")

        self.log.info("test -uacomment max length")
        self.stop_node(0)
        str_sub_version_len = len(format_sub_version("Satoshi", 1010000, ['testnode0', 'a'*256]))
        self.log.info("str_sub_version_len: %d" % str_sub_version_len)
        expected = "Total length of network version string (%d) exceeds maximum length (256). Reduce the number or size of uacomments." % str_sub_version_len
        self.assert_start_raises_init_error(0, ["-uacomment=" + 'a' * 256], expected)

        self.log.info("test -uacomment unsafe characters")
        for unsafe_char in ['/', ':', '(', ')']:
            expected = "User Agent comment (" + unsafe_char + ") contains unsafe characters"
            self.assert_start_raises_init_error(0, ["-uacomment=" + unsafe_char], expected)

if __name__ == '__main__':
    UacommentTest().main()


import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy.stats

parser = argparse.ArgumentParser()
parser.add_argument('-o', type=str, required=True, help="figure outdir")
args = parser.parse_args()

if not os.path.exists(args.o):
    os.makedirs(args.o)

#data = np.loadtxt("data_regions.dat", skiprows=1)
#    Sample         CB         HB        HPF         HY         IC         TH
data = np.loadtxt("data_regions.dat", skiprows=1, usecols=(1,2,3,4,5,6))
headers = np.loadtxt("data_regions.dat", skiprows=1, usecols=(0), dtype=str)

dx=3.26*1.e-3
dz=3.00*1.e-3
#regions = ["CB", "HB", "HPF", "HY", "IC", "TH"]
#regions = ["Cerebellum", "Brain stem", "Hippocampus", "Hypothalamus", "Cortex", "Thalamus"]
regions = ["Brain stem", "Hippocampus", "Hypothalamus", "Cortex", "Thalamus"]
vp = dx*dx*dz

Nc = np.shape(data)[1]
x_pos = np.arange(len(regions))

my_cmap = plt.cm.get_cmap('plasma')

group1=["840298_52_P_20",  "840298_16_P_17", "840298_50_P_19"]
group2=["340258_2LD_5",    "840258_3_LD_6",  "454371_17_LD_7"]
group3=["340299_35_22_HD", "840295_42_HD",   "840295_40_HD_27"]

# Compute mean/std of segmented volume per group
g1 = []
for i,s in enumerate(group1):
    idx1 = np.where(headers==s)[0]
    o = data[idx1,:][0] * vp
    g1.append( o )
means1 = np.mean(g1, axis=0)[1::]
stads1 = np.std( g1, axis=0)[1::]

g2 = []
for i,s in enumerate(group2):
    idx1 = np.where(headers==s)[0]
    o = data[idx1,:][0] * vp
    g2.append( o )
means2 = np.mean(g2, axis=0)[1::]
stads2 = np.std( g2, axis=0)[1::]

g3 = []
for i,s in enumerate(group3):
    idx1 = np.where(headers==s)[0]
    o = data[idx1,:][0] * vp
    g3.append( o )
means3 = np.mean(g3, axis=0)[1::]
stads3 = np.std( g3, axis=0)[1::]

# fig, ax = plt.subplots(figsize=(9,5))
# #ax.bar(x_pos-0.25, means1, yerr=stads1, align='edge', width=0.2, capsize=7, color='m', label="Toxofilin-Cre")
# #ax.bar(x_pos,      means2, yerr=stads2, align='edge', width=0.2, capsize=7, color='c', label="Gra16-Cre")
# #ax.bar(x_pos+0.25, means3, yerr=stads3, align='edge', width=0.2, capsize=7, color='#ffea00', label="saline")
# ax.bar(x_pos-0.25, means1, align='edge', width=0.2, edgecolor='k', linewidth=0.5, color='m', label="Control")
# ax.bar(x_pos,      means2, align='edge', width=0.2, edgecolor='k', linewidth=0.5, color='c', label="Low dose")
# ax.bar(x_pos+0.25, means3, align='edge', width=0.2, edgecolor='k', linewidth=0.5, color='#ffea00', label="High dose")
# ax.set_ylabel(r'Cell volume ($mm^3$)', fontsize=13)
# ax.set_xticks(x_pos)
# ax.set_xticklabels(regions, fontsize=13)
# ax.tick_params(axis='y', which='major', labelsize=13)
# plt.legend(prop={'size': 11})
# plt.savefig("%s/pic_per_region_counts_group_averages.png"%args.o, transparent=True)

fig, ax = plt.subplots(figsize=(9,5))
ax.bar(x_pos-0.25, means1, yerr=stads1, align='edge', width=0.2, capsize=7, edgecolor='k', linewidth=0.5, color='m', label="Control")
ax.bar(x_pos,      means2, yerr=stads2, align='edge', width=0.2, capsize=7, edgecolor='k', linewidth=0.5, color='c', label="Low dose")
ax.bar(x_pos+0.25, means3, yerr=stads3, align='edge', width=0.2, capsize=7, edgecolor='k', linewidth=0.5, color='#ffea00', label="High dose")
ax.set_ylabel(r'Cell volume ($mm^3$)', fontsize=13)
ax.set_xticks(x_pos)
ax.set_xticklabels(regions, fontsize=13)
ax.tick_params(axis='y', which='major', labelsize=13)
ax.set_ylim(bottom=0)
plt.legend(prop={'size': 11})
plt.savefig("%s/pic_per_region_counts_group_averages_w_std.png"%args.o, transparent=True)

# Compute 2-sided t-test
from scipy.stats import ttest_ind_from_stats

tCL = ttest_ind_from_stats(mean1=means2, std1=stads2, nobs1=3,   mean2=means1, std2=stads1, nobs2=3)
print("LD group", tCL)

tCH = ttest_ind_from_stats(mean1=means3, std1=stads3, nobs1=3,   mean2=means1, std2=stads1, nobs2=3)
print("HD group", tCH)

print(np.shape(g1))
print(np.shape(regions))
print(np.shape(means1))

# Dump data in CSV
fw = open("pvalues_SELECTED_regions.csv", 'w')

fw.write("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\n " % ("Region name", "vol P1", "vol P2", "vol P3", "avg_P",  "vol LD1", "vol LD2", "vol LD3", "avg_LD",  "vol HD1", "vol HD2", "vol HD3", "avg HD",  "st LD", "pv LD", "st HD", "pv HD") )

for i in range(len(means1)):
    fw.write("%s, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g\n " % (regions[i].replace(',', ''), g1[0][i+1], g1[1][i+1], g1[2][i+1], means1[i], g2[0][i+1], g2[1][i+1], g2[2][i+1], means2[i], g3[0][i+1], g3[1][i+1], g3[2][i+1], means3[i], tCL.statistic[i], tCL.pvalue[i], tCH.statistic[i], tCH.pvalue[i] ) )

fw.close()


"""
CRIE UM PROGRAMA QUE TENHA A FUNÇÃO LEIAINT(),
QUE VAI FUNCIONAR DE FORMA SEMELHANTE Á FUNÇÃO
INPUT() DO PYTHON, SÓ QUE FAZENDO A VALIDAÇÃO
PARA ACEIRTAR APENAS UM VALOR NUMÉRICO.

EX:
N = LEIAINT('DIGITE UM N')
"""

def leiaInt(num):
      while not num.isnumeric():
            num = input('Digite um número: ')
            if not num.isnumeric():
                  print('\033[0;31mERROR! Digite um número inteiro válido.\033[m')

      return num

# PROGRAMA PRINCIPAl
n = leiaInt("Digite um número: ")
print(f'Você acabou de digitar o número {n}')


import random
import math

print('f -> Farmers and s -> Soldiers')
input_num=int(input('Enter the number of input : '))
soldiers=math.ceil(input_num/2)
farmers=soldiers-1

list=[]
for i in range(soldiers):
	list.append('s')
for i in range(farmers):
	list.append('f')
random.shuffle(list)			# Shuffling List
print('Input : ',list)

j=0
cost=0
for i in range(soldiers+farmers):	# Sorting Arrangement
	cost+=1
	j=i
	check=0
	if i%2==0 and list[i]=='f':
		while(list[j]!='s'):
			j+=1
			cost+=1
		check=1
	if i%2!=0 and list[i]=='s':
		while(list[j]!='f'):
			j+=1
			cost+=1
		check=1

	if check==1:
		temp=list[i]
		list[i]=list[j]
		list[j]=temp
		cost+=1

print('Output : ',list)
print('Total Cost : ',cost)


import sys
input = sys.stdin.readline

N = int(input())
kw = []
for i in range(N):
    a  = list(map(int, input().split()))
    a.append(i)
    kw.append(a)

c = sorted(kw, key = lambda x : -x[0])
print(c)
print(1)
for j in range(N):
    if c[j][1] > c[j + 1][1]:
        print(j+1)
        cur = j+1
    else:
        print(cur)


#######################################################
# This simulation analyzes performance of the mean field approximation
# versus the local approximation for small times, for various values
# of kappa (degree of the tree) and beta for the Ising model.
# These two approximations are compared directly, and measured by
# the total variation distance between the joints of the root node
# and one of its neighbors, as well as the distributions of the root,
# joint distributions with more neighbors, and trajectories as well.
#
# There is plotting code to visualize the total variation distances.
#######################################################

import os
import sys
sys.path.append("../SimulateProcesses")
sys.path.append("../SimulateProcesses/Ising")
from IsingModelSimulation import run_mean_field_simulations
import Create_Graphs as graphs
import Dyadic_measures as measures
import Ising_Model as Ising
import IsingMonitor as monitor
import Misc

# import standard libraries
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import itertools as itr
import functools
import numpy as np

import ast
import importlib
import argparse

from mpl_toolkits.axes_grid1 import make_axes_locatable

p = 0.9 #update parameter
bias = -0.2
p_0 = (1+bias)/2

## intake what parameters to run/ analyze
kappa_params = [2,3,4,5,6,7]
beta_params = np.array(np.linspace(0,2,11))
# k = [1]

# ideally want this to be larger
T = 3

### Collect Data
# use Pandas, want multidimensional index;
# columns should be dynamics; mean field; k-approximation,various vals of k.

columns = ["Local Approx", "Mean Field"]
idx_iter = [kappa_params, beta_params]
index = pd.MultiIndex.from_product(idx_iter, names = ['kappa','beta'])
zero_df = np.zeros((len(kappa_params)*len(beta_params),len(columns)))

# probability at node 0, time T
joint2_prob_df = pd.DataFrame(zero_df,columns = columns, index = index)

def create_product_measure(bernoulli_p, dim):
	initial = np.zeros(tuple([2]*(dim)))
	for idx in itr.product([0,1],repeat = dim):
		initial[idx] = ((bernoulli_p)**(sum(idx)))*((1-bernoulli_p)**(dim + 1 - sum(idx)))

	return measures.dyadic_measure(initial,k = 1, dimension = dim)

def create_product_measure_from_vec(vec, dim):
	probs = np.array([1 - np.array(vec),vec])
	initial = np.zeros(tuple([len(vec)]*(dim)))
	for idx in itr.product(list(range(len(vec))),repeat = dim):
		initial[idx] = np.product([vec[i] for i in idx])

	return initial

def idx2bin(idx):
	return int(np.dot(np.power(2,range(len(idx))),idx))

# compute the distances
total_variations_2_marginal = np.zeros((len(kappa_params),len(beta_params)))
total_variations_root_marginal = np.zeros((len(kappa_params),len(beta_params)))
total_variations_3_marginal = np.zeros((len(kappa_params),len(beta_params)))
total_variations_kappa_marginal = np.zeros((len(kappa_params),len(beta_params)))
total_variations_history = np.zeros((len(kappa_params),len(beta_params)))

idx = pd.IndexSlice
## run local approximation
for i in range(len(kappa_params)):
	for j in range(len(beta_params)):

		print(kappa_params[i],beta_params[j])
	### Get the mean field data
		(root, joint, root_occ, joint_occ, root_history, joint_history) = \
			run_mean_field_simulations(kappa_params[i], p_0, T, p, beta_params[j], load_data = False)

		single_mf = np.array([1-root, root])
		joint2_mf= create_product_measure(root,2)
		joint3_mf = create_product_measure(root,3)
		joint_kappa_mf = create_product_measure(root,kappa_params[i]+1)

		# to get joint history mf, encode root history via binary
		probs = np.array([1-np.array(root_history),root_history])
		vec = [0]*(2**T)
		for idx in itr.product([0,1], repeat = T):
			vec[idx2bin(tuple(reversed(idx)))] = np.product(probs[idx,range(T)])

		joint_history_mf = create_product_measure_from_vec(vec, kappa_params[i] + 1)

		### get the local approximation data
		filename = "/Users/timothysudijono/Desktop/localapproxdata/localapprox_kappa{}_p0.9_beta{:.1f}_T{}_bias{}.npy".format(kappa_params[i],beta_params[j], T, bias)
		measure_history = np.load(filename)

		process = monitor.MonitorLocalApproximation(np.zeros((2,2,2)),p,beta_params[j])
		process.measure_history = measure_history

		single_la = process.get_fixed_time_measure([0],T-1)
		joint2_la = process.get_fixed_time_measure((0,1),T-1)
		joint3_la = process.get_fixed_time_measure((0,1,2),T-1)
		joint_kappa_la = process.get_fixed_time_measure(list(range(kappa_params[i] + 1)),T-1)

		joint_history_la = measure_history[-1]

		total_variations_root_marginal[i,j] = np.sum(np.abs(single_la - single_mf))
		total_variations_2_marginal[i,j] = np.sum(np.abs(joint2_la - joint2_mf))
		total_variations_3_marginal[i,j] = np.sum(np.abs(joint3_la - joint3_mf))
		total_variations_kappa_marginal[i,j] = np.sum(np.abs(joint_kappa_la - joint_kappa_mf))
		total_variations_history[i,j] = np.sum(np.abs(joint_history_la - joint_history_mf))

def visualize_total_var(array, title):
	fig, ax = plt.subplots(1,1, figsize = (10,10))

	cmap = matplotlib.cm.viridis
	norm = plt.Normalize(0, 2)

	betas = np.array(np.linspace(0,2,81))
	kappas = 2*np.exp(2*betas)/(np.exp(2* betas) - 1)
	ax.plot(5.5*betas-0.5, kappas - 2, color = 'red', label = "Critical Value")
	im1 = ax.imshow(array[::-1,],cmap = cmap.reversed(), norm = norm, extent = [0 - 0.5,len(beta_params)-1 + 0.5,0 - 0.5,len(kappa_params)-1 + 0.5])

	tick_size = 6.5

	ax.set_xlabel('Beta',fontsize = 10)
	ax.set_xticks(np.arange(len(beta_params)))
	ax.set_xticklabels(labels = ["{:0.1f}".format(beta) for beta in beta_params],fontsize = tick_size )

	ax.set_ylabel('Kappa',fontsize = 10)
	ax.set_yticks(np.arange(len(kappa_params)))
	ax.set_yticklabels(labels = list(kappa_params),fontsize = tick_size )
	#ax.legend(loc='upper right', bbox_to_anchor=(0.15, 0.0))

	ax.set_title(title)

	for i in range(len(kappa_params)):
		for j in range(len(beta_params)):
			text = ax.text(j, i, "{:0.2f}".format(array[i, j]),
				ha="center", va="center", color="w")

	divider1 = make_axes_locatable(ax)
	cax1 = divider1.append_axes('right', size='5%', pad=0.1)
	fig.colorbar(im1,cax1,orientation = 'vertical')

	plt.show()

visualize_total_var(total_variations_root_marginal, "Total Variation of Root")
visualize_total_var(total_variations_2_marginal, "Total Variation of 2 Node Joint")
visualize_total_var(total_variations_3_marginal, "Total Variation of 3 Node Joint")
visualize_total_var(total_variations_kappa_marginal, "Total Variation of Kappa Node Joint")
visualize_total_var(total_variations_history, "Total Variation of Kappa Node Trajectory")


import logging
from datetime import datetime
from ftplib import FTP, FTP_TLS
from os import path as pth
from typing import List

from kodi.AppConfiguration import FtpConfiguration
from kodi.exception.CannotConnectToFtpException import CannotConnectToFtpException
from kodi.exception.UnknownFtpProtocolException import UnknownFtpProtocolException
from kodi.fs.FileItem import FileItem
from kodi.fs.FileSystemHelper import FileSystemHelper

logger = logging.getLogger(__name__)

class FtpService:

    def __init__(self, config: FtpConfiguration):
        self.config = config
        self.__connect()

    def __connect(self) -> None:
        if self.config.protocol == "FTP":
            self.ftp = FTP()
        elif self.config.protocol == "SFTP":
            self.ftp = FTP_TLS()
        else:
            raise UnknownFtpProtocolException(self.config.protocol)
        self.ftp.connect(host=self.config.host, port=self.config.port, timeout=10)
        resp: str = self.ftp.login(self.config.username, self.config.passwd)
        if resp.startswith("230"):
            logger.info("Successfully connect to FTP server")
        else:
            raise CannotConnectToFtpException(self.config)

    def read_file_items(self, path: str) -> List[FileItem]:
        files = list()
        items = list()
        self.ftp.cwd(path)
        self.ftp.dir(items.append)
        for item in items:
            name, is_file, size = self.__parse_list_line(item)
            if is_file:
                file_path = path + "/" + name
                mdt = self.ftp.sendcmd("MDTM " + file_path)
                dt = self.__parse_mdt(mdt)
                files.append(FileItem(file_path, dt, int(size)))
        return files

    def download_file(self, ftp_path: str, store_path: str) -> FileItem:
        a_store_path = pth.abspath(store_path)
        logger.info("Try download file from ftp \"%s\" to \"%s\"" % (ftp_path, a_store_path))
        try:
            self.ftp.retrbinary("RETR " + ftp_path, open(a_store_path, 'wb').write)
        except Exception as ex:
            logger.error("Cannot download file", ex)
            raise ex
        return FileSystemHelper.read_file_item(a_store_path)

    def close(self):
        self.ftp.close()
        logger.info("Close ftp connection with server")

    @staticmethod
    def __parse_list_line(line: str) -> tuple:
        items = line.split()
        is_file = True
        if items[0].startswith("d"):
            is_file = False
        size = items[4]
        name = items[8:]
        return str.join(" ", name), is_file, size

    @staticmethod
    def __parse_mdt(mdt: str) -> datetime:
        items = mdt.split()
        dt = items[1]
        year = int(dt[0:4])
        month = int(dt[4:6])
        day = int(dt[6:8])
        hour = int(dt[8:10])
        minute = int(dt[10:12])
        second = int(dt[12:14])
        return datetime(year, month, day, hour, minute, second)


from collections import Counter
import sys
sys.path.append('../../mymodule')
import mm

if __name__ == '__main__':
    f = open('./col1.txt')
    target = f.readlines()
    counter = Counter(target)
    for word, cnt in counter.most_common():
        word = word[0:-1]
        mm.chkprint(word, cnt)


# 주어진 N 길이의 숫자열을 오름차순으로 정렬하여 출력하라.

# [제약 사항]

# N 은 5 이상 50 이하이다.

# [입력]

# 가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.

# 각 테스트 케이스의 첫 번째 줄에 N 이 주어지고, 다음 줄에 N 개의 숫자가 주어진다.

# [출력]

# 출력의 각 줄은 '#t'로 시작하고, 공백을 한 칸 둔 다음 정답을 출력한다.

# (t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)

T = int(input())
for i in range(1, T+1):
    N = int(input())
    nums = sorted(map(int, input().split()))
    print("#{} ".format(i), end='')
    for j in nums:
        print(j, end=" ")
    print()


# RubberNugget HID Attack Tool
# By Kody Kinzie & Alex Lynd
# Optimized by NullUsxr
# Forked from https://github.com/dbisu/pico-ducky

# import libraries
import board
import busio
import displayio
import os
import terminalio
import time
import usb_hid
from adafruit_debouncer import Debouncer
from adafruit_display_text import label
from adafruit_display_shapes.line import Line
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS as KeyboardLayout
from adafruit_hid.keycode import Keycode
from digitalio import DigitalInOut, Pull

# Backup code in case the new display config doesn't work
# displayio.release_displays()
# WIDTH = 130
# HEIGHT = 64
# BORDER = 1
# i2c = busio.I2C(SCL, SDA)
# display_bus = displayio.I2CDisplay(i2c, device_address=0x3c)
# display = adafruit_displayio_sh1106.SH1106(display_bus, width=WIDTH, height=HEIGHT)

# display config for SH1106
displayio.release_displays()
BORDER = 1
i2c = busio.I2C(SCL, SDA)
display_bus = displayio.I2CDisplay(i2c, device_address=0x3c)
# display = adafruit_displayio_sh1106.SH1106(display_bus, width=WIDTH, height=HEIGHT)
display = board.DISPLAY

# use default font & white for font
font = terminalio.FONT
color = 0xFFFFFF

# configure button input
pins = (board.IO9, board.IO18, board.IO11, board.IO7)
buttons = []  # will hold list of Debouncer objects
for pin in pins:  # set up each pin
    tmp_pin = DigitalInOut(pin)  # defaults to input
    tmp_pin.pull = Pull.UP  # turn on internal pull-up resistor
    buttons.append(Debouncer(tmp_pin))

# keyboard configuration
kbd = Keyboard(usb_hid.devices)
layout = KeyboardLayout(kbd)

# payload config & root dir
payloadstatus = ""
defaultDelay = 0
path = "payloads"

# get pressed button
def getButtonPressed():
    for i in range(len(buttons)):
        buttons[i].update()
        if buttons[i].fell:
            return i
    return -1

# draw key map function

def drawNavMap(map_vals):
    global path
    map = ["UP   ", "DOWN ", "LEFT ", "RIGHT"]

    # insert "back" as down value or blank values
    if len(map_vals) < 4:
        for i in range(len(map_vals), 4):
            map_vals.insert(i, "")
        map_vals.insert(1, "Back")
    counter = 0
    navScreen = displayio.Group()

    # iterate text values and add to screen
    for i in map_vals[:4]:
        text_area = label.Label(font, text=map[counter] + ": " + i, color=color)
        text_area.x = 2
        text_area.y = 3 + (10 * counter)
        counter += 1
        navScreen.append(text_area)

    # draw stuff
    navScreen.append(Line(0, 50, 127, 50, 0xFFFFFF))
    navScreen.append(Line(0, 51, 127, 51, 0xFFFFFF))
    text_area = label.Label(font, text="Dir: " + path[path.rfind("/") + 1:], color=color)
    text_area.x = 2
    text_area.y = 57
    navScreen.append(text_area)
    display.show(navScreen)

    # update path until text file reached
    currButton = -1
    while currButton == -1:
        currButton = getButtonPressed()
    if "Back" in map_vals and currButton == 1:
        path = path[0:path.rfind("/")]
    elif map_vals[currButton] == "":
        pass
    else:
        path += "/" + map_vals[currButton]
    if ".txt" in path:
        runPayload(path)
        path = path[0:path.rfind("/")]
        path = path[0:path.rfind("/")]

# draw and execute payload

def drawPayload(status, payloadName):
    # draw Nugget to indicate status!

    if status == "START":
        statusText = "executing"
        bitmap = displayio.OnDiskBitmap("/faces/payload-running.bmp")
    else:
        statusText = "finished"
        bitmap = displayio.OnDiskBitmap("/faces/payload-finished.bmp")
    # Setup the file as the bitmap data source
    tile_grid = displayio.TileGrid(bitmap, pixel_shader=bitmap.pixel_shader)

    group = displayio.Group()  # Create a Group to hold the TileGrid
    group.append(tile_grid)
    group.append(Line(0, 50, 129, 50, 0xFFFFFF))
    group.append(Line(0, 51, 129, 51, 0xFFFFFF))
    group.append(Line(0, 11, 129, 11, 0xFFFFFF))
    group.append(Line(0, 12, 129, 12, 0xFFFFFF))

    text = ("STATUS: " + statusText)
    text_area = label.Label(font, text=text, color=color)
    text_area.x = 2
    text_area.y = 57
    group.append(text_area)
    text = (payloadName[path.rfind("/") + 1:])
    if len(text) > 21:
        text = text[:18] + "..."

    text_area = label.Label(font, text=text, color=color)
    text_area.x = 2
    text_area.y = 3
    group.append(text_area)
    display.show(group)
    time.sleep(3)

# duckyscript command map

duckyCommands = {
    'WINDOWS': Keycode.WINDOWS, 'GUI': Keycode.GUI,
    'APP': Keycode.APPLICATION, 'MENU': Keycode.APPLICATION, 'SHIFT': Keycode.SHIFT,
    'ALT': Keycode.ALT, 'CONTROL': Keycode.CONTROL, 'CTRL': Keycode.CONTROL,
    'DOWNARROW': Keycode.DOWN_ARROW, 'DOWN': Keycode.DOWN_ARROW,
    'LEFTARROW': Keycode.LEFT_ARROW, 'LEFT': Keycode.LEFT_ARROW,
    'RIGHTARROW': Keycode.RIGHT_ARROW, 'RIGHT': Keycode.RIGHT_ARROW,
    'UPARROW': Keycode.UP_ARROW, 'UP': Keycode.UP_ARROW, 'BREAK': Keycode.PAUSE,
    'PAUSE': Keycode.PAUSE,
    'CAPSLOCK': Keycode.CAPS_LOCK, 'DELETE': Keycode.DELETE,
    'END': Keycode.END, 'ESC': Keycode.ESCAPE, 'ESCAPE': Keycode.ESCAPE,
    'HOME': Keycode.HOME, 'INSERT': Keycode.INSERT,
    'NUMLOCK': Keycode.KEYPAD_NUMLOCK, 'PAGEUP': Keycode.PAGE_UP,
    'PAGEDOWN': Keycode.PAGE_DOWN, 'PRINTSCREEN': Keycode.PRINT_SCREEN,
    'ENTER': Keycode.ENTER,
    'SCROLLLOCK': Keycode.SCROLL_LOCK, 'SPACE': Keycode.SPACE, 'TAB': Keycode.TAB,
    'A': Keycode.A, 'B': Keycode.B, 'C': Keycode.C, 'D': Keycode.D, 'E': Keycode.E,
    'F': Keycode.F, 'G': Keycode.G, 'H': Keycode.H, 'I': Keycode.I, 'J': Keycode.J,
    'K': Keycode.K, 'L': Keycode.L, 'M': Keycode.M, 'N': Keycode.N, 'O': Keycode.O,
    'P': Keycode.P, 'Q': Keycode.Q, 'R': Keycode.R, 'S': Keycode.S, 'T': Keycode.T,
    'U': Keycode.U, 'V': Keycode.V, 'W': Keycode.W, 'X': Keycode.X, 'Y': Keycode.Y,
    'Z': Keycode.Z, 'F1': Keycode.F1, 'F2': Keycode.F2, 'F3': Keycode.F3,
    'F4': Keycode.F4, 'F5': Keycode.F5, 'F6': Keycode.F6, 'F7': Keycode.F7,
    'F8': Keycode.F8, 'F9': Keycode.F9, 'F10': Keycode.F10, 'F11': Keycode.F11,
    'F12': Keycode.F12,
}

# ducky parser by @dbisu

def convertLine(line):
    newline = []
    print(line)
    # loop on each key - the filter removes empty values
    for key in filter(None, line.split(" ")):
        key = key.upper()
        # find the keycode for the command in the list
        command_keycode = duckyCommands.get(key, None)
        if command_keycode is not None:
            # if it exists in the list, use it
            newline.append(command_keycode)
        elif hasattr(Keycode, key):
            # if it's in the Keycode module, use it (allows any valid keycode)
            newline.append(getattr(Keycode, key))
        else:
            # if it's not a known key name, show the error for diagnosis
            print(f"Unknown key: <{key}>")
    print(newline)
    return newline

def runScriptLine(line):
    for k in line:
        kbd.press(k)
    kbd.release_all()

def sendString(line):
    layout.write(line)

def parseLine(line):
    global defaultDelay
    if line[0:3] == "REM":
        # ignore ducky script comments
        pass
    elif line[0:5] == "DELAY":
        time.sleep(float(line[6:]) / 1000)
    elif line[0:6] == "STRING":
        sendString(line[7:])
    elif line[0:13] == "DEFAULT_DELAY":
        defaultDelay = int(line[14:]) * 10
    elif line[0:12] == "DEFAULTDELAY":
        defaultDelay = int(line[13:]) * 10
    else:
        newScriptLine = convertLine(line)
        runScriptLine(newScriptLine)

# payload run function

def runPayload(payloadPath):
    # startup indicator
    drawPayload("START", payloadPath)
    f = open(payloadPath, "r", encoding='utf-8')
    previousLine = ""
    duckyScript = f.readlines()
    for line in duckyScript:
        print(line)
        line = line.rstrip()
        if line[0:6] == "REPEAT":
            for i in range(int(line[7:])):
                # repeat the last command
                parseLine(previousLine)
                time.sleep(float(defaultDelay) / 1000)
        else:
            parseLine(line)
            previousLine = line
        time.sleep(float(defaultDelay) / 1000)

    # finish indicator
    drawPayload("STOP", payloadPath)
    time.sleep(.5)

# create default directories

default_os = ["Windows", "Starred", "Mac", "Linux"]
for os_name in default_os:
    if os_name not in (os.listdir("payloads")):
        os.mkdir(os_name)

while True:
    # check for root payload directory
    if path != "payloads":
        drawNavMap(os.listdir(path)[:3])  # take first 3 items from list
    else:
        drawNavMap(os.listdir(path))

# Unused imports
# Import them if you need them?

# import ipaddress
# import neopixel
# import socketpool
# import wifi
# import ampule
# import base64
# import adafruit_binascii as binascii
# import adafruit_displayio_sh1106
# import adafruit_requests
# import adafruit_requests as requests
# import ssl
# import adafruit_framebuf


from typing import List, Tuple, Set
from collections import Counter

# Implementation of the super-stable-matching algorithm described in
# "Stable marriage and indifference" by Robert W. Irving (1990).
# Both preference inputs should be lists of preference lists in descending order for each
# group member; the preference lists should consist of sets of indices in the opposite group
# list which are tied in priority.
def super_stable_matching(g1_prefs: List[List[Set[int]]], g2_prefs: List[List[Set[int]]]):
    pairings: Set[Tuple[int, int]] = set()  # A simple set of pairs for now

    while True:
        # Find the first unpaired member of group 1 (this_g1_index)
        paired_g1s = set(g1 for g1, _ in pairings)
        this_g1_index = next((i for i in range(len(g1_prefs)) if i not in paired_g1s), None)

        # If there are none, then all members of group 1 are paired, and we have a maximum matching.
        if this_g1_index is None:
            return pairings

        this_g1_list = g1_prefs[this_g1_index]

        # If this preference list is empty, then this member cannot be paired, so a full matching
        # cannot exist.
        if len(this_g1_list) == 0:
            return None
        else:
            # Add pairings from the member of group 1 to all first-ranked members of group 2.
            # At the same time, discard any inferior entries from the group 2 members' lists as well
            # as the corresponding entries in the group 1 lists and any pairings involving these entries.
            for this_g2_index in this_g1_list[0]:
                pairings.add((this_g1_index, this_g2_index))
                g2_list_index = next(i for i in range(len(g2_prefs[this_g2_index]))
                                     if this_g1_index in g2_prefs[this_g2_index][i])
                for inferior_g1_index in (index for i in range(g2_list_index + 1, len(g2_prefs[this_g2_index]))
                                                for index in g2_prefs[this_g2_index][i]):
                    pairings.discard((inferior_g1_index, this_g2_index))
                    for inferior_g1_pref_set in g1_prefs[inferior_g1_index]:
                        inferior_g1_pref_set.discard(this_g2_index)

                g2_prefs[this_g2_index] = g2_prefs[this_g2_index][:g2_list_index + 1]

        # Find members of group 2 which are involved in multiple pairings, and remove all
        # of their pairings.
        # Also, remove the bottom layer from such members' preference lists as well as the
        # respective preferences in group 1.
        g2_pairing_counts = Counter(g2_index for (_, g2_index) in pairings)
        for (g2_index, g2_pair_count) in g2_pairing_counts.items():
            if g2_pair_count >= 2:
                pairings_to_remove = {(g1, g2) for (g1, g2) in pairings if g2 == g2_index}
                pairings.difference_update(pairings_to_remove)

                for worst_g1_index in g2_prefs[g2_index][-1]:
                    for g1_pref_set in g1_prefs[worst_g1_index]:
                        g1_pref_set.discard(g2_index)

                g2_prefs[g2_index].pop()

        # Prune any empty tie sets from group 1 (since some set members may have been discarded).
        for g1_pref_list in g1_prefs:
            g1_pref_list[:] = [this_set for this_set in g1_pref_list if len(this_set) >= 1]

# Run a couple of test examples
if __name__ == "__main__":
    print(super_stable_matching([[{0}, {1, 2}], [{2}, {0, 1}], [{1}, {2}, {0}]],
                                [[{0}, {1}, {2}], [{2, 0}, {1}], [{1}, {2, 0}]]))
    print(super_stable_matching([[{0}, {1}], [{0}, {1}]],
                                [[{0}, {1}], [{0}, {1}]]))