"""Tic-tac-toe game on a 6x6 field.
The image and sound files are located in the repository by
name 'Image-and-sound-for-the-published-repositories'"""

"""Игра крестики-нолики на поле 6х6.
Файлы изображения и звука находятся в repository по имени
 'Image-and-sound-for-the-published-repositories'"""

from tkinter import *
import random
import winsound
import threading
from multiprocessing import Process

def musika_clik_igrok_m():
    w = Process(target=musika_clik_igrok)
    w.daemon = True
    w.start()

def musika_clik_comp_m():
    w = Process(target=musika_clik_comp)
    w.daemon = True
    w.start()

def musika_clik_comp_p():
    thr_p5 = threading.Thread(target=musika_clik_comp).start()

def musika_win_comp_p():
    thr_p1 = threading.Thread(target=musika_win_comp).start()

def musika_win_igrok_p():
    thr_p2 = threading.Thread(target=musika_win_igrok).start()

def musika_clik_igrok_p():
    thr_p3 = threading.Thread(target=musika_clik_igrok).start()

def musika_win_comp():
    winsound.PlaySound(r"C:\\FOTO  Python\\poragen igr.wav",
                       winsound.SND_FILENAME)

def musika_win_igrok():
    winsound.PlaySound(r"C:\\FOTO  Python\\pobeda igr.wav",
                       winsound.SND_FILENAME)

def musika_clik_comp():
    winsound.PlaySound(r"C:\\FOTO  Python\\clik computer.wav",
                       winsound.SND_FILENAME)

def musika_clik_igrok():
    winsound.PlaySound(r"C:\\FOTO  Python\\clik igroka.wav",
                       winsound.SND_FILENAME)

def new_game(event):
    for row in range(6):
        for col in range(6):
            field[row][col]['text'] = ' '
            field[row][col]['background'] = '#add6b8'

    global game_run
    game_run = True
    global cross_count
    cross_count = 0
    c.itemconfig('new', state='hidden')

    row = random.randint(2, 3)
    col = random.randint(2, 3)
    field[row][col]['text'] = 'O'
    print('Случайно')
    check_win('O')

def click(row, col):

    if game_run and field[row][col]['text'] == ' ':
        field[row][col]['text'] = 'X'
        global cross_count
        cross_count += 1
        musika_clik_igrok_m()
        check_win('X')

        if game_run and cross_count < 18:
            computer_move()
            check_win('O')

def check_win(smb): # ПРОВЕРЕНО 100%
    for n in range(6):

        check_line(field[n][0], field[n][1], field[n][2],
                   field[n][3], smb)

        check_line(field[n][1], field[n][2], field[n][3],
                   field[n][4], smb)

        check_line(field[n][2], field[n][3], field[n][4],
                   field[n][5], smb)
        #####
        check_line(field[0][n], field[1][n], field[2][n],
                   field[3][n], smb)

        check_line(field[1][n], field[2][n], field[3][n],
                   field[4][n], smb)

        check_line(field[2][n], field[3][n], field[4][n],
                   field[5][n], smb)

    #### БОЛЬШАЯ ДИАГОНАЛЬ 1
    check_line(field[0][0], field[1][1], field[2][2],
               field[3][3], smb)

    check_line(field[1][1], field[2][2], field[3][3],
               field[4][4], smb)

    check_line(field[2][2], field[3][3], field[4][4],
               field[5][5], smb)

    ##### БОЛЬШАЯ ДИАГОНАЛЬ 2
    check_line(field[0][5], field[1][4], field[2][3],
               field[3][2], smb)

    check_line(field[1][4], field[2][3], field[3][2],
               field[4][1], smb)

    check_line(field[2][3], field[3][2], field[4][1],
               field[5][0], smb)

    #### малая диагональ
    check_line(field[0][3], field[1][2], field[2][1],
               field[3][0], smb)

    #### средняя диагональ
    check_line(field[0][4], field[1][3], field[2][2],
               field[3][1], smb)

    check_line(field[1][3], field[2][2], field[3][1],
               field[4][0], smb)
    ####
    check_line(field[2][5], field[3][4], field[4][3],
               field[5][2], smb)
    ####
    check_line(field[1][5], field[2][4], field[3][3],
               field[4][2], smb)

    check_line(field[2][4], field[3][3], field[4][2],
               field[5][1], smb)
    ###
    check_line(field[5][3], field[4][2], field[3][1],
               field[2][0], smb)
    ###
    check_line(field[1][0], field[2][1], field[3][2],
               field[4][3], smb)

    check_line(field[2][1], field[3][2], field[4][3],
               field[5][4], smb)
    ####
    check_line(field[0][2], field[1][3], field[2][4],
               field[3][5], smb)
    ####
    check_line(field[0][1], field[1][2], field[2][3],
               field[3][4], smb)

    check_line(field[1][2], field[2][3], field[3][4],
               field[4][5], smb)

def check_line(a1, a2, a3, a4, smb):
    global game_run, z_igr, z_com
    if a1['text'] == 'X' and a2['text'] == 'X' and a3['text'] == 'X' and \
            a4['text'] == 'X':
        a1['background'] = a2['background'] = a3['background'] = \
            a4['background'] = '#178e17'
        z_igr = z_igr + 1
        print("z_igr=", z_igr)
        c.delete("ch")
        chet = c.create_text(30, 20,
                             text=(s * 65 + 'КОМПЬЮТЕР   %s : %s   ИГРОК'
                                   % (z_com, z_igr)),
                             font='Times 20', fill='black',
                             state='normal', tag="ch")
        musika_win_igrok_p()
        c.itemconfig('new', state='normal')
        game_run = False

    if a1['text'] == 'O' and a2['text'] == 'O' and a3['text'] == 'O' and \
            a4['text'] == 'O':
        a1['background'] = a2['background'] = a3['background'] = \
            a4['background'] = '#d90640'
        z_com = z_com + 1
        print("z_com=", z_com)
        c.delete("ch")
        chet = c.create_text(30, 20,
                             text=(s * 65 + 'КОМПЬЮТЕР   %s : %s   ИГРОК'
                                   % (z_com, z_igr)),
                             font='Times 20', fill='black',
                             state='normal', tag="ch")
        musika_win_comp_p()
        c.itemconfig('new', state='normal')
        game_run = False

"""ОБУЧЕНИЕ КОМПЬЮТЕРА"""
def can_win(a1, a2, a3, a4, smb):
    res = False

    # ЗА 1 ХОД ДО ПОБЕДЫ
    if a1['text'] == 'O' and a2['text'] == 'O' and a3['text'] == 'O' \
            and a4['text'] == ' ':
        a4['text'] = 'O'
        print('за 1 ход до победы')
        res = True

    if a1['text'] == 'O' and a2['text'] == 'O' and a3['text'] == ' ' \
            and a4['text'] == 'O':
        a3['text'] = 'O'
        print('за 1 ход до победы')
        res = True

    if a1['text'] == 'O' and a2['text'] == ' ' and a3['text'] == 'O' \
            and a4['text'] == 'O':
        a2['text'] = 'O'
        print('за 1 ход до победы')
        res = True

    if a1['text'] == ' ' and a2['text'] == 'O' and a3['text'] == 'O' \
            and a4['text'] == 'O':
        a1['text'] = 'O'
        print('за 1 ход до победы')
        res = True

    #ЗА 2 ХОДА ДО ПОБЕДЫ
    if a1['text'] == 'O' and a2['text'] == 'O' and a3['text'] == ' ' \
            and a4['text'] == ' ':
        a3['text'] = 'O'
        print('за 2 хода до победы')
        res = True

    if a1['text'] == ' ' and a2['text'] == ' ' and a3['text'] == 'O' \
            and a4['text'] == 'O':
        a2['text'] = 'O'
        print('за 2 хода до победы')
        res = True

    if a1['text'] == 'O' and a2['text'] == ' ' and a3['text'] == 'O' \
            and a4['text'] == ' ':
        a2['text'] = 'O'
        print('за 2 хода до победы')
        res = True

    if a1['text'] == ' ' and a2['text'] == 'O' and a3['text'] == ' ' \
            and a4['text'] == 'O':
        a3['text'] = 'O'
        print('за 2 хода до победы')
        res = True

    if a1['text'] == ' ' and a2['text'] == 'O' and a3['text'] == 'O' \
            and a4['text'] == ' ':
        a1['text'] = 'O'
        print('за 2 хода до победы')
        res = True

    if a1['text'] == 'O' and a2['text'] == ' ' and a3['text'] == ' ' \
            and a4['text'] == 'O':
        a2['text'] = 'O'
        print('за 2 хода до победы')
        res = True

    return res

def computer_move():

    # ДЛЯ КОМПЬЮТЕРА проверено 100%
    for n in range(6):
        if can_win(field[n][0], field[n][1], field[n][2],
                   field[n][3], 'O'):
            return

        if can_win(field[n][1], field[n][2], field[n][3],
                   field[n][4], 'O'):
            return

        if can_win(field[n][2], field[n][3], field[n][4],
                   field[n][5], 'O'):
            return

        if can_win(field[0][n], field[1][n], field[2][n],
                   field[3][n], 'O'):
            return

        if can_win(field[1][n], field[2][n], field[3][n],
                   field[4][n], 'O'):
            return

        if can_win(field[2][n], field[3][n], field[4][n],
                   field[5][n], 'O'):
            return

    if can_win(field[0][0], field[1][1], field[2][2],
               field[3][3], 'O'):
        return

    if can_win(field[1][1], field[2][2], field[3][3],
               field[4][4], 'O'):
        return

    if can_win(field[2][2], field[3][3], field[4][4],
               field[5][5], 'O'):
        return
#########
    if can_win(field[0][5], field[1][4], field[2][3],
               field[3][2], 'O'):
        return

    if can_win(field[1][4], field[2][3], field[3][2],
               field[4][1], 'O'):
        return

    if can_win(field[2][3], field[3][2], field[4][1],
               field[5][0], 'O'):
        return
########
    if can_win(field[0][3], field[1][2], field[2][1],
               field[3][0], 'O'):
        return

#########
    if can_win(field[0][4], field[1][3], field[2][2],
               field[3][1], 'O'):
        return

    if can_win(field[1][3], field[2][2], field[3][1],
               field[4][0], 'O'):
        return
########
    if can_win(field[2][0], field[3][1], field[4][2],
               field[5][3], 'O'):
        return
#######
    if can_win(field[1][0], field[2][1], field[3][2],
               field[4][3], 'O'):
        return

    if can_win(field[2][1], field[3][2], field[4][3],
               field[5][4], 'O'):
        return
    ######

    if can_win(field[0][2], field[1][3], field[2][4],
               field[3][5], 'O'):
        return
    #######
    if can_win(field[0][1], field[1][2], field[2][3],
               field[3][4], 'O'):
        return

    if can_win(field[1][2], field[2][3], field[3][4],
               field[4][5], 'O'):
        return
    ######
    if can_win(field[2][5], field[3][4], field[4][3],
               field[5][2], 'O'):
        return
    ########

    if can_win(field[1][5], field[2][4], field[3][3],
               field[4][2], 'O'):
        return

    if can_win(field[2][4], field[3][3], field[4][2],
               field[5][1], 'O'):
        return
    ######

####### ДЛЯ ИГРОКА проверено 100%

    for n in range(6):
        if can_win(field[n][0], field[n][1], field[n][2],
                   field[n][3], 'X'):
            return

        if can_win(field[n][1], field[n][2], field[n][3],
                   field[n][4], 'X'):
            return

        if can_win(field[n][2], field[n][3], field[n][4],
                   field[n][5], 'X'):
            return

        if can_win(field[0][n], field[1][n], field[2][n],
                   field[3][n], 'X'):
            return

        if can_win(field[1][n], field[2][n], field[3][n],
                   field[4][n], 'X'):
            return

        if can_win(field[2][n], field[3][n], field[4][n],
                   field[5][n], 'X'):
            return
#########
    if can_win(field[0][0], field[1][1], field[2][2],
               field[3][3], 'X'):
        return

    if can_win(field[1][1], field[2][2], field[3][3],
               field[4][4], 'X'):
        return

    if can_win(field[2][2], field[3][3], field[4][4],
               field[5][5], 'X'):
        return
#########
    if can_win(field[2][5], field[3][4], field[4][3],
               field[5][2], 'X'):
        return
########
    if can_win(field[1][5], field[2][4], field[3][3],
               field[4][2], 'X'):
        return

    if can_win(field[2][4], field[3][3], field[4][2],
               field[5][1], 'X'):
        return
#########
    if can_win(field[0][2], field[1][3], field[2][4],
               field[3][5], 'X'):
        return
#########
    if can_win(field[0][1], field[1][2], field[2][3],
               field[3][4], 'X'):
        return

    if can_win(field[1][2], field[2][3], field[3][4],
               field[4][5], 'X'):
        return
##########
    if can_win(field[0][5], field[1][4], field[2][3],
               field[3][2], 'X'):
        return

    if can_win(field[1][4], field[2][3], field[3][2],
               field[4][1], 'X'):
        return

    if can_win(field[2][3], field[3][2], field[4][1],
               field[5][0], 'X'):
        return
    #######
    if can_win(field[0][3], field[1][2], field[2][1],
               field[3][0], 'X'):
        return
    #########
    if can_win(field[0][4], field[1][3], field[2][2],
                field[3][1], 'X'):
        return

    if can_win(field[1][3], field[2][2], field[3][1],
                field[4][0], 'X'):
        return
    ##########
    if can_win(field[2][0], field[3][1], field[4][2],
               field[5][3], 'X'):
        return
    #########
    if can_win(field[1][0], field[2][1], field[3][2],
                field[4][3], 'X'):
        return

    if can_win(field[2][1], field[3][2], field[4][3],
                field[5][4], 'X'):
        return

    while True:
        row = random.randint(2, 3)
        col = random.randint(2, 3)
        if field[row][col]['text'] == ' ':
            field[row][col]['text'] = 'O'
            print('Случайно')
            break

if __name__ == '__main__':

    tk = Tk()
    s = ' '
    tk.title(s * 50 + 'ИГРА "КРЕСТИКИ-НОЛИКИ"')
    tk.iconbitmap(default=r"C:\\FOTO  Python\\monitor2.ico")
    tk.resizable(0, 0)
    tk.wm_attributes('-topmost', 1)
    tk.geometry('516x600+500+50')

    game_run = True
    field = []
    cross_count = 0
    z_com = 0
    z_igr = 0

    for row in range(6):
        line = []
        for col in range(6):
            button = Button(tk, text=' ', width=4, height=2,
                            font=('Verdana', 20, 'bold'),
                            background='#add6b8',
                            command=lambda row=row, col=col: click(row, col))
            button.grid(row=row, column=col, sticky='nsew')
            line.append(button)
        field.append(line)

    new_button = Button(tk, text='НОВАЯ     ИГРА', font=('Times', 15, 'bold'),
                        foreground="green", command=new_game)
    new_button.grid(row=7, column=0, columnspan=6, sticky='nsew')

    row = random.randint(2, 3)
    col = random.randint(2, 3)
    field[row][col]['text'] = 'O'
    check_win('O')

    c = Canvas(tk, width=516, height=70, bg="#cacaca")
    c.grid(row=6, column=0, columnspan=6, sticky='nsew')
    c.focus_set()

    new = c.create_text(30, 50,
                          text=s * 65 + "НОВАЯ ИГРА",
                          font=('Times', 20, 'bold'), fill='green',
                        state='hidden', tag="new")

    chet = c.create_text(30, 20,
                        text=(s * 65 + 'КОМПЬЮТЕР   %s : %s   ИГРОК'
                              % (z_com, z_igr)),
                        font=('Times', 20), fill='black',
                         state='normal', tag="ch")

    c.tag_bind(new, "<Button-1>", new_game)

    tk.mainloop()


#   Returning to the beginning of the introduction for OOP,
# we should remind ourselves about the possibility of creating
# attributes which are shared by all instances of a given class.
#
#   NOTE:
#       EXAMPLE
class Point:
    counter = []

    def __init__(self, x=0, y=0):
        """Construct a Point."""
        self.x = x
        self.y = y

    def update(self, n):
        self.counter.append(n)

p1 = Point(0,0)
p2 = Point(1,1)

print(p1.counter)
print(p2.counter)
p1.update(1)
print(p1.counter)
print(p2.counter)


#!/usr/bin/python

import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
import time

warnings.filterwarnings("ignore", category=UserWarning)

if __name__ == "__main__":
    base_dir = os.path.abspath('')
    jammed_freq = 2442
    jammer_dist = 20
    jamming_power = 10
    raw_dir = f'{base_dir}/jam_shield/datasets/raw/spectral_scans_QC9880_ht20_background'
    scenario = f'samples_chamber_{jammed_freq}MHz_{jammer_dist}cm_{jamming_power}dBm'
    # scenario = 'samples_chamber_None'
    df = pd.read_csv(f'{raw_dir}/{scenario}_5.csv')
    # Getting channel information
    band = '2.4GHz'
    all_channels = None
    if band == '2.4GHz':
        all_channels = list(range(2412, 2467, 5))
    elif band == '5GHz':
        all_channels = [list(range(5180, 5340, 20)), list(range(5745, 5865, 20))]
        all_channels = [freq for band in range(len(all_channels)) for freq in all_channels[band]]
    else:
        print('Invalid band')

    x = []
    y = []
    for channel in all_channels:
        df_channel = df.where(df['freq1'] == channel).dropna()
        df_channel[df_channel['snr'] < -100] = np.NaN
        df_channel[df_channel['snr'] > 100] = np.NaN
        df_channel.fillna(df_channel['snr'].mean(), inplace=True)
        x.append(channel)
        y.append(df_channel['snr'].mean())

    plotName = f'{scenario}.png'
    plt.bar(x, y, width=4.5)
    plt.xlabel('Frequency (MHz')
    plt.ylabel('Average received power (dBm)')
    plt.savefig(plotName, bbox_inches='tight')
    plt.show()


from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required

from .shell_logic import disks
from .request_handler import handler

@login_required
def show_disks(request):

    context = {
        'disks': disks.get_all_disks(),
        'title': 'SUPER ULTRA HARD DRIVER MANAGER 3000'
    }

    return render(request, template_name='main/drivers.html', context=context)

@login_required
def mount_disk(request):

    request_body = handler.extract_dict_from_body(request)

    if disks.mount_disk(request_body['name']) is False:
        return render(request, 'main/err_mount.html')

    return redirect('/disks/')

@login_required
def umount_disk(request):

    request_body = handler.extract_dict_from_body(request)
    disks.umount_disk(request_body['name'])

    return redirect('/disks/')

@login_required
def format_disk(request):

    request_body = handler.extract_dict_from_body(request)

    if disks.format_disk(request_body['name']) is False:
        return render(request, 'main/err_format.html')

    return redirect('/disks/')

@login_required
def redirect_to_home_page(request):

    return redirect('/disks/')


import os, sys

if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    print(tools)
    sys.path.append(tools)
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")

from drawTravelTimes import *

class mainwindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mainwindow,self).__init__(None)
        loadUi('gui_marl.ui',self)

        r1 = MplTravelTime(self.widget_times, width=5, height=4, dpi=100, route=1)
        r2 = MplTravelTime(self.widget_times, width=5, height=4, dpi=100, route=2)
        #r3 = MplTravelTime(self.widget_times, width=5, height=4, dpi=100, route=3)
        #r4 = MplTravelTime(self.widget_times, width=5, height=4, dpi=100, route=4)
        self.layoutTimes1.addWidget(r1)
        self.layoutTimes1.addWidget(r2)
        #self.layoutTimes2.addWidget(r3)
        #self.layoutTimes2.addWidget(r4)
        self.widget_times.setFocus()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    ui = mainwindow()
    ui.setWindowTitle('MARL for traffic control')
    ui.show()
    sys.exit(app.exec_())


from django import forms
from django.forms import DateInput, DateField
from django.contrib.admin.widgets import AdminDateWidget
from .models import kesif

class KesifForm(forms.ModelForm):
    tarih = DateField(widget=AdminDateWidget)
    class Meta:
        model=kesif
        fields=[
            'kesifNo',
            'tarih',
            'musteri',
            'ilgiliKisi',
            'tel',
            'adres',
            'aciklama',
        ]
    widgets = {
             'tarih': DateInput(attrs={'type': 'date'})
        }


# -*- coding: utf-8 -*-
from flask import Flask
from flask import request
from flask import make_response
from flask import jsonify
from flask import abort
import urllib.request
from urllib.parse import quote
import sqlite3
from random import randint
import time
from functools import wraps
from flask import url_for, redirect, render_template
from DBAccessor import query_db, commit_db_and_get_lastId, commit_db
from SharedFunction import checkRequestValid, checkTimeStamp
from flask_cors import cross_origin
import os
import logging

app = Flask(__name__)
app.config['DEBUG'] = True

@app.route('/addSource',methods = {'POST'})
@cross_origin()
@checkRequestValid(tagList = ['username','source'])
@checkTimeStamp
def addSource():
        username = request.json['username']
        sourceName = request.json['source']
        id = commit_db_and_get_lastId('insert into '+username+'_sources' +' (source) values (?)',[sourceName])
        return jsonify({'status':'success','lastId':id}),200

@app.route('/deleteSource',methods = ['POST'])
@cross_origin()
@checkRequestValid(tagList = ['username','sourceId','deleteSourceMode'])
@checkTimeStamp
def deleteSource():
    sourceTableName = request.json['username'] + '_sources'
    wordTableName = request.json['username'] + '_words'
    sourceId = request.json['sourceId']
    deleteSourceMode = request.json['deleteSourceMode']

    if deleteSourceMode != '0' and deleteSourceMode != '1':
        print('error deleteSourceMode = '+deleteSourceMode)
        return jsonify({'status':'error deleteSourceMode = '
            + deleteSourceMode}),199

    row = query_db('select * from '+ sourceTableName +' where id = ?'
            ,[sourceId],one=True)
    if row is not None:
        commit_db('delete from '+ sourceTableName + ' where id = ?',
                [sourceId])
    else:
        return jsonify({'status':'cant find source id:'+
            str(sourceId)}),199
    rowCount =  query_db('select count(*) from '+ wordTableName + ' where sourceId = ?'
                                ,[sourceId],one=True)
    affectedWordNum = str(rowCount['count(*)'])
    r={'status':'success'}
    if deleteSourceMode == '0':
        commit_db('delete from '+ wordTableName + ' where sourceId = ?',
                [sourceId])
        r['detail']=affectedWordNum+' words deleted.'
        return jsonify(r),200
    elif deleteSourceMode == '1':
        commit_db('update '+wordTableName +
                ' set sourceId = -1 where sourceId = ?',[sourceId])
        r['detail']=affectedWordNum+' words updated.'
        return jsonify(r),200

@app.route('/addWord',methods = {'POST'})
@cross_origin()
@checkRequestValid(tagList =
        ['word','reading','meaning','sourceId','page','sentence'])
@checkTimeStamp
def addWord():
    wordTableAddr = request.json['username']+"_words"
    wordInfo = []
    wordInfo.append(request.json['word'])
    wordInfo.append(request.json['reading'])
    wordInfo.append(request.json['meaning'])
    wordInfo.append(request.json['sourceId'])
    wordInfo.append(request.json['page'])
    wordInfo.append(request.json['sentence'])
    commit_db('insert into '+ wordTableAddr +
            ''' (word,reading,description,sourceId,page,sentence)
            values (?,?,?,?,?,?)''',wordInfo)
    return jsonify({'status':'success'}),200

@app.route('/listSource',methods = {'POST'})
@cross_origin()
@checkRequestValid(tagList = ['username'])
@checkTimeStamp
def listSource():
    rows = query_db('select * from '+request.json['username']+'_sources')
    sources = {}
    if rows is not None:
        for row in rows:
            sources[row['id']] = row['source']
    r = {'sources':sources}
    r['status']='success'
    return jsonify(r),200

def eliminateNonWordChar(str):
    nonWordList=['・']
    for nonWord in nonWordList:
        str = str.replace(nonWord,'')
    return str
MozillaFakeHeader = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                     'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
                     'Accept-Encoding': 'none',
                     'Accept-Language': 'en-US,en;q=0.8',
                     'Content-Type': 'application/json;charset=UTF-8',
                     'Connection': 'keep-alive'}
gooURLFront = "http://dictionary.goo.ne.jp/srch/"
gooURLMiddleAll = "all/"
gooURLMiddleJn2 = "jn/"
gooURLTail = "/m0u/"
right ='】'
left ='【'
singleResultPage = 1
multipleResultPage = 2
notFoundPage=3

multipleResultPageKeyword = '国語辞書の検索結果'
NotFoundPageKeyword = '一致する情報は見つかりませんでした'

@app.route('/listAllReadingByWord',methods = ['POST'])
@cross_origin()
@checkRequestValid(tagList = ['word'])
@checkTimeStamp
def listReadingByWord():
    readingList = []
    word = request.json['word'].encode('utf-8')
    wordEnd = left+request.json['word']+right
    wordBegin = '
'
    cursor = 0
    url = gooURLFront+gooURLMiddleJn2+quote(word)+gooURLTail
    req = urllib.request.Request(url, headers=MozillaFakeHeader)
    page = urllib.request.urlopen(req).read().decode("utf-8")
    while(cursor!=-1):
        posEnd = page.find(wordEnd,cursor)
        if posEnd==-1:
            break
        posBegin = page.find(wordBegin,posEnd-100)
        posBegin = posBegin+len(wordBegin)
        if posEnd>posBegin and posEnd-posBegin<50:
            reading = eliminateNonWordChar(page[posBegin:posEnd])
            #print(reading)
            if reading not in readingList:
                readingList.append(reading)
        cursor=posEnd+len(wordEnd)+1
    if readingList == []:
        readingList = ['Not found']
    return jsonify({'status':'success','readingList':readingList}),200

@app.route('/listAllMeaningByWord',methods = ['POST'])
@cross_origin()
@checkRequestValid(tagList = ['word'])
@checkTimeStamp
def listMeaningByWord():
    meaningList = []
    word = request.json['word'].encode('utf-8')
    req = urllib.request.Request(gooURLFront+gooURLMiddleJn2+quote(word)+gooURLTail, headers=MozillaFakeHeader)
    page = urllib.request.urlopen(req).read().decode("utf-8")
    pageType = determinePageType(page)
    if pageType == singleResultPage:
        meaningList = parseSingleResultPage(page)
    elif pageType == multipleResultPage:
        meaningList = parseMultipleResultPage(page,word)
    elif pageType == notFoundPage:
        meaningList = ['Not found']

    return jsonify({'status':'success','meaningList':meaningList}),200

def determinePageType(page):
    if page.find(NotFoundPageKeyword) != -1:
        return notFoundPage
    result = page.find(multipleResultPageKeyword)
    if result == -1:
        return singleResultPage
    else:
        return multipleResultPage

def filterNoiseBlock(sentence,left,right):
    cursor = sentence.find(left,0)
    while cursor != -1:
        begin = cursor
        end = sentence.find(right,begin)+len(right)
        if end!=-1:
            sentence = sentence.replace(sentence[begin:end],"")
        cursor = sentence.find(left,0)
    return sentence

def getTagText(xml,tagBegin,tagEnd):
    t = tagBegin.find(' ',0)
    if t == -1:
        pureTag=tagBegin
    else:
        pureTag=tagBegin[:t]
    posBegin = xml.find(tagBegin,0)
    if posBegin == -1:
        print('Cannot find tag : "'+tagBegin+'" in getTagText function')
        return 'error'
    pureTagPos = posBegin
    posEnd = xml.find(tagEnd,posBegin)
    if posEnd == -1:
        print('cannot find tag : "'+tagEnd+'" in getTagText function')
        return 'error'
    while True:
        pureTagPos = xml.find(pureTag,pureTagPos+len(pureTag),posEnd)
        if pureTagPos == -1:
            break
        else:
            posEnd = xml.find(tagEnd,posEnd+len(tagEnd))
    posBegin=posBegin+len(tagBegin)
    return xml[posBegin:posEnd]

def parseSingleResultPage(page):
    cursor = 0
    targetPrevBegin = '
'
    targetBegin = '<li class="in-ttl-b'
    targetEnd = '
'
    exitKeyword = ''
    meaningList = []
    beginPosition = page.find(targetPrevBegin,cursor)
    if beginPosition == 0:
        return []
    endPosition = page.find(exitKeyword,beginPosition)
    page = page[beginPosition:endPosition]
    while cursor != -1:
        posBegin = page.find(targetBegin,cursor)
        if posBegin == -1:
            break
        rawMeaning = getTagText(page[posBegin:],targetBegin,targetEnd)
        posBegin = posBegin + len(rawMeaning)
        if rawMeaning == 'error':
            break
        meaning = filterNoiseBlock(rawMeaning,'','')
        meaning = filterNoiseBlock(meaning,'<','>')
        meaning = filterNoiseBlock(meaning,'text','">')
        if meaning[:2]=='">':
            meaning = meaning[2:]
        meaningList.append(meaning)
        cursor = posBegin
    return meaningList

def parseMultipleResultPage(page,word):
    meaningList = []
    targetBegin = 'class="title search-ttl-a">'
    hrefKeywordBegin = 'href="'
    hrefKeywordEnd = '">'
    cursor = 0
    url=''
    while cursor != -1:
        cursor = page.find(targetBegin,cursor)
        if cursor == -1:
            break
        wordBeginPos = page.find(left,cursor)
        wordEndPos = page.find(right,wordBeginPos)
        if wordBeginPos == -1 or wordEndPos == -1:
            break
        if word == page[wordBeginPos+len(left):wordEndPos]:
            startSearchPos = cursor-175
            urlPosBegin = page.find(hrefKeywordBegin,startSearchPos)+len(hrefKeywordBegin)
            urlPosEnd = page.find(hrefKeywordEnd,urlPosBegin)
            if urlPosBegin == -1 or urlPosEnd == -1:
                return meaningList
            urlTail = page[urlPosBegin:urlPosEnd]
            url='http://dictionary.goo.ne.jp'+urlTail
            req = urllib.request.Request(url, headers=MozillaFakeHeader)
            concretePage = urllib.request.urlopen(req).read()
            meaningList+=parseSingleResultPage(concretePage)
        cursor = wordEndPos

    return meaningList

if __name__ == '__main__':
    app.run(host='0.0.0.0')


data = [7,5,9,0,3,1,6,2,4,8]

def swapListElement(list, a, b):
    list[a], list[b] = list[b], list[a]
    return list

def quickSort2(list, start, end):
    if start >= end:
        return list
    pivot = start
    left = start + 1
    right = end
    while left <= right:
        while left <= end and list[left] <= list[pivot]:
            left += 1
        while right > start and list[right] >= list[pivot]:
            right -= 1
        if right < left:
            swapListElement(list, right, pivot)
        else:
            swapListElement(list, right, left)
    quickSort2(list, start, right - 1)
    quickSort2(list, right + 1, end)
    return list

print(quickSort2(data, 0, len(data) - 1))


import sys
from importlib import reload

from bs4 import BeautifulSoup
import urllib.request
from urllib.request import  Request
import csv
import pandas as pd
import numpy as np
import nltk
nltk.download('punkt') # one time execution
import re
import csv
import pandas
from nltk.tokenize import sent_tokenize
import copy
import csv
from textblob import TextBlob
import os

nltk.download('stopwords')
from nltk.corpus import stopwords
stop_words = stopwords.words('english')
from sklearn.metrics.pairwise import cosine_similarity
import networkx as nx

url = "https://dunyanews.tv/"
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    'Accept-Encoding': 'none',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive'}
r = Request(url, None, headers)

thepage = urllib.request.urlopen(r)
soup = BeautifulSoup(thepage, "html.parser" )

if os.path.exists('DunyaTemp.csv'):
    os.remove('DunyaTemp.csv')
if os.path.exists('dunya.csv'):
    os.remove('dunya.csv')

def getLinks(url):
    html_page = urllib.request.urlopen(url)
    soup = BeautifulSoup(html_page, "html.parser" )
    links = []

    for link in soup.ul.findAll('a'):
        if link.text != 'Featured':
            data = []
            data.append((link['href'] if link['href'].startswith('http') else url + link['href']))
            data.append(link.text)
            links.append(data)

    return links

def getStories(urlstory):
    html_page = urllib.request.urlopen(urlstory[0])
    soup = BeautifulSoup(html_page, "html.parser")
    links = []

    for link in soup.select('article > h3 > a'):
        data=[]

        data.append((link['href'] if link['href'].startswith('http') else url + link['href']))
        data.append(urlstory[1])
        links.append(data)

    return links

def getStoryDetails(url):
    html_page = urllib.request.urlopen(url[0])
    soup = BeautifulSoup(html_page, "html.parser" )

    title =soup.select('#main-heading > div.date > h2')[0].get_text()     #ppppppheading
    news =soup.select('#post_content > article > div.post_content ')[0].get_text()

    img = soup.select('#post_content > article > div.pic.post_thumb > img')
    if  len(img) > 0:
     img=(img[0]['src'])
    else:
     img = ''
    articles = []

    for s in [news]:
        articles.append(sent_tokenize(s))

    # articles = [y for x in articles for y in x]

    for article in articles:
        # print(article)

        # Extract word vectors
        word_embeddings = {}
        f = open('glove.6B.100d.txt', encoding='utf-8')
        for line in f:
            values = line.split()
            word = values[0]
            coefs = np.asarray(values[1:], dtype='float32')
            word_embeddings[word] = coefs
        f.close()

        clean_article = pd.Series(article).astype(str).str.replace("[^a-zA-Z]", " ")
        # make alphabets lowercase
        clean_article = [s.lower() for s in clean_article]

        # print(clean_article)

        # function to remove stopwords
        def remove_stopwords(sen):
            sen_new = " ".join([i for i in sen if i not in stop_words])
            return sen_new

        # remove stopwords from the articles
        clean_article = [remove_stopwords(r.split()) for r in clean_article]

        # print(clean_article)

        # Extract word vectors
        word_embeddings = {}
        f = open('glove.6B.100d.txt', encoding='utf-8')
        for line in f:
            values = line.split()
            word = values[0]
            coefs = np.asarray(values[1:], dtype='float32')
            word_embeddings[word] = coefs
        f.close()

        sentence_vectors = []
        for i in clean_article:
            if len(i) != 0:
                v = sum([word_embeddings.get(w, np.zeros((100,))) for w in i.split()]) / (len(i.split()) + 0.001)
            else:
                v = np.zeros((100,))
            sentence_vectors.append(v)

        # print(sentence_vectors)

        # similarity matrix
        sim_mat = np.zeros([len(article), len(article)])

        for i in range(len(article)):
            for j in range(len(article)):
                if i != j:
                    sim_mat[i][j] = \
                    cosine_similarity(sentence_vectors[i].reshape(1, 100), sentence_vectors[j].reshape(1, 100))[0, 0]
                # print(sim_mat[i][j])

        nx_graph = nx.from_numpy_array(sim_mat)
        scores = nx.pagerank(nx_graph)

        ranked_sentences = sorted(((scores[i], s) for i, s in enumerate(article)), reverse=True)

        # print(ranked_sentences[0][1]
        mylist=[]
        mylist = ranked_sentences[0][1]

        p = []

        for sentence in mylist[0]:
            # row = sentence
            row = mylist
            blob = TextBlob(row)
            # r = sentence
            if blob.sentiment.polarity == 0:
                p = 'neutral'
            elif blob.sentiment.polarity < 0:
                p = 'negative'
            elif blob.sentiment.polarity > 0:
                p = 'positive'
            # print(p)

        with open('DunyaTemp.csv', 'a+', encoding= 'utf-8-sig') as file:
            writer = csv.writer(file, delimiter=',')
            new = title, news, img, url[1], mylist, p
            if file.tell()==0:
             writer.writerow(['title', 'news', 'img-url','category','summery','opinion'])
            writer.writerow(new)
            return writer

for item in getLinks("https://dunyanews.tv"):
    for item2 in (getStories(item)):
        print(getStoryDetails(item2))

import os

os.rename('DunyaTemp.csv', 'dunya.csv')


#!/usr/bin/python3.5

import os
import shutil

from myargparse import parse_args

args = parse_args()

input_dir = '/media/hector/HECTOR/dataset/mujer'
output_dir = '../dataset/mujer'
#input_dir = '../dataset/mujer'
#output_dir = '/media/hector/HECTOR/dataset/mujer'

for shop in args.shops:
    for category in args.categories:
        products_folder = os.path.join(input_dir, category, shop, 'products')
        dst_products_folder = os.path.join(output_dir, category, shop, 'products')
        if os.path.isdir(products_folder):
            if os.path.isdir(dst_products_folder) is False:
                os.makedirs(dst_products_folder)
            for item in os.listdir(products_folder):
                src = os.path.join(products_folder, item)
                dst = os.path.join(dst_products_folder, item)
                if os.path.isdir(src):
                    if os.path.isdir(dst):
                        shutil.rmtree(dst)
                    shutil.copytree(src, dst, False, None)
                else:
                    if os.path.isfile(dst):
                        os.remove(dst)
                    shutil.copyfile(src, dst)


from __future__ import annotations

from dataclasses import dataclass
from typing import List

import cli
import downloader
import m3u8

from ..utils import Path
from . import base

@dataclass
class RelativeSegment(base.Item):
    RelativeStart: float

@dataclass
class Stream(base.Item):
    RelativeStart: float
    RelativeEnd: float
    StreamUrl: str
    RelativeSegments: List[RelativeSegment] | None

    @property
    def duration(self):
        return self.RelativeEnd - self.RelativeStart

    @property
    def to_download(self):
        return self.duration > 20

    @property
    def start(self):
        return (
            self.RelativeSegments[0].RelativeStart
            if self.RelativeSegments
            else self.RelativeStart
        )

@dataclass
class DownloadStream(Stream):
    index: int
    streams: Streams

    @property
    def name(self):
        name = self.streams.name
        if self.index > 0:
            name += f"__VIEW__{self.index + 1}"
        return name

    @property
    def dest(self):
        return (self.streams.folder / self.name).with_suffix(".mp4")

    def download(self):
        if self.to_download and not self.dest.exists():
            self.start_download()

    def start_download(self):
        if "m3u8" in self.StreamUrl:
            download_m3u8(self.StreamUrl, self.dest)
        else:
            downloader.download(self.StreamUrl, self.dest)
        self.synchronize_download_start()
        self.dest.mtime = self.streams.mtime

    def synchronize_download_start(self):
        offset_difference = self.streams.start - self.start
        cut(self.dest, offset_difference)

@dataclass
class Streams(base.Item):
    streams: List[Stream]
    folder: Path
    name: str
    mtime: float

    @property
    def streams_to_download(self):
        for stream in self.streams:
            if stream.to_download:
                yield stream

    @property
    def start(self):
        return max([s.start for s in self.streams_to_download])

    def download(self):
        for i, stream in enumerate(self.streams_to_download):
            stream_info = stream.dict() | dict(streams=self, index=i)
            stream = DownloadStream.from_dict(stream_info)
            stream.download()
        if self.folder.exists():
            self.folder.mtime = self.mtime

def download_m3u8(url: str, dest: Path, headers=None):
    headers = headers or {}
    playlist = m3u8.load(url, headers=headers)
    playlist = m3u8.load(playlist.playlists[0].absolute_uri, headers=headers)
    url = playlist.segments[0].absolute_uri
    downloader.download(url, dest)

def cut(dest: Path, start_offset):
    with Path.tempfile().with_suffix(dest.suffix) as tmp:
        args = (
            "ffmpeg",
            "-i",
            dest,
            "-ss",
            start_offset,
            "-vcodec",
            "copy",
            "-acodec",
            "copy",
            tmp,
        )
        cli.get(args)
        tmp.copy_to(dest)


import numpy as np

def manual_list(row, col):
    tempArr = []
    for i in range(row):
        print('Baris ke-', (i + 1))
        for j in range(col):
            tempArr.append(float(input('    Elemen: ')))
        print('')
    return np.array(tempArr)

def populate_list(row, col, spread):
    np.set_printoptions(precision=2)
    return np.array(np.random.uniform(1, spread, (row, col)), dtype=float)

def template_list():
    tempArr = [
        [26, 35],
        [13, 12],
        [11, 5],
        [10, 15],
        [50, 45],
        [200, 200],
        [18, 20],
        [21, 14],
        [16, 20],
        [21, 75]
    ]
    return np.array(tempArr)

def proximity_matrix(A, B):
    kuadratA = (A ** 2).sum(axis=1)
    kuadratB = (B ** 2).sum(axis=1).reshape((A.shape[0], 1))
    duaAB = 2 * A.dot(B.T)
    return np.sqrt(abs(kuadratA - duaAB + kuadratB))

def idx_matrix(size):
    tempArr = []
    for i in range(size):
        tempArr.append(np.arange(size))
    return np.array(tempArr)

def nearest_matrix(prxM, idxM):
    for i in range(prxM.shape[0]):
        for j in range(prxM.shape[1]):
            for k in range(prxM.shape[1] - j - 1):
                if (prxM[i, k] > prxM[i, k + 1]):
                    prxM[i, k], prxM[i, k + 1] = prxM[i, k + 1], prxM[i, k]
                    idxM[i, k], idxM[i, k + 1] = idxM[i, k + 1], idxM[i, k]

def average_density(K, valueTrim):
    np.set_printoptions(precision=5)
    avgDens = K / valueTrim.sum(axis=1)
    return avgDens.reshape((avgDens.shape[0], 1))

def average_rel_dens(indexTrim, avgDens, K):
    tempArr = []
    for i in range(avgDens.shape[0]):
        totDens = 0
        for j in range(indexTrim.shape[1]):
            totDens += avgDens[indexTrim[i, j]]
        tempArr.append(float(totDens / K / avgDens[i]))
    return np.array(tempArr).reshape((avgDens.shape[0], 1))


import os
import glob
import time
from Boardlogger import Boardlogger
from PTorchEnv.PPO_Buffer import PPO_Buffer
from PTorchEnv.PPO_Actor_Proxy import PPO_Actor_Proxy
import PTorchEnv.model
from PTorchEnv.Typechecker import TensorTypecheck
from DroneEnv import DroneEnv

from PPO import PPO

####### initialize environment hyperparameters ######
env=DroneEnv(23005)

#vrep的接口和TCP的接口还不一样
#TCP的接口只要考虑两端就行了，
#但是vrep的接口用的是zmq，所以需要考虑到其它的东西
#但是我们还是以这个例子开始训练比较好

replaybuff=PPO_Buffer()
optimizer = PPO()
optimizer.set_Replaybuff(replaybuff,0.99, 0.0003, 0.001)

actor_proxy=PPO_Actor_Proxy()
actorNet=PTorchEnv.model.Actor_Drone()
criticM=PTorchEnv.model.Critic_PPO(12,128,1)
actor_proxy.setNet(actorNet,criticM)

actor_proxy.set_action_dim(4)
actor_proxy.setActFlag("Continuous")
actor_proxy.set_range([5,5,5,5],[0,0,0,0])
actor_proxy.decayInterval=200
optimizer.setNet(actorNet,criticM,actor_proxy)

time_step = 0

lastobs = env.randominit()
current_ep_reward = 0
epoch=1
rllogger=Boardlogger()
# training loop
while True:
    # select action with policy
    action=actor_proxy.response(lastobs)
    obs,reward,done,info= env.step(action)
    replaybuff.appendnew(lastobs,actor_proxy.action,obs,reward)
    lastobs=TensorTypecheck(obs)
    if done or info== "truncated": #drone任务中没有truncated的情况,只有一个终点
        replaybuff.ResetNotify()#only notify once!!
        lastobs = env.randominit()
        rllogger.log_per_step_scalr(current_ep_reward,"epoc_reward")
        epoch+=1
        current_ep_reward = 0
    time_step +=1
    current_ep_reward += reward
    optimizer.update()


from importlib.metadata import entry_points
import setuptools

long_description = open('README.md').read()

setuptools.setup(
    name='proof-mouse',
    version='0.6',
    author='Raghav Malik',
    author_email='malik22@purdue.edu',
    description='Proof Mouse proof checker',
    long_description=long_description,
    url='https://github.com/raghav198/proof-mouse',
    license='MIT',
    packages=['.'],
    install_requires=['pyparsing==3.0.9'],
    entry_points={
        'console_scripts': ['mouse=mouse:main']
    }
)


# -*- coding: utf-8 -*-
"""
Created on Wed Jul 26 16:54:47 2023

@author: timsargent
"""

from datetime import datetime, timedelta
from sqlhandler import SqlConnection
from dotenv import load_dotenv
import os

class func():
    def __init__(self):
        load_dotenv()
        CIV_GAME_DB = os.getenv('CIV_GAME_DB')
        self.sql = SqlConnection(CIV_GAME_DB)
        return

    def game_match(self, game_name, civ_name=None, game_turn=None):
        #preform the fuzzy match for game based on the three values civ gives us
        #If the name is unuque or does not exsist, it's a quick match
        game_id = self.sql.get_games_by_name(game_name)
        if len(game_id) == 1:
            return game_id[0][0]
        elif len(game_id) == 0:
            return None
        else:
            return False

    def age_formater(self, time):
        day_unit = timedelta(days=1)
        hour_unit = timedelta(hours=1)
        minute_unit = timedelta(seconds=60)
        now = datetime.now()

        if isinstance(time, str):
            date_format = '%Y-%m-%d %H:%M:%S.%f'
            time = datetime.strptime(time, date_format)

        delta = now - time
        if delta < minute_unit:
            #under a min
            return "<1m"
        elif delta < hour_unit:
            #under an hour, show min
            return str(divmod(delta.seconds, 60)[0]) + "m"
        elif delta < day_unit:
            #under a day, show hour
            return str(divmod(delta.seconds, 3600)[0]) + "h"
        else:
            #Show Days
            return str(delta.days) + "d"

    def ping_gen(self, game_name, civ_name, game_turn, game_note = None):
    # Generate ping
        discord_id = self.sql.get_discord_id(civ_name)
        if discord_id == None:
            message = "**{}** Update! Turn {} for {}".format(game_name,
                                                                str(game_turn),
                                                                str(civ_name))
        else:
            message = "<@{}>, Turn {} for {}".format(str(discord_id[0]),
                                                                str(game_turn),
                                                                str(game_name))
        if game_note is not None:
            message = "{}\nGame Note: {}".format(message,game_note[0])

        return message


import pygame
from pygame.locals import *
from UDP import sendUDP
import time
import threading

pygame.init()
#Attach joysticks before running
JOYSTICKS = [0]
RPI_IPS = ["192.168.86.33"]

jstick_list = []
for i in JOYSTICKS:
    jstick_list.append(pygame.joystick.Joystick(i))

stop_threads = False

def send_values(jstick, i):
    global stop_threads
    while True:
        time.sleep(.005)
        if stop_threads:
            break
        if jstick.get_button(2):
            #print("stopped")
            break
        else:
            x = round(jstick.get_axis(2), 3)
            y = round(-jstick.get_axis(1), 3)
            manip1 = round(jstick.get_axis(4), 3)
            manip2 = round(jstick.get_axis(5), 3)
            a_press = int(jstick.get_button(0))
            b_press = int(jstick.get_button(1))
            msg = str(x) + ":" + str(y) + ":" + str(manip1) + ":" + str(manip2) + ":" + str(a_press) + ":" + str(b_press)
            #print(msg)
            sendUDP(msg, IP = RPI_IPS[i], port = 8080)

thread_list = []
for i in range(0, len(jstick_list)):
    thread_list.append(threading.Thread(target = send_values, args = (jstick_list[i], i)))

for i in range(0, len(thread_list)):
    thread_list[i].start()

while True:
    for event in pygame.event.get(): # get the events (update the joystick)
        if event.type == QUIT: # allow to click on the X button to close the window
            stop_threads = True
            for i in thread_list:
                i.join()
            pygame.quit()
            exit()
'''
while True:
    time.sleep(.005)
    for event in pygame.event.get(): # get the events (update the joystick)
        if event.type == QUIT: # allow to click on the X button to close the window
            pygame.quit()
            exit()

    if jstick_list[0].get_button(0):
        print("stopped")
        break
    else:
        for i in range(0, len(jstick_list)):
            x = round(jstick_list[i].get_axis(2), 3)
            y = round(-jstick_list[i].get_axis(1), 3)
            manip1 = round(jstick_list[i].get_axis(4), 3)
            manip2 = round(jstick_list[i].get_axis(5), 3)
            msg = str(x) + ":" + str(y) + ":" + str(manip1) + ":" + str(manip2)
            print(msg)
            sendUDP(msg, IP = RPI_IPS[i], port = 8080)
'''


import enum
import warnings
import certifi

import pymongo
from pymongo.collection import Collection

class MgdbClass:
    """
    Usage:
    Mgdb.database("<database_name>").collection("<name>").<any mongodb collection function available in pymongo>
    """

    _query = None

    def __init__(self, mongo_url) -> None:
        self.url = mongo_url

    def __get_mgdb_client(self):
        mongo_client = pymongo.MongoClient(self.url, tlsCAFile=certifi.where())
        return mongo_client

    def collection(self, collection_name: str):
        if self._query is None:
            raise ValueError("Database Name not defined")
        return self._query[collection_name]

    def database(self, name: str):
        if not isinstance(name, str):
            raise ValueError(f"{name} is not a valid database name")
        self._query = self._database(name)
        return self

    def _database(self, name):
        return self.__get_mgdb_client()[name]

class MgdbManager:
    __collection_class = None
    __default_db_name = None
    __mandatory_settings = {}
    __settings = {"strictmode": True}
    def __init__(self, mongo_url, default_db_name: str, settings={"strictmode": True}):
        if not isinstance(default_db_name, str):
            raise ValueError("Database name must be a string!")

        if not isinstance(mongo_url, str):
            raise ValueError("Mongo Url must be a string!")

        self.__default_db_name = default_db_name
        self.mongo_url = mongo_url
        self._mgdb = MgdbClass(self.mongo_url)

    def update_settings(self, settings:dict):
        self.__settings = {**self.__settings, **settings, **self.__mandatory_settings}
        return self.__settings

    def __checks(self):
        """Class level error checks"""
        if self.__collection_class is None:
            if self.__settings.get("strictmode")==True:
                raise ValueError(
                    "Collection class has not been registered. Call register_collection_class first!"
                )
            warnings.simplefilter("always", SyntaxWarning)
            warnings.warn(
                f"Collection class is missing, Please use collection class. Refer to https://github.com/ArunVenkata/MgdbORM/blob/master/README.md",
                category=SyntaxWarning,
                stacklevel=2
            )
            warnings.simplefilter("default", SyntaxWarning)

        if self.__default_db_name is None:
            raise ValueError("Default Database name has not been specified")

    def register_collection_class(self, class_ref):
        if not issubclass(class_ref, enum.Enum):
            raise ValueError("Class type not valid, class must inherit from Enum!")
        self.__collection_class = class_ref

    def get(self, collection_name: __collection_class) -> Collection:

        self.__checks()

        if isinstance(collection_name, self.__collection_class):
            collection_name = collection_name.value

        return self._mgdb.database(self.__default_db_name).collection(
            collection_name
        )

class MandateMgdbManager:
    mgdb_manager = None

    def __init__(self, *args, **kwargs):
        if not isinstance(kwargs.get("mgdb_manager_instance"), MgdbManager):
            raise ValueError(
                "MgdbManager instance Missing!\nAssign mgdb_manager_instance to be an instance of MgdbManager!"
            )
        self.mgdb_manager: MgdbManager = kwargs.get("mgdb_manager_instance")

__all__ = ("MgdbClass", "MgdbManager", "MandateMgdbManager")


def countOddSumSubSeq(A, N, curr_sum, DP):

    if str(N)+":"+str(curr_sum) in  DP:
        return DP[str(N)+":"+str(curr_sum)]
    if N == -1:
        if abs(curr_sum)%2 !=0:
            return 1
        else:
            return 0
    else:
        DP[str(N)+":"+str(curr_sum)] = countOddSumSubSeq(A, N-1, curr_sum+A[N], DP)+countOddSumSubSeq(A, N-1, curr_sum, DP)
        return DP[str(N)+":"+str(curr_sum)]
class Solv:
    def solve(self, A):
        DP = {}
        return countOddSumSubSeq(A, len(A)-1, 0, DP)

A = [1, 2, 2, 3]
sol =Solv()
print(sol.solve(A))


# run with : python3 -m unittest TestLMFitter

import unittest
import os
import numpy as numpy
from numpy.testing import assert_array_almost_equal as assertAAE
from astropy import units
import math

import matplotlib.pyplot as plt

from BayesicFitting import *
from BayesicFitting import LevenbergMarquardtFitter as LMFitter

from BayesicFitting import formatter as fmt

__author__ = "Do Kester"
__year__ = 2017
__license__ = "GPL3"
__version__ = "0.9"
__maintainer__ = "Do"
__status__ = "Development"

#  *
#  * This file is part of the BayesicFitting package.
#  *
#  * BayesicFitting is free software: you can redistribute it and/or modify
#  * it under the terms of the GNU Lesser General Public License as
#  * published by the Free Software Foundation, either version 3 of
#  * the License, or ( at your option ) any later version.
#  *
#  * BayesicFitting is distributed in the hope that it will be useful,
#  * but WITHOUT ANY WARRANTY; without even the implied warranty of
#  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#  * GNU Lesser General Public License for more details.
#  *
#  * The GPL3 license can be found at <http://www.gnu.org/licenses/>.
#  *
#  * A JAVA version of this code was part of the Herschel Common
#  * Science System (HCSS), also under GPL3.
#  *
#  *  2004 - 2014 Do Kester, SRON (Java code)
#  *  2017        Do Kester

class Test( unittest.TestCase ):
    """
    Test harness for Fitter class.

    Author:      Do Kester

    """
    def __init__( self, testname ):
        super( ).__init__( testname )
        self.doplot = ( "DOPLOT" in os.environ and os.environ["DOPLOT"] == "1" )

    def makeData( self, bg=False ) :

        p = [3.2, -0.1, 0.3, 1.1, 2.1]
        ss = 0.3

        ndata = 101
        x = numpy.linspace( -1, +1, ndata, dtype=float )
        y = ( x - p[1] ) / p[2]
        numpy.random.seed( 3456 )
        y = p[0] * numpy.exp( -y * y ) + ss * numpy.random.randn( ndata )
        if not bg :
            return (x,y,p[:3])

        y += ( p[3] + p[4] * x )
        return (x,y,p)

    def eq( self, a, b, eps=1e-10 ) :
        if ( a + b ) != 0 :
            return abs( a - b ) / abs( a + b ) < eps
        else :
            return abs( a - b ) < eps

################################################################################
    def test1( self ):

        x,y,p1 = self.makeData()

        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )
        print( "Testing Nonlinear Fitters: LevenbergMarquardt (lm)" )
        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )
        modl1 = GaussModel( )

        amfit = LMFitter( x, modl1 )

        print( "truth   ", fmt( p1 ) )
        par1 = amfit.fit( y )

        print( "pars1   ", fmt( par1 ) )
        assertAAE( par1, p1, 1 )
        print( "chisq1  ", amfit.chisq )
        print( "hessian \n", fmt( amfit.hessian ) )
        print( "design  \n", fmt( amfit.design[-4:,:], max=None ) )

        print( "With background" )
        x,z,p2 = self.makeData( bg=True )

        modl2 = GaussModel( )
        modl2.addModel( PolynomialModel(1) )

        modl2.parameters = numpy.append( par1, [0,0] )
        lmfit = LMFitter( x, modl2 )

        par2 = lmfit.fit( z )
        print( "truth   ", fmt( p2 ) )
        print( "pars2   ", fmt( par2 ) )

        print( "chisq2  ", lmfit.chisq )

        assertAAE( par2, p2, 1 )

        print( "hessian \n", fmt( lmfit.hessian ) )
        print( "design  \n", fmt( lmfit.design[-4:,:], max=None ) )

        if self.doplot :
            xx = numpy.linspace( -1, +1, 1001 )
            plt.plot( x, y, 'k+' )
            plt.plot( xx, modl1.result( xx ), 'k-' )
            plt.plot( x, z, 'r+' )
            plt.plot( xx, modl2.result( xx ), 'r-' )
            plt.show()

    def test2( self ):

        x,y,p1 = self.makeData()

        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )
        print( "Testing LevenbergMarquardt (normalized)" )
        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )
        modl1 = GaussModel( )

        amfit = LMFitter( x, modl1 )

        par1 = amfit.fit( y )

        bmfit = LMFitter( x, modl1 )

        conpr1 = numpy.asarray( [1.0,0.0,0.0] )

        bmfit.normalize( conpr1, p1[0], weight=10.0 )

        print( "Normweight = ", bmfit.normweight )

        print( "truth  ", fmt( p1 ) )

        par3 = bmfit.fit( y )
        print( "pars3  ", fmt( par3 ) )
        print( "chisq  ", fmt( bmfit.chisq ) )

        hes1 = amfit.getHessian( params=par3 )
        print( "hessian\n", fmt( hes1 ) )
        hes3 = bmfit.getHessian( params=par3 )
        print( "hessian\n", fmt( hes3 ) )

        f = bmfit.normweight
        for h1,h3 in zip( hes1.flat, hes3.flat ) :
            self.assertTrue( abs( h1 + f - h3 ) < 1e-8 )
            f = 0.0

        if self.doplot :
            xx = numpy.linspace( -1, +1, 1001 )
            plt.plot( x, y, 'k+' )
            plt.plot( xx, modl1.result( xx ), 'g-' )
            plt.show()

    def test3( self ):

        x,y,p1 = self.makeData( bg=True )

        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )
        print( "Testing Linear Fitter with limits" )
        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )

        print( "   1. no limits and keep in fit " )

        modl1 = GaussModel( )
        modl1.addModel( PolynomialModel(1) )

        amfit = LMFitter( x, modl1 )

#        par0 = amfit.limitsFit( amfit.fit, y )
        par0 = amfit.limitsFit( y )
        print( "pars0   ", fmt( par0 ) )
        print( "stdv0   ", fmt( amfit.stdevs ) )
        print( "chisq0  ", amfit.chisq )

#        par1 = amfit.limitsFit( amfit.fit, y, keep={0:3.3} )
        par1 = amfit.limitsFit( y, keep={0:3.3} )
        print( "pars1   ", fmt( par1 ) )
        print( "stdv1   ", fmt( amfit.stdevs ) )
        print( "chisq1  ", amfit.chisq )

        printclass( amfit )

        print( "   2. limits and keep in fit " )
        gm = GaussModel()
        gm.setLimits( [-3.0, -1.0, 0.1], [3.0, 1.0, 1.0] )
        pm = PolynomialModel( 1 )
        pm.setLimits( [-5], [5] )
        modl2 = gm + pm

        lmfit = LMFitter( x, modl2 )

#        par2 = lmfit.limitsFit( lmfit.fit, y )
        par2 = lmfit.limitsFit( y )
        print( "pars2   ", fmt( par2 ) )
        print( "stdv2   ", fmt( lmfit.stdevs ) )
        print( "chisq2  ", lmfit.chisq )

#        par3 = lmfit.limitsFit( lmfit.fit, y, keep={0:3.3} )
        par3 = lmfit.limitsFit( y, keep={0:3.3} )
        print( "pars3   ", fmt( par3 ) )
        print( "stdv3   ", fmt( lmfit.stdevs ) )
        print( "chisq3  ", lmfit.chisq )

        printclass( lmfit )

        print( "   2. limits and keep in fitter and fit " )
        gm = GaussModel()
        gm.setLimits( [-3.0, -1.0, 0.1], [3.0, 1.0, 1.0] )
        pm = PolynomialModel( 1 )
        pm.setLimits( [-5], [5] )
        modl3 = gm + pm

        lmfit = LMFitter( x, modl3, keep={4:5.0} )

#        par4 = lmfit.limitsFit( lmfit.fit, y )
        par4 = lmfit.limitsFit( y )
        print( "pars4   ", fmt( par4 ) )
        print( "stdv4   ", fmt( lmfit.stdevs ) )
        print( "chisq4  ", lmfit.chisq )

#        par5 = lmfit.limitsFit( lmfit.fit, y, keep={0:3.3} )
        par5 = lmfit.limitsFit( y, keep={0:3.3} )
        print( "pars5   ", fmt( par5 ) )
        print( "stdv5   ", fmt( lmfit.stdevs ) )
        print( "chisq5  ", lmfit.chisq )

        printclass( lmfit )

        if self.doplot :
            xx = numpy.linspace( -1, +1, 1001 )
            plt.plot( x, y, 'k+' )
            plt.plot( xx, modl1.result( xx ), 'k-' )

            plt.plot( xx, modl2.result( xx ), 'r-' )
            plt.show()

    def test5( self ):

        x,y,p1 = self.makeData( bg=True )

        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )
        print( "Testing Nonlinear Fitters: LevenbergMarquardt (lm)" )
        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )
        modl1 = GaussModel( )
        modl1.addModel( PolynomialModel( 1 ) )

        amfit = LMFitter( x, modl1 )

        print( "truth   ", fmt( p1 ) )
#        par1 = amfit.limitsFit( amfit.fit, y )
        par1 = amfit.limitsFit( y )

        print( "pars1   ", fmt( par1 ) )
        assertAAE( par1, p1, 1 )
        print( "chisq1  ", amfit.chisq )
        print( "hessian \n", fmt( amfit.hessian ) )
        print( "design  \n", fmt( amfit.design[-4:,:], max=None ) )

        gm = GaussModel( )
        gm.setLimits( [0.0, -1.0, 0.0], [3.2, 1.0, 1.0] )
        pm = PolynomialModel( 1 )
        pm.setLimits( [0.0, 0.0], [2.0, 2.0] )
        modl2 = gm + pm

        modl2.parameters = par1
        lmfit = LMFitter( x, modl2 )

#        par2 = lmfit.limitsFit( lmfit.fit, y )
        par2 = lmfit.limitsFit( y )
        print( "pars2   ", fmt( par2 ) )

        print( "chisq2  ", lmfit.chisq )

        assertAAE( par1, par2, 1 )

        print( "hessian \n", fmt( lmfit.hessian ) )
        print( "design  \n", fmt( lmfit.design[-4:,:], max=None ) )

        if self.doplot :
            xx = numpy.linspace( -1, +1, 1001 )
            plt.plot( x, y, 'k+' )
            plt.plot( xx, modl1.result( xx ), 'k-' )

            plt.plot( xx, modl2.result( xx ), 'r-' )
            plt.show()

    def test6( self ) :

        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )
        print( "Testing AmoebaFitter using a map" )
        print( "++++++++++++++++++++++++++++++++++++++++++++++++++" )

        N = 71
        b0 = 3.5            # amplitude of source
        b1 = 30             # position
        b2 = 45             # position
        b3 = 13             # size of source
        b4 = 0.3            # background

        sig = 0.2

        x = numpy.arange( N, dtype=float )
        x1 = ( x - b1 ) / b3
        y1 = numpy.exp( - x1 * x1 )
        x2 = ( x - b2 ) / b3
        y2 = numpy.exp( - x2 * x2 )

        y = b0 * numpy.outer( y1, y2 ) + b4
        numpy.random.seed( 130105 )
        y += sig * numpy.random.randn( N, N )

        mdl = Kernel2dModel( kernel=Gauss(), shape='circular' )
        mdl += PolySurfaceModel( 0 )
        print( mdl )
        lo = [0, 0, 0, 0.01, 0 ]
        hi = [10, 70, 70, 70, 10 ]
        #mdl.setLimits( lo, hi )
        par = [5.0,30.0,30.0,30.0,5.0]
        mdl.parameters = par

        fitter = AmoebaFitter( y, mdl, map=True )
        print( "y      ", y.shape )
        print( "xdata  ", fitter.xdata.shape )

        # find the parameters
        param = fitter.fit( y, temp=10, maxiter=100000, size=5 )

        print( "yfit   ", fitter.yfit.shape )
        print( "mdlfit ", mdl( fitter.xdata ).shape )

        print( "Parameters :", fmt( param, max=None ) )
        print( "StDevs     :", fmt( fitter.stdevs, max=None ) )
        print( "Chisq      :", fmt( fitter.chisq ) )
        print( "Scale      :", fmt( fitter.scale ) )
        print( "Evidence   :", fmt( fitter.getEvidence( limits=[-100,100] ) ) )
        print( "Covar matrix :" )
        print( fmt( fitter.covariance))

    def test4( self ) :

        self.normalizetest( Fitter )
        self.normalizetest( QRFitter )
        self.normalizetest( CurveFitter )
        self.normalizetest( LMFitter )
        self.assertRaises( NotImplementedError, self.normalizetest, AmoebaFitter )
#        self.assertRaises( NotImplementedError, self.normalizetest, PowellFitter )

    def normalizetest( self, fitter ) :

        p = numpy.asarray( [2.0, 1.3] )
        x = numpy.asarray( [1.0, 1.3, 1.5, 1.8, 2.0] )
        numpy.random.seed( 12345 )
        y = p[0] + p[1] * x + 0.5 * numpy.random.randn( 5 )

        m = PolynomialModel( 1 )

        ftr = fitter( x, m )
        print( "=============================================================" )
        print( str( ftr ) )
        print( "xdata  ", fmt( x ) )
        print( "ydata  ", fmt( y ) )

        par = ftr.fit( y )
        print( "truth  ", fmt( p ) )
        print( "param  ", fmt( par ) )

        conpr = numpy.asarray( [1.0,0.0] )
        for w in [0,1,10,100,1000] :
            m2 = m.copy()
            ftr = fitter( x, m2 )

            ftr.normalize( conpr, p[0], weight=w )

            par = ftr.fit( y )
            print( fmt( w ), fmt( par ), fmt( ftr.chisq ) )

        self.assertTrue( abs( p[0] - par[0] ) < 1e-3 )

        print( fmt( ftr.hessian ) )
#        print( fmt( ftr.getVector( y ) ) )

    @classmethod
    def suite( cls ):
        return unittest.TestCase.suite( TestLMFitter.__class__ )


n = int(input())
result = []
for i in range(0,n):
    goal = list(map(int,input().split(' ')))
    num = goal[0]
    if(num >= sum(range(goal[1] + 1))):
        result.append(1)
    else:
        result.append(0)
for item in result:
    print(item)


import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

def shorten_categories(categories,cutoff):
    categories_map = {}
    for i in range(len(categories)):
        if categories.values[i] >= cutoff:
            categories_map[categories.index[i]] = categories.index[i]
        else :
            categories_map[categories.index[i]] = 'Other'
    return categories_map

def clean_YearsCodePro(x):
    if x == 'More than 50 years':
        return 50
    if x == 'Less than 1 year':
        return 0.5
    return float(x)

def clean_education(x):
    if 'Bachelor’s degree' in x:
        return 'Bachelor’s degree'
    if 'Master’s degree' in x:
        return 'Master’s degree'
    if 'Professional degree' in x or 'Other doctoral' in x:
        return 'Post grad'
    return 'Less than a Bachelors'

@st.cache #Decorator to cache the DataFrame
def load_data():
	df_new = pd.read_csv('survey_results_public.csv')
	df_new = df_new[['Country','EdLevel','YearsCodePro','Employment','ConvertedCompYearly']]
	df_new = df_new.rename({'ConvertedCompYearly':'Salary'},axis=1)
	df_new = df_new[df_new['Salary'].notnull()]
	df_new = df_new.dropna()
	df_new = df_new[df_new['Employment'] == 'Employed full-time']
	df_new = df_new.drop('Employment',axis=1)
	country_map = shorten_categories(df_new.Country.value_counts(),400)
	df_new['Country'] = df_new['Country'].map(country_map)
	df_new = df_new[df_new['Salary'] <= 150000]
	df_new = df_new[df_new['Salary'] >= 10000]
	df_new = df_new[df_new['Country'] != 'Other']
	df_new['YearsCodePro'] = df_new['YearsCodePro'].apply(clean_YearsCodePro)
	df_new['EdLevel'] = df_new['EdLevel'].apply(clean_education)

	return df_new

df = load_data()

def show_explore_page():
	st.title("Explore Software Engineer Salaries")
	st.write("""
		### Stack Overflow Developer Survey 2021
		""")

	data = df['Country'].value_counts()

	fig1, ax1 = plt.subplots()
	ax1.pie(data, labels=data.index, autopct="%1.1f%%", shadow=True, startangle=90)
	ax1.axis("equal")

	st.write("""#### Number of Data from different countries""")
	st.pyplot(fig1)

	st.write("""#### Mean Salary Based on Country""")
	data = df.groupby(["Country"])['Salary'].mean().sort_values(ascending=True)
	st.bar_chart(data, width=1000, height=600)

	st.write("""#### Mean Salary Based on Experience""")
	data = df.groupby(["Country"])['Salary'].mean().sort_values(ascending=True)
	st.line_chart(data, width=1000, height=450)


# coding: utf-8

# ## Example
# * This Python example shows the non-linear superposition with parameter **$2*a=alpha=0.6$, in the Bark scale**. We construct a matrix which does the actual superposition in the Bark domain, because that is most efficient:

# In[1]:

import numpy as np

def spreadingfunctionmat(maxfreq,nfilts,alpha):
    #Arguments: maxfreq: half the sampling frequency
    #nfilts: Number of subbands in the Bark domain, for instance 64
    fadB= 14.5+12 # Simultaneous masking for tones at Bark band 12
    fbdb=7.5 # Upper slope of spreading function
    fbbdb=26.0 # Lower slope of spreading function
    maxbark=hz2bark(maxfreq)
    spreadingfunctionBarkdB=np.zeros(2*nfilts)

    #upper slope, fbdB attenuation per Bark, over maxbark Bark (full frequency range), with fadB dB simultaneous masking:
    spreadingfunctionBarkdB[0:nfilts]=np.linspace(-maxbark*fbdb,-2.5,nfilts)-fadB

    #lower slope fbbdb attenuation per Bark, over maxbark Bark (full frequency range):
    spreadingfunctionBarkdB[nfilts:2*nfilts]=np.linspace(0,-maxbark*fbbdb,nfilts)-fadB

    #Convert from dB to "voltage" and include alpha exponent
    spreadingfunctionBarkVoltage=10.0**(spreadingfunctionBarkdB/20.0*alpha)

    #Spreading functions for all bark scale bands in a matrix:
    spreadingfuncmatrix=np.zeros((nfilts,nfilts))
    for k in range(nfilts):
        spreadingfuncmatrix[:,k]=spreadingfunctionBarkVoltage[(nfilts-k):(2*nfilts-k)]
    return spreadingfuncmatrix

# The above produces a prototype of spreading functions for all the bark bands(bark counts based on the resolution)

# Below is the psyacmodel python example

# In[2]:

get_ipython().magic(u'matplotlib inline')
from psyacmodel import *
import matplotlib.pyplot as plt

fs=32000 # sampling frequency of audio signal
maxfreq=fs/2
alpha=0.6 #Exponent for non-linear superposition of spreading functions
nfilts=64 #number of subbands in the bark domain

spreadingfuncmatrix=spreadingfunctionmat(maxfreq,nfilts,alpha)

plt.imshow(spreadingfuncmatrix)
plt.title('Matrix spreadingfuncmatrix as Image')
plt.xlabel('Bark Domain Subbands')
plt.ylabel('Bark Domain Subbands')
plt.show()


from aiogram import Bot, Dispatcher, executor, types
from aiogram.utils.deep_linking import get_start_link
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.utils.deep_linking import decode_payload
from aiogram.dispatcher import FSMContext
from aiogram.types import ChatMemberUpdated, ContentType, InlineKeyboardButton, InlineKeyboardMarkup
import logging
import db
import time
import re
import os

API_TOKEN = os.environ['API_TOKEN']

answer_regexp = re.compile("answer_(.*)")
logging.basicConfig(level=logging.DEBUG)

bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)

channels_to_subscribe = []
channel_links = []

class Stage(StatesGroup):
    send_message_to = State()

async def check_subscription(user_id):
    result = True
    for channel in channels_to_subscribe:
        chat_member = await bot.get_chat_member(channel, user_id)
        result = result and chat_member['status'] != 'left'
    return result

@dp.message_handler(commands=['start'], state=['*', Stage.send_message_to])
async def start(message: types.Message, state: FSMContext):
    is_subscribed = await check_subscription(message.from_user.id)
    inline_kb = InlineKeyboardMarkup()
    if not is_subscribed:
        for channel_link in channel_links:
            inline_btn = InlineKeyboardButton('Channel', url=channel_link)
            inline_kb.add(inline_btn)
        await message.answer('Please subscribe to the channels to use the bot.', reply_markup=inline_kb)
        return
    args = message.get_args()
    payload = decode_payload(args)
    if payload:
        async with state.proxy() as data:
            data['user-id'] = payload
        await Stage.send_message_to.set()
        start_text = """Send an anonymous message to this person who posted this link.

Write here everything you think about him in one message and in a few moments he will receive it, but he will not know who it is from.

👀 You can send text, voice message, photo or video."""
        await message.reply(start_text)
        db.add_user(message.from_user.id, message.from_user.username, time.time())
        return
    link = await get_start_link(message.from_user.id, encode=True)
    content = f"""❗INSTRUCTIONS FOR USE:
1. Copy this link: {link}

2. Paste it into the profile description or insta-story, AS IN THE SCREENSHOT

3. We are waiting for anonymous questions :)

P.S. the link is personal, by clicking on it, the person will send a message to YOU"""
    with open('inst.jpg', 'rb') as photo:
        await message.answer_photo(caption=content, photo=photo)
    db.add_user(message.from_user.id, message.from_user.username, time.time())

@dp.my_chat_member_handler()
async def add_to_channel(update: ChatMemberUpdated):
    if update.new_chat_member.status == 'member':
        db.add_user(update.from_user.id, update.from_user.username, time.time())
    elif update.new_chat_member.status == 'kicked':
        db.delete_user(update.from_user.id)

@dp.message_handler(state=Stage.send_message_to, content_types=ContentType.ANY)
async def process_message(message: types.Message, state: FSMContext):
    is_subscribed = await check_subscription(message.from_user.id)
    inline_kb = InlineKeyboardMarkup()
    if not is_subscribed:
        for channel_link in channel_links:
            inline_btn = InlineKeyboardButton('Channel', url=channel_link)
            inline_kb.add(inline_btn)
        await message.answer('Please subscribe to the channels to use the bot.', reply_markup=inline_kb)
        return
    inline_btn = InlineKeyboardButton('Reply', callback_data=f'answer_{message.from_user.id}')
    inline_btn2 = InlineKeyboardButton('Share the reply on Instagram', url='https://www.instagram.com/')
    inline_kb = InlineKeyboardMarkup().add(inline_btn)
    inline_kb = inline_kb.add(inline_btn2)
    async with state.proxy() as data:
        if 'answer_user_id' in data:
            user_id = data['answer_user_id']
            await message.answer("Your response has been delivered.")
            await message.bot.send_message(user_id,
                                           'You got an answer. To ask a question to a person again, follow his link again.')
        else:
            user_id = data['user-id']
            await message.answer(
                "Your message has been sent. To ask a question to a person again, follow his link again.")
            await message.bot.send_message(user_id, 'You have received a new anonymous message.')
        if message.video:
            await message.bot.send_video(user_id, message.video.file_id, reply_markup=inline_kb)
            content = message.video.as_json()
        elif message.video_note:
            await message.bot.send_video_note(user_id, message.video_note.file_id, reply_markup=inline_kb)
            content = message.video_note.as_json()
        elif message.voice:
            await message.bot.send_voice(user_id, message.voice.file_id, reply_markup=inline_kb)
            content = message.voice.as_json()
        elif message.photo:
            await message.bot.send_photo(user_id, message.photo[-1].file_id, reply_markup=inline_kb)
            content = message.photo[-1].as_json()
        elif message.audio:
            await message.bot.send_audio(user_id, message.audio.file_id, reply_markup=inline_kb)
            content = message.audio.as_json()
        elif message.sticker:
            await message.bot.send_sticker(user_id, message.sticker.file_id, reply_markup=inline_kb)
            content = message.sticker.file_id
        elif message.document:
            await message.bot.send_document(user_id, message.document.file_id, reply_markup=inline_kb)
            content = message.document.as_json()
        else:
            await message.bot.send_message(user_id, message.text, reply_markup=inline_kb)
            content = message.text
    await state.finish()
    user_to = await bot.get_chat_member(user_id, user_id)
    if 'answer_user_id' in data:
        message_type = 'answer'
    else:
        message_type = 'question'
    db.add_message(message.from_user.id,
                   user_id, message.from_user.username,
                   user_to.user.username, content,
                   message_type, time.time())

@dp.callback_query_handler(lambda c: answer_regexp.match(c.data), state=['*', Stage.send_message_to])
async def process_callback_answer(callback_query: types.CallbackQuery, state: FSMContext):
    await bot.answer_callback_query(callback_query.id)
    await bot.send_message(callback_query.from_user.id, 'Enter your answer (voice, picture, video, text).')
    async with state.proxy() as data:
        data['answer_user_id'] = answer_regexp.match(callback_query.data).group(1)
    await Stage.send_message_to.set()

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=False)