#!/usr/bin/env python
"""
``onecodex``
------------

``onecodex`` provides a command line client and Python library for
interacting with the One Codex API.

Links
`````
* `One Codex: <https://www.onecodex.com/>`
* `API Docs: <http://docs.onecodex.com/>`

"""
from setuptools import setup, find_packages

with open("onecodex/version.py") as import_file:
    exec(import_file.read())

with open("README.md") as readme:
    README = readme.read()

# Dependencies
TESTING_DEPS = [
    "coverage",
    "pytest",
    "pytest-cov",
    "responses",
    "testfixtures",
    "mock",
    "vega_datasets",
    "pre-commit",
    "pdfplumber",
]
ALL_DEPS = [
    "altair==4.2.2",
    "numpy>=1.11.0",
    "pandas>=1.0.3",
    "pillow>=9.0.1",
    "scikit-bio>=0.5.8",
    "scikit-learn>=0.19.0",
    "scipy",
    "jupyter-client==7.2.0",
]
REPORT_DEPS = ALL_DEPS + [
    "notebook==6.4.10",
    "nbconvert>=6",
    # Hardcoding jinja2 version for https://github.com/jupyter/nbconvert/issues/1742
    "jinja2<=3.1",
    "WeasyPrint==59.0",
    "altair-saver==0.5.0",
    "selenium<4.3.0",  # see https://github.com/altair-viz/altair_saver/issues/104
]

setup(
    name="onecodex",
    version=__version__,  # noqa
    packages=find_packages(exclude=["*test*"]),
    python_requires=">=3.8",
    install_requires=[
        "boto3>=1.17.98",
        "click>=8.0",
        "jsonschema>=3.0",
        "python-dateutil>=2.5.3",
        "pytz>=2014.1",
        "sentry-sdk>=0.10.2",
        "requests>=2.27.1",
        "requests_toolbelt>=0.7.0",
        "six>=1.10.0",
        "unidecode>=1.0.23",
        "filelock>=3.0.12,<4",
    ],
    include_package_data=True,
    zip_safe=False,
    extras_require={
        "all": ALL_DEPS,
        "reports": REPORT_DEPS,
        "testing": TESTING_DEPS,
    },
    author="One Codex",
    author_email="opensource@onecodex.com",
    description="One Codex API client and Python library",
    long_description=README,
    long_description_content_type="text/markdown",
    license="MIT License",
    keywords="One Codex API Client",
    url="https://github.com/onecodex/onecodex",
    classifiers=[
        "Environment :: Console",
        "License :: OSI Approved :: MIT License",
        "Topic :: Scientific/Engineering :: Bio-Informatics",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Internet :: WWW/HTTP",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3 :: Only",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
    ],
    entry_points={
        "console_scripts": ["onecodex = onecodex.cli:onecodex"],
        "nbconvert.exporters": [
            "onecodex_pdf = onecodex.notebooks.exporters:OneCodexPDFExporter",
            "onecodex_html = onecodex.notebooks.exporters:OneCodexHTMLExporter",
            "onecodex_doc = onecodex.notebooks.exporters:OneCodexDocumentExporter",
        ],
    },
    test_suite="tests",
)


import requests
import pandas as pd
import streamlit as st

def app():

    #inputs
    week = 15

    hold_wallets = ['GNc185Keqebtg8aKcGW27FGwq1j4k4vG25evVe61CrHE', 'G5FbQJTfGWwgLxTk1tUe6NpfjAUcY9UBnjKuA2nGqrdW',
                    '4zHL5ioFdLVmbK2eHzrvW9zVehR1jhnJqyQodT8fAuhU','52a6HJHqGWNPsjqMGjyWYSdf2KpjwRZ6Kp8bYSLbPQty',
                    'AqpNPzQFqsXngfH2pwtN8xiDpRtAManMU7t2Ku2bE5Hx','BtzWy68tqCYYZVSK9iqLEu1CSnKKwfG9NE5tpr3sJZ6D',
                    '3g1FF1wTyv4guNSZLX5Hb8FYVspv7d1bPKAuK9fXpijq','H8zN9ByTsougVbga5Pyiav3Tse9DyEruXyoceKrBGzFz',
                    '8ATd1GZaZQCmy2frV7bjg9gEqW8vwu5Lao6ydCRuMksd','ANionh4uLhpDRgUWxwCjQ5qPmrhnHEodZ6ngs1WUMPXc',
                    'Cb9EGRp5E45SVzJJVunaRjDAbXGhi1Ez7SmrdayVvYRT','83sE14avcn654GRjs38HDVL1ui8ysSnC2Spkwo8hTabk',
                    'G5FbQJTfGWwgLxTk1tUe6NpfjAUcY9UBnjKuA2nGqrdW', 'FFbxRPpeqfSi5gnrhh1iGbqdZ7VyVNDYEbPcgfjktTpd',
                    'G5FbQJTfGWwgLxTk1tUe6NpfjAUcY9UBnjKuA2nGqrdW'
                    ]

    mint_wallets = ['BJrgn9rG2Yht724a9xSzW2NGXNuxMvrkPhr93x8bgS3Q', 'BL6FcJaaBh8gS6scKM7Bwjpom2Zt1qGdX2YtHPKSuh1M',
                    '7hdTiiPfXUVQJhzJwXCQiB3BZz3uydCEPbyxYjbgU8AB', '5T34gvjZn9weBe6Uogxi4em4MPKAc87CHe3yvqp2s5gK',
                    'CjpEdDMam97bGWfTVhKy5RS1Ha1Qizg7nKFmz7P7ZmYz', 'CeHp4cmKbbyey5b4CoTWfJmFCa34otE9nQtghfhiyWys',
                    'HyNFUGdT8ikdytmT36hiXKX6bQdiRL6ztbfsQsXKwgbe', '2WLb1me2uF9xM6iHoXvyhj8zt1k8NtRQLkyPvL7nEGE8',
                    '6aZ58KguXD1zR6xwFhG45yWq853jtKe3qvgWWfgoH4X4', 'A4Kk3SH1HxZr8TGJcF3sTBXns32c4jkXqrEkFVr72QZk',
                    'ABsKmyQNygQpeTTj6jw7Ud1jiAjMpkAZU1awN89Z5Zeu', 'HJJU28gUMCckq9VR6TY639amYQ2jb3XcdCaTEkkPegce',
                    'BL6FcJaaBh8gS6scKM7Bwjpom2Zt1qGdX2YtHPKSuh1M','44z22UtScfZcisUVD9TuV7QJESA2v7oKZSDx5AgCJuMh',
                    'BL6FcJaaBh8gS6scKM7Bwjpom2Zt1qGdX2YtHPKSuh1M'
                    ]

    makeup_wallets = ['4zWrm2oMQGHKqAs3j5xenitorSfQHJeV28S737r23AhM']

    hold_values = [1.275, 0.404, 0.165, 0.111, 0.03, 0.0295, 0.0235, 0.021, 0.0125, 0.0101, 0.0065, 0.006275, 0.00575, 0.0275, 0.024]

    mint_values = [0.225, 0.07, 0.024, 0.01625, 0.005, 0.00525, 0.004, 0.0035, 0.0021, 0.0015, 0.001, 0.001, 0.001, 0.00475, 0.0042]

    SOL_values = [157,144,157,213,203,252,238,220,204,195,155,178,174,168,135]

    #rest is automatic
    headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    page = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd&include_last_updated_at=true', headers=headers).json()
    solPrice = page['solana']['usd']

    dates = pd.date_range(start='10/4/2021', periods = week,freq='W-MON')

    hold_init = [0] * (week+1)
    mint_init = [0] * (week+1)

    wk_gen = ['Week {}'.format(i) for i in range(1, week+2)]
    wk_gen[-1] = 'Makeup'

    df = pd.DataFrame(index=[wk_gen], columns=['Holder','Minter','# Held','# Minted'])

    st.title('Weekly Rewards Checker')

    input = st.text_area("Enter your SOL wallets, enter each wallet in a new row")
    input = "EbXvaxV15vjJFV2jD1iuzYAULY4g1Rak2FNX4oJJxa1Y"

    if input is not None:
        wallets = input.splitlines()

    for wallet in wallets:
        resp = requests.get("https://api.solscan.io/account/soltransfer/txs?address=" + wallet + "&offset=0&limit=100000", headers=headers).json()
        count1 = 2
        count2 = 2
        for tx in resp['data']['tx']['transactions']:
            if tx['src'] in hold_wallets:
                idx = hold_wallets.index(tx['src'])
                print(idx)
                if idx == 1 and count1 == 2: #week 15 temp fix
                    idx = 14
                    hold_init[idx] = hold_init[idx]+ tx['lamport']/1000000000
                    df.loc['Week ' + str(idx+1), 'Holder'] = hold_init[idx]
                    df.loc['Week ' + str(idx+1), '# Held'] = round(hold_init[idx]/hold_values[idx],2)
                    count1 = count1 - 1
                elif idx == 1 and count1 == 1: #week 13 temp fix
                    idx = 12
                    hold_init[idx] = hold_init[idx]+ tx['lamport']/1000000000
                    df.loc['Week ' + str(idx+1), 'Holder'] = hold_init[idx]
                    df.loc['Week ' + str(idx+1), '# Held'] = round(hold_init[idx]/hold_values[idx],2)
                    count1 = count1 - 1
                else:
                    hold_init[idx] = hold_init[idx]+ tx['lamport']/1000000000
                    df.loc['Week ' + str(idx+1), 'Holder'] = hold_init[idx]
                    df.loc['Week ' + str(idx+1), '# Held'] = round(hold_init[idx]/hold_values[idx],2)

            elif tx['src'] in mint_wallets:
                idx = mint_wallets.index(tx['src'])
                if idx == 1 and count2 == 2: #week 13 temp fix
                    idx = 14
                    mint_init[idx] = mint_init[idx]+ tx['lamport']/1000000000
                    df.loc['Week ' + str(idx+1), 'Minter'] = mint_init[idx]
                    df.loc['Week ' + str(idx+1), '# Minted'] = round(mint_init[idx]/mint_values[idx],2)
                    count2 = count2 - 1
                elif idx == 1 and count2 == 1: #week 13 temp fix
                    idx = 12
                    mint_init[idx] = mint_init[idx]+ tx['lamport']/1000000000
                    df.loc['Week ' + str(idx+1), 'Minter'] = mint_init[idx]
                    df.loc['Week ' + str(idx+1), '# Minted'] = round(mint_init[idx]/mint_values[idx],2)
                    count2 = count2 - 1
                else:
                    mint_init[idx] = mint_init[idx]+ tx['lamport']/1000000000
                    df.loc['Week ' + str(idx+1), 'Minter'] = mint_init[idx]
                    df.loc['Week ' + str(idx+1), '# Minted'] = round(mint_init[idx]/mint_values[idx],2)

            elif tx['src'] in makeup_wallets:
                idx = makeup_wallets.index(tx['src'])
                hold_init[idx] = hold_init[idx]+ tx['lamport']/1000000000
                df.loc['Makeup', 'Holder'] = hold_init[idx]

    #sum sol df
    temp_df = pd.DataFrame(data = [df['Holder'][0:week+1].tolist(),df['Minter'][0:week+1].tolist()]).T

    wk_gen2 = ['Week {}'.format(i) for i in range(1, week+2)]
    wk_gen2[-1] = 'Makeup'
    temp_df.index = wk_gen2
    temp_df.columns = ['Holder','Minter']

    temp_df['SUM'] = temp_df.fillna(0)['Holder'] + temp_df.fillna(0)['Minter']
    temp_df['USD'] = temp_df['SUM']*solPrice

    df_sum = pd.DataFrame(data = [temp_df['SUM'].sum(), temp_df['USD'].sum()]).T
    df_sum.columns = (['Sol','USD'])
    df_sum.index = (['Total'])

    col1, col2 = st.columns([1,2.75])

    with col1:
        st.write("You have recieved these rewards:")
        st.table(df)
        st.table(df_sum)

    with col2:
        st.write("Rewards data")

        df2 = pd.DataFrame(data = [dates, hold_values, mint_values, SOL_values,hold_wallets, mint_wallets]).T
        df2.index=(['Week {}'.format(i) for i in range(1, week+1)])
        df2.columns=(['Date','Holder Reward','Minter Reward','SOL/USD','Holder Wallet','Mint Wallet'])
        df2['Date'] = df2['Date'].apply(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d'))

        st.table(df2)
    print(df)

app()


import click
import sys
from .reader import Reader
from ..utils import protocol

@click.group()
def main():
    pass

@main.command('read')
@click.argument('path', type=click.STRING)
def read_sample(path):
    """ Reads the sample binary file from PATH and prints its data. """
    try:
        reader = Reader(path)
        print(f"User details:\n{protocol.repr_protocol_user(reader.user)}")
        print("Snapshots:\n")
        for snapshot in reader:
            print(protocol.repr_protocol_snapshot(snapshot))
    except Exception as error:
        print(f'Error: {error}')
        return 1

if __name__ == '__main__':
    try:
        main()
    except Exception as err:
        click.echo(f'ERROR: {err}')
        sys.exit(1)


import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn.decomposition import PCA as sklearnPCA
from sklearn.cluster import KMeans , AgglomerativeClustering , DBSCAN
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import MinMaxScaler

headers = ['status_id','status_type','status_published','num_reactions','num_comments',
          'num_shares','num_likes','num_loves','num_wows','num_hahas','num_sads','num_angrys','1','2','3','4'
]
header = ['status_type','num_reactions','num_comments',
          'num_shares','num_likes','num_loves','num_wows','num_hahas','num_sads','num_angrys'
]

train = pd.read_csv("dataset.csv", header=None,names= headers)
# test = pandas.read_csv("adult.test.csv", header=None , names = header , index_col=False , na_values="?" , skipinitialspace=True)
# dataset = pandas.concat([train,test])
AutoMpg_data = pd.concat([train])
AutoMpg_data.drop(labels=["1", "2", "3", "4",'status_id','status_published'], axis = 1, inplace = True)
AutoMpg_data.info()
for col in header:
    print ("values of %s"%(col))
    print (AutoMpg_data[col].value_counts())
    print (AutoMpg_data[col].count())
    print ('////////////////////////////\n')

plt.rcParams['figure.figsize'] = (18, 7)

plt.subplot(2, 2, 1)
sns.countplot(AutoMpg_data['num_reactions'], palette = 'pastel')
plt.title('num_reactions', fontsize = 10,color='red')
plt.xlabel('num_reactions', fontsize = 10)
plt.ylabel('count', fontsize = 10)

# checking the Distribution of customers on Weekend
plt.subplot(2, 2, 2)
sns.countplot(AutoMpg_data['num_comments'], palette = 'inferno')
plt.title('num_comments', fontsize = 10,color='red')
plt.xlabel('num_comments', fontsize = 10)
plt.ylabel('count', fontsize = 10)

plt.subplot(2, 2, 3)
sns.countplot(AutoMpg_data['num_likes'], palette = 'husl')
plt.title('num_likes', fontsize = 10,color='red')
plt.xlabel('num_likes', fontsize = 10)
plt.ylabel('count', fontsize = 10)

plt.subplot(2, 2, 4)
sns.countplot(AutoMpg_data['num_loves'], palette = 'Paired')
plt.title('num_loves', fontsize = 10,color='red')
plt.xlabel('num_loves', fontsize = 10)
plt.ylabel('count', fontsize = 10)

plt.show()

plt.rcParams['figure.figsize'] = (18, 7)

plt.subplot(2, 2, 1)
sns.countplot(AutoMpg_data['num_sads'], palette = 'pastel')
plt.title('num_sads', fontsize = 10,color='red')
plt.xlabel('num_sads', fontsize = 10)
plt.ylabel('count', fontsize = 10)

# checking the Distribution of customers on Weekend
plt.subplot(2, 2, 2)
sns.countplot(AutoMpg_data['status_type'], palette = 'inferno')
plt.title('status_type', fontsize = 10,color='red')
plt.xlabel('status_type', fontsize = 10)
plt.ylabel('count', fontsize = 10)

plt.subplot(2, 2, 3)
sns.countplot(AutoMpg_data['num_angrys'], palette = 'husl')
plt.title('num_angrys', fontsize = 10,color='red')
plt.xlabel('num_angrys', fontsize = 10)
plt.ylabel('count', fontsize = 10)

plt.subplot(2, 2, 4)
sns.countplot(AutoMpg_data['num_shares'], palette = 'Paired')
plt.title('num_shares', fontsize = 10,color='red')
plt.xlabel('num_shares', fontsize = 10)
plt.ylabel('count', fontsize = 10)

plt.show()

plt.rcParams['figure.figsize'] = (18, 7)

plt.subplot(2, 2, 1)
sns.countplot(AutoMpg_data['num_wows'], palette = 'pastel')
plt.title('num_wows', fontsize = 10,color='red')
plt.xlabel('num_wows', fontsize = 10)
plt.ylabel('count', fontsize = 10)

# checking the Distribution of customers on Weekend
plt.subplot(2, 2, 2)
sns.countplot(AutoMpg_data['num_hahas'], palette = 'inferno')
plt.title('num_hahas', fontsize = 10,color='red')
plt.xlabel('num_hahas', fontsize = 10)
plt.ylabel('count', fontsize = 10)
AutoMpg_data['status_type'] = AutoMpg_data['status_type'].map({ 'photo':0, 'video':1,'status':2,'link':3})
plt.show()

# AutoMpg_data.drop(labels=["num_likes", "num_shares"], axis = 1, inplace = True)
print(len(AutoMpg_data.columns))
AutoMpg_data = AutoMpg_data.drop(AutoMpg_data.columns[8], axis=1)
print (AutoMpg_data.info())
# print(AutoMpg_data[0].describe())

df = pd.DataFrame(np.random.randn(100, 2))
pca = sklearnPCA(n_components=2)
AutoMpg_data = pd.DataFrame(pca.fit_transform(AutoMpg_data))
plt.scatter(AutoMpg_data[0], AutoMpg_data[1])
plt.show()
Sum_of_squared_distances = []
K = range(1,15)
mms = MinMaxScaler()
mms.fit(AutoMpg_data)
data_transformed = mms.transform(AutoMpg_data)
for k in K:
    km = KMeans(n_clusters=k)
    km = km.fit(data_transformed)
    Sum_of_squared_distances.append(km.inertia_)
plt.plot(K, Sum_of_squared_distances, 'bx-')
plt.xlabel('k')
plt.ylabel('Sum_of_squared_distances')
plt.title('Elbow Method For Optimal k')
plt.show()
N = 7
kmeans = KMeans(n_clusters=N, random_state=1).fit(AutoMpg_data)
highrachial = AgglomerativeClustering(n_clusters=N).fit(AutoMpg_data)
db=DBSCAN(eps=84,min_samples=1).fit(AutoMpg_data)
inertia = kmeans.inertia_
print("inertia kmeans:",inertia)

neigh = NearestNeighbors(n_neighbors=2)
nbrs = neigh.fit(AutoMpg_data)
distances, indices = nbrs.kneighbors(AutoMpg_data)
distances = np.sort(distances, axis=0)
distances = distances[:,1]
plt.plot(distances)
plt.show()

plt.figure(1)
plt.scatter(AutoMpg_data[0], AutoMpg_data[1], c=kmeans.labels_, cmap='viridis' , )
plt.suptitle("KMeans")
plt.show()
plt.figure(2)
plt.suptitle("Highrachial")
plt.scatter(AutoMpg_data[0], AutoMpg_data[1], c=highrachial.labels_, cmap='viridis')
plt.show()
plt.figure(3)
plt.suptitle("DBScan")
plt.scatter(AutoMpg_data[0], AutoMpg_data[1], c=db.labels_, cmap='viridis')
plt.show()


import pytest

from .utils import Page

# -- Tests ---------------------------------------------------------------------

@pytest.mark.parametrize('dsn', [
    "ssh://127.0.0.1:21",
    "mailto:example@example.org",
])
def test_default_dsn_with_issues(runner, dsn):
    """ Passing unsupported DSN string. """
    result = runner([dsn])

    assert result['code'] == 2

    assert "Error: URL {} is not valid".format(dsn) in result['output']

def test_default_url_no_scheme_issue(server, runner):
    """ no domain cli execution test """

    address = server.router({'^/$': Page("").exists()})

    scheme, address = address.split("//")
    args = [address, '-r1', '-s', 'failed', '--no-progress', '--fiff']
    result = runner(args)

    assert result['code'] == 0
    assert "{}//{}".format(scheme, address) in result['output']

def test_help(runner):
    result = runner(['--help'])

    from deadlinks.exporters import Default

    section, _ = Default.options()
    assert section in result['output']


"""
	@author: Akshay Nevrekar
	@created on: 14/10/2019
"""

import argparse
import cv2
import imutils
import numpy as np

ap = argparse.ArgumentParser()
ap.add_argument("-i","--image", required=True, help="path to image")
args = vars(ap.parse_args())

image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cv2.imshow("Original Image", image)

# find the contours and grab
cnts = cv2.findContours(gray.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# create a copy of OG image and draw contours on it
clone = image.copy()
cv2.drawContours(clone, cnts, -1, (0,255,0), 2)

print(f"Found {len(cnts)} contours in image")

cv2.imshow("Contours", clone)
cv2.waitKey(0)

# reconstruct the image
clone = image.copy()
cv2.destroyAllWindows()

for (i,c) in enumerate(cnts, start=1):
	print(f"Drawing contour #{i} ")
	cv2.drawContours(clone, [c], -1, (0,255,0), 2)
	cv2.imshow("Single contour",clone)
	cv2.waitKey(0)

# re-clone the image and close all open windows
clone = image.copy()
cv2.destroyAllWindows()

# find contours in the image, but this time keep only the EXTERNAL
# contours in the image
cnts = cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cv2.drawContours(clone, cnts, -1, (0, 255, 0), 2)
print(f"Found {len(cnts)} EXTERNAL contours")

# show the output image
cv2.imshow("All Contours", clone)
cv2.waitKey(0)

clone = image.copy()
cv2.destroyAllWindows()

# loop over the contours individually
for c in cnts:
	# construct a mask by drawing only the current contour
	mask = np.zeros(gray.shape, dtype="uint8")
	cv2.drawContours(mask, [c], -1, 255, -1)

	# show the images
	cv2.imshow("Image", image)
	cv2.imshow("Mask", mask)
	cv2.imshow("Image + Mask", cv2.bitwise_and(image, image, mask=mask))
	cv2.waitKey(0)


import time
import threading
import logging
import struct

from events.events import *

class JoystickEventProducer(object):

    started = False
    file = None
    index = 0

    def __init__(self, file, index):
        self.file = file
        self.index = index

    def _loop(self):

        js = open(self.file, 'rb')

        while self.started:
            evbuf = js.read(8)
            if evbuf:
                time, value, type, number = struct.unpack('IhBB', evbuf)
                if not (type & 0x80) and (type & 0x01):
                    if value == 1:
                        e = Event('joystick_button_pressed', {'joystick_num': self.index, 'button_num': number})
                        notify_event_receivers(e)

    def start(self):
        self.started = True
        t = threading.Thread(target=self._loop)
        t.daemon = True
        t.start()

    def stop(self):
        self.started = False

class JoystickService(object):

    started = False

    event_producers = [JoystickEventProducer('/dev/input/js0', 0), JoystickEventProducer('/dev/input/js1', 1)]

    def __init__(self):
        pass

    def _loop(self):

        for producer in self.event_producers:
            producer.start()

    def start(self):
        logging.info('Starting Joystick service...')
        self.started = True
        t = threading.Thread(target=self._loop)
        t.daemon = True
        t.start()

    def stop(self):
        for producer in self.event_producers:
            producer.stop()
        self.started = False


from Analisadores.AnalisadorLexico.Analisador_Lexico import *
from Analisadores.AnalisadorSintatico.Analisador_Sintatico import *
from Analisadores.AnalisadorLexico.dfageneratormaster.main import *

import argparse, textwrap, os

def readArgs() :
    helpEpilog = ""
    parser = argparse.ArgumentParser(description="Compiladores 2020/2", add_help=True)
    parser.add_argument("-i","--input",help="input txt file", required=True, type=str, dest="input")
    parser.add_argument("-o","--output",help="output folder", default="output", type=str, dest="output")
    return parser.parse_args()

def compilador() :
    main()

    lexico = Analisador_Lexico()
    sintatico = Analisador_Sintatico()

    args = readArgs()

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

    arquivo = open(args.input,'r')
    entrada = arquivo.read()
    try:
        lexico.read(entrada.strip())
        lexico.write()
        sintatico.read()
        sintatico.write()

        print("Compilation Sucesseful")
    except ValueError as err:
        print("ValueError:", err)
    except SyntaxError as err:
        print("SyntaxError:", err)

if __name__=="__main__" :
    compilador()


#!/usr/bin/env python
from __future__ import print_function, absolute_import
import os
import sys
import subprocess
import numpy as np
import astropy.io.fits as fits
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from desc.twinkles import PostageStampMaker, render_fits_image, \
    convert_image_to_hdu
from desc.twinkles.Display import image_norm
from desc.twinkles.db_table_access import LsstDatabaseTable

try:
    objectId = int(sys.argv[1])
    tempdir = sys.argv[2]
except:
    print("usage: %s <objectId> <tempdir>" % sys.argv[0])
    sys.exit(0)

def output_dir(filename):
    return os.path.join(tempdir, filename)

level2_repo = '/nfs/farm/g/desc/u1/users/jchiang/desc_projects/twinkles/Run1.1/output'

band = 'u'
size = 10.
scaling_factor = 50.

db_info = dict(db='jc_desc', read_default_file='~/.my.cnf')
jc_desc = LsstDatabaseTable(**db_info)

# Find all of the visits for the specified band.
visits = jc_desc.apply('''select visitId from CcdVisit
                          where filterName='%(band)s'
                          order by visitId''' % locals(),
                       lambda curs : [x[0] for x in curs])

# Find the coordinates of the object.
ra, dec = jc_desc.apply('''select psRA, psDecl from Object
                           where objectId=%(objectId)i''' % locals(),
                        lambda curs : tuple([x for x in curs][0]))

# Create the coadd postage stamp to get the normalization for the
# individual stamp images.
coadd = PostageStampMaker(os.path.join(level2_repo, 'deepCoadd', band,
                                       '0/0,0.fits'))
stamp = coadd.create(ra, dec, size)
hdu = convert_image_to_hdu(stamp)
norm = image_norm(hdu.data*scaling_factor)

fig, axes, norm = render_fits_image(hdu)
plt.savefig('coadd_%(objectId)i.png' % locals())
plt.close(fig)

# Generate the png files for each visit.
for visit in visits:
    print("working on", visit)
    sys.stdout.flush()
    maker = PostageStampMaker(os.path.join(level2_repo, 'deepCoadd', band,
                                           '0/0,0tempExp',
                                           'v%i-fu.fits' % visit))
    stamp = maker.create(ra, dec, size)
    hdu = convert_image_to_hdu(stamp)
    title = 'objectId: %(objectId)i; visit: %(visit)7i' % locals()
    fig, axes, norm = render_fits_image(hdu, title=title, norm=norm)
    plt.savefig(output_dir('stamp_%07i.png' % visit))
    plt.close(fig)

# Create the gif movie.
command = 'convert -delay 20 -loop 0 %(tempdir)s/stamp*.png objectId_%(objectId)i.gif' % locals()
print(command)
subprocess.call(command, shell=True)


import numpy as np
from os import path
import pytest

import autofit as af

import autolens as al

from autolens.imaging.model.result import ResultImaging

from autolens import exc

directory = path.dirname(path.realpath(__file__))

def test__make_result__result_imaging_is_returned(masked_imaging_7x7):

    model = af.Collection(galaxies=af.Collection(galaxy_0=al.Galaxy(redshift=0.5)))

    instance = model.instance_from_prior_medians()

    samples = al.m.MockSamples(max_log_likelihood_instance=instance)

    search = al.m.MockSearch(name="test_search", samples=samples)

    analysis = al.AnalysisImaging(dataset=masked_imaging_7x7)

    def modify_after_fit(
        paths: af.DirectoryPaths, model: af.AbstractPriorModel, result: af.Result
    ):
        pass

    analysis.modify_after_fit = modify_after_fit

    result = search.fit(model=model, analysis=analysis)

    assert isinstance(result, ResultImaging)

def test__figure_of_merit__matches_correct_fit_given_galaxy_profiles(
    masked_imaging_7x7
):
    lens = al.Galaxy(redshift=0.5, light=al.lp.Sersic(intensity=0.1))

    model = af.Collection(galaxies=af.Collection(lens=lens))

    analysis = al.AnalysisImaging(dataset=masked_imaging_7x7)
    instance = model.instance_from_unit_vector([])
    analysis_log_likelihood = analysis.log_likelihood_function(instance=instance)

    tracer = analysis.tracer_via_instance_from(instance=instance)

    fit = al.FitImaging(dataset=masked_imaging_7x7, tracer=tracer)

    assert fit.log_likelihood == analysis_log_likelihood

def test__figure_of_merit__includes_hyper_image_and_noise__matches_fit(
    masked_imaging_7x7
):

    hyper_image_sky = al.hyper_data.HyperImageSky(sky_scale=1.0)
    hyper_background_noise = al.hyper_data.HyperBackgroundNoise(noise_scale=1.0)

    lens = al.Galaxy(redshift=0.5, light=al.lp.Sersic(intensity=0.1))

    model = af.Collection(
        hyper_image_sky=hyper_image_sky,
        hyper_background_noise=hyper_background_noise,
        galaxies=af.Collection(lens=lens),
    )

    analysis = al.AnalysisImaging(dataset=masked_imaging_7x7)
    instance = model.instance_from_unit_vector([])
    analysis_log_likelihood = analysis.log_likelihood_function(instance=instance)

    tracer = analysis.tracer_via_instance_from(instance=instance)
    fit = al.FitImaging(
        dataset=masked_imaging_7x7,
        tracer=tracer,
        hyper_image_sky=hyper_image_sky,
        hyper_background_noise=hyper_background_noise,
    )

    assert fit.log_likelihood == analysis_log_likelihood

def test__positions__resample__raises_exception(masked_imaging_7x7):

    model = af.Collection(
        galaxies=af.Collection(
            lens=al.Galaxy(redshift=0.5, mass=al.mp.IsothermalSph()),
            source=al.Galaxy(redshift=1.0),
        )
    )

    positions_likelihood = al.PositionsLHResample(
        positions=al.Grid2DIrregular([(1.0, 100.0), (200.0, 2.0)]), threshold=0.01
    )

    analysis = al.AnalysisImaging(
        dataset=masked_imaging_7x7, positions_likelihood=positions_likelihood
    )

    instance = model.instance_from_unit_vector([])

    with pytest.raises(exc.RayTracingException):
        analysis.log_likelihood_function(instance=instance)

def test__positions__likelihood_overwrites__changes_likelihood(masked_imaging_7x7):

    lens = al.Galaxy(redshift=0.5, mass=al.mp.IsothermalSph())
    source = al.Galaxy(redshift=1.0, light=al.lp.SersicSph())

    model = af.Collection(galaxies=af.Collection(lens=lens, source=source))

    instance = model.instance_from_unit_vector([])

    analysis = al.AnalysisImaging(dataset=masked_imaging_7x7)
    analysis_log_likelihood = analysis.log_likelihood_function(instance=instance)

    tracer = analysis.tracer_via_instance_from(instance=instance)

    fit = al.FitImaging(dataset=masked_imaging_7x7, tracer=tracer)

    assert fit.log_likelihood == pytest.approx(analysis_log_likelihood, 1.0e-4)
    assert analysis_log_likelihood == pytest.approx(-6258.043397009, 1.0e-4)

    positions_likelihood = al.PositionsLHPenalty(
        positions=al.Grid2DIrregular([(1.0, 100.0), (200.0, 2.0)]), threshold=0.01
    )

    analysis = al.AnalysisImaging(
        dataset=masked_imaging_7x7, positions_likelihood=positions_likelihood
    )
    analysis_log_likelihood = analysis.log_likelihood_function(instance=instance)

    log_likelihood_penalty_base = positions_likelihood.log_likelihood_penalty_base_from(
        dataset=masked_imaging_7x7
    )
    log_likelihood_penalty = positions_likelihood.log_likelihood_penalty_from(
        tracer=tracer
    )

    assert analysis_log_likelihood == pytest.approx(
        log_likelihood_penalty_base - log_likelihood_penalty, 1.0e-4
    )
    assert analysis_log_likelihood == pytest.approx(-22048700558.9052, 1.0e-4)

def test__uses_hyper_fit_correctly(masked_imaging_7x7):

    galaxies = af.ModelInstance()
    galaxies.lens = al.Galaxy(
        redshift=0.5, light=al.lp.Sersic(intensity=1.0), mass=al.mp.IsothermalSph
    )
    galaxies.source = al.Galaxy(redshift=1.0, light=al.lp.Sersic())

    instance = af.ModelInstance()
    instance.galaxies = galaxies

    lens_hyper_image = al.Array2D.ones(shape_native=(3, 3), pixel_scales=0.1)
    lens_hyper_image[4] = 10.0
    hyper_model_image = al.Array2D.full(
        fill_value=0.5, shape_native=(3, 3), pixel_scales=0.1
    )

    hyper_galaxy_image_path_dict = {("galaxies", "lens"): lens_hyper_image}

    result = al.m.MockResult(
        hyper_galaxy_image_path_dict=hyper_galaxy_image_path_dict,
        hyper_model_image=hyper_model_image,
    )

    analysis = al.AnalysisImaging(
        dataset=masked_imaging_7x7, hyper_dataset_result=result
    )

    hyper_galaxy = al.HyperGalaxy(
        contribution_factor=1.0, noise_factor=1.0, noise_power=1.0
    )

    instance.galaxies.lens.hyper_galaxy = hyper_galaxy

    analysis_log_likelihood = analysis.log_likelihood_function(instance=instance)

    g0 = al.Galaxy(
        redshift=0.5,
        light_profile=instance.galaxies.lens.light,
        mass_profile=instance.galaxies.lens.mass,
        hyper_galaxy=hyper_galaxy,
        hyper_model_image=hyper_model_image,
        hyper_galaxy_image=lens_hyper_image,
        hyper_minimum_value=0.0,
    )
    g1 = al.Galaxy(redshift=1.0, light_profile=instance.galaxies.source.light)

    tracer = al.Tracer.from_galaxies(galaxies=[g0, g1])

    fit = al.FitImaging(dataset=masked_imaging_7x7, tracer=tracer)

    assert (fit.tracer.galaxies[0].hyper_galaxy_image == lens_hyper_image).all()
    assert analysis_log_likelihood == fit.log_likelihood

def test__sets_up_hyper_galaxy_images__froms(masked_imaging_7x7):

    hyper_galaxy_image_path_dict = {
        ("galaxies", "lens"): al.Array2D.ones(shape_native=(3, 3), pixel_scales=1.0),
        ("galaxies", "source"): al.Array2D.full(
            fill_value=2.0, shape_native=(3, 3), pixel_scales=1.0
        ),
    }

    result = al.m.MockResult(
        hyper_galaxy_image_path_dict=hyper_galaxy_image_path_dict,
        hyper_model_image=al.Array2D.full(
            fill_value=3.0, shape_native=(3, 3), pixel_scales=1.0
        ),
    )

    analysis = al.AnalysisImaging(
        dataset=masked_imaging_7x7, hyper_dataset_result=result
    )

    assert (
        analysis.hyper_galaxy_image_path_dict[("galaxies", "lens")].native
        == np.ones((3, 3))
    ).all()

    assert (
        analysis.hyper_galaxy_image_path_dict[("galaxies", "source")].native
        == 2.0 * np.ones((3, 3))
    ).all()

    assert (analysis.hyper_model_image.native == 3.0 * np.ones((3, 3))).all()

def test__stochastic_log_likelihoods_for_instance(masked_imaging_7x7):

    lens_hyper_image = al.Array2D.ones(shape_native=(3, 3), pixel_scales=0.1)
    lens_hyper_image[4] = 10.0
    source_hyper_image = al.Array2D.ones(shape_native=(3, 3), pixel_scales=0.1)
    source_hyper_image[4] = 10.0
    hyper_model_image = al.Array2D.full(
        fill_value=0.5, shape_native=(3, 3), pixel_scales=0.1
    )

    hyper_galaxy_image_path_dict = {
        ("galaxies", "lens"): lens_hyper_image,
        ("galaxies", "source"): source_hyper_image,
    }

    result = al.m.MockResult(
        hyper_galaxy_image_path_dict=hyper_galaxy_image_path_dict,
        hyper_model_image=hyper_model_image,
    )

    pixelization = al.Pixelization(mesh=al.mesh.VoronoiMagnification(shape=(3, 3)))

    galaxies = af.ModelInstance()
    galaxies.lens = al.Galaxy(
        redshift=0.5, mass=al.mp.IsothermalSph(einstein_radius=1.0)
    )
    galaxies.source = al.Galaxy(redshift=1.0, pixelization=pixelization)

    instance = af.ModelInstance()
    instance.galaxies = galaxies

    analysis = al.AnalysisImaging(
        dataset=masked_imaging_7x7,
        hyper_dataset_result=result,
        settings_lens=al.SettingsLens(stochastic_samples=10),
    )

    stochastic_log_likelihoods = analysis.stochastic_log_likelihoods_via_instance_from(
        instance=instance
    )

    assert stochastic_log_likelihoods is None

    pixelization = al.Pixelization(mesh=al.mesh.VoronoiBrightnessImage(pixels=7))

    galaxies.source = al.Galaxy(redshift=1.0, pixelization=pixelization)

    instance = af.ModelInstance()
    instance.galaxies = galaxies

    stochastic_log_likelihoods = analysis.stochastic_log_likelihoods_via_instance_from(
        instance=instance
    )

    assert sum(stochastic_log_likelihoods[0:5]) != pytest.approx(
        sum(stochastic_log_likelihoods[5:10], 1.0e-4)
    )

    pixelization = al.Pixelization(mesh=al.mesh.DelaunayBrightnessImage(pixels=5))

    galaxies.source = al.Galaxy(redshift=1.0, pixelization=pixelization)

    instance = af.ModelInstance()
    instance.galaxies = galaxies

    stochastic_log_likelihoods = analysis.stochastic_log_likelihoods_via_instance_from(
        instance=instance
    )

    assert sum(stochastic_log_likelihoods[0:5]) != pytest.approx(
        sum(stochastic_log_likelihoods[5:10], 1.0e-4)
    )

def test__profile_log_likelihood_function(masked_imaging_7x7):

    pixelization = al.Pixelization(
        mesh=al.mesh.Rectangular(shape=(3, 3)),
        regularization=al.reg.Constant(coefficient=1.0),
    )

    lens = al.Galaxy(redshift=0.5, light=al.lp.Sersic(intensity=0.1))
    source = al.Galaxy(redshift=1.0, pixelization=pixelization)

    model = af.Collection(galaxies=af.Collection(lens=lens, source=source))

    instance = model.instance_from_unit_vector([])

    analysis = al.AnalysisImaging(dataset=masked_imaging_7x7)

    profiling_dict = analysis.profile_log_likelihood_function(instance=instance)

    assert "regularization_term_0" in profiling_dict
    assert "log_det_regularization_matrix_term_0" in profiling_dict


#!/usr/bin/env python

import numpy as np
import pandas as pd
import pandas.testing as pdt
import pytest

from recordlinkage.preprocessing import clean
from recordlinkage.preprocessing import phonenumbers
from recordlinkage.preprocessing import phonetic
from recordlinkage.preprocessing import phonetic_algorithms
from recordlinkage.preprocessing import value_occurence

class TestCleaningStandardise:
    def test_clean(self):
        values = pd.Series(
            [
                "Mary-ann",
                "Bob :)",
                "Angel",
                "Bob (alias Billy)",
                "Mary ann",
                "John",
                np.nan,
            ]
        )

        expected = pd.Series(
            ["mary ann", "bob", "angel", "bob", "mary ann", "john", np.nan]
        )

        clean_series = clean(values)

        # Check if series are identical.
        pdt.assert_series_equal(clean_series, expected)

        clean_series_nothing = clean(
            values,
            lowercase=False,
            replace_by_none=False,
            replace_by_whitespace=False,
            strip_accents=False,
            remove_brackets=False,
        )

        # Check if ntohing happend.
        pdt.assert_series_equal(clean_series_nothing, values)

    def test_clean_empty(self):
        """Test the cleaning of an empty Series"""

        # Check empty series
        pdt.assert_series_equal(clean(pd.Series(dtype=object)), pd.Series(dtype=object))

    def test_clean_unicode(self):
        values = pd.Series(
            [
                "Mary-ann",
                "Bob :)",
                "Angel",
                "Bob (alias Billy)",
                "Mary  ann",
                "John",
                np.nan,
            ]
        )

        expected = pd.Series(
            ["mary ann", "bob", "angel", "bob", "mary ann", "john", np.nan]
        )

        clean_series = clean(values)

        # Check if series are identical.
        pdt.assert_series_equal(clean_series, expected)

    def test_clean_parameters(self):
        values = pd.Series(
            [
                "Mary-ann",
                "Bob :)",
                "Angel",
                "Bob (alias Billy)",
                "Mary  ann",
                "John",
                np.nan,
            ]
        )

        expected = pd.Series(
            ["mary ann", "bob", "angel", "bob", "mary ann", "john", np.nan]
        )

        clean_series = clean(
            values,
            lowercase=True,
            replace_by_none=r"[^ \-\_A-Za-z0-9]+",
            replace_by_whitespace=r"[\-\_]",
            remove_brackets=True,
        )

        # Check if series are identical.
        pdt.assert_series_equal(clean_series, expected)

    def test_clean_lower(self):
        values = pd.Series([np.nan, "LowerHigher", "HIGHERLOWER"])
        expected = pd.Series([np.nan, "lowerhigher", "higherlower"])

        clean_series = clean(values, lowercase=True)

        # Check if series are identical.
        pdt.assert_series_equal(clean_series, expected)

    def test_clean_brackets(self):
        values = pd.Series([np.nan, "bra(cke)ts", "brackets with (brackets)"])
        expected = pd.Series([np.nan, "brats", "brackets with"])

        clean_series = clean(values, remove_brackets=True)

        # Check if series are identical.
        pdt.assert_series_equal(clean_series, expected)

    def test_clean_accent_stripping(self):
        values = pd.Series(["ősdfésdfë", "without"])
        expected = pd.Series(["osdfesdfe", "without"])

        values_unicode = pd.Series(["ősdfésdfë", "without"])
        expected_unicode = pd.Series(["osdfesdfe", "without"])

        # values_callable = pd.Series([u'ősdfésdfë', u'without'])
        # expected_callable = pd.Series([u'ősdfésdfë', u'without'])

        # # Callable.
        # pdt.assert_series_equal(
        #     clean(values_callable, strip_accents=lambda x: x),
        #     expected_callable)

        # Check if series are identical.
        pdt.assert_series_equal(clean(values, strip_accents="unicode"), expected)

        # Check if series are identical.
        pdt.assert_series_equal(clean(values, strip_accents="ascii"), expected)

        # Check if series are identical.
        pdt.assert_series_equal(
            clean(values_unicode, strip_accents="unicode"), expected_unicode
        )

        # Check if series are identical.
        pdt.assert_series_equal(
            clean(values_unicode, strip_accents="ascii"), expected_unicode
        )

        with pytest.raises(ValueError):
            clean(values, strip_accents="unknown_algorithm")

    def test_clean_phonenumbers(self):
        values = pd.Series(
            [np.nan, "0033612345678", "+1 201 123 4567", "+336-123 45678"]
        )
        expected = pd.Series([np.nan, "0033612345678", "+12011234567", "+33612345678"])

        clean_series = phonenumbers(values)

        # Check if series are identical.
        pdt.assert_series_equal(clean_series, expected)

    def test_value_occurence(self):
        values = pd.Series(
            [
                np.nan,
                np.nan,
                "str1",
                "str1",
                "str1",
                "str1",
                "str2",
                "str3",
                "str3",
                "str1",
            ]
        )
        expected = pd.Series([2, 2, 5, 5, 5, 5, 1, 2, 2, 5])

        pdt.assert_series_equal(value_occurence(values), expected)

class TestEncodingStandardise:
    def test_encode_soundex(self):
        values = pd.Series(
            [
                np.nan,
                "John",
                "Mary Ann",
                "billy",
                "Jonathan",
                "Gretha",
                "Micheal",
                "Sjors",
            ]
        )
        expected = pd.Series(
            [np.nan, "J500", "M650", "B400", "J535", "G630", "M240", "S620"]
        )

        phon = phonetic(values, "soundex")

        pdt.assert_series_equal(phon, expected)

    def test_encode_nysiis(self):
        values = pd.Series(
            [
                np.nan,
                "John",
                "Mary Ann",
                "billy",
                "Jonathan",
                "Gretha",
                "Micheal",
                "Sjors",
            ]
        )
        expected = pd.Series(
            [np.nan, "JAN", "MARYAN", "BALY", "JANATAN", "GRAT", "MACAL", "SJAR"]
        )

        phon = phonetic(values, "nysiis")

        pdt.assert_series_equal(phon, expected)

    def test_encode_metaphone(self):
        values = pd.Series(
            [
                np.nan,
                "John",
                "Mary Ann",
                "billy",
                "Jonathan",
                "Gretha",
                "Micheal",
                "Sjors",
            ]
        )
        expected = pd.Series([np.nan, "JN", "MRYN", "BL", "JN0N", "KR0", "MXL", "SJRS"])

        phon = phonetic(values, method="metaphone")

        pdt.assert_series_equal(phon, expected)

    def test_encode_match_rating(self):
        values = pd.Series(
            [
                np.nan,
                "John",
                "Mary Ann",
                "billy",
                "Jonathan",
                "Gretha",
                "Micheal",
                "Sjors",
            ]
        )
        # in jellyfish.match_rating_codex version 0.8.0 results have changed
        expected = pd.Series(
            [np.nan, "JHN", "MRYN", "BLY", "JNTHN", "GRTH", "MCHL", "SJRS"]
        )

        phon = phonetic(values, method="match_rating")

        pdt.assert_series_equal(phon, expected)

    def test_phonetic_does_not_exist(self):
        values = pd.Series(
            [
                np.nan,
                "John",
                "Mary Ann",
                "billy",
                "Jonathan",
                "Gretha",
                "Micheal",
                "Sjors",
            ]
        )

        with pytest.raises(ValueError):
            phonetic(values, "unknown_algorithm")

    def test_list_of_algorithms(self):
        algorithms = phonetic_algorithms

        assert isinstance(algorithms, list)

        assert "soundex" in algorithms
        assert "nysiis" in algorithms
        assert "metaphone" in algorithms
        assert "match_rating" in algorithms


import re
import subprocess
from types import ModuleType

import reusables
import wx
from wx.adv import TaskBarIcon
import logging
import argparse

class AudioController:
    def __init__(self):
        # Recover configs
        config = reusables.config_dict("config.ini")
        self.name_device_a = config["device_a"]["name"]
        self.name_device_b = config["device_b"]["name"]
        self.icon_device_a = config["device_a"]["icon"]
        self.icon_device_b = config["device_b"]["icon"]

    @staticmethod
    def _force_portaudio_reload(sounddevice: ModuleType) -> None:
        """Cause the PortAudio library inside the given sounddevice module to be reloaded.

        Without doing this the default device is not refreshed after changing it."""
        sounddevice._ffi.dlclose(sounddevice._lib)
        sounddevice._lib = sounddevice._ffi.dlopen(sounddevice._libname)
        sounddevice._lib.Pa_Initialize()

    def get_default_device_name(self) -> str:
        import sounddevice

        # force sounddevice to reload the default device from the PortAudio dll
        # noinspection PyTypeChecker
        self._force_portaudio_reload(sounddevice)
        # now get the raw name of the device
        idd = sounddevice.default.device[1]
        raw_name = sounddevice.query_devices(idd)["name"]
        # extract the name and return it
        matches = re.finditer(r".*(?= \()", raw_name, re.MULTILINE)
        return next(matches).group()

    def set_default_device(self, device_name: str) -> None:
        subprocess.run(
            ["nircmd.exe", "setdefaultsounddevice", "{}".format(device_name)]
        )

    def toggle_between_devices(self) -> None:
        default_device_name = self.get_default_device_name()
        if default_device_name == self.name_device_a:
            self.set_default_device(self.name_device_b)
        else:
            self.set_default_device(self.name_device_a)

    def open_sound_panel(self, event):
        subprocess.run(["control", "mmsys.cpl", "sounds"])

def create_menu_item(menu, label, func):
    item = wx.MenuItem(menu, -1, label)
    menu.Bind(wx.EVT_MENU, func, id=item.GetId())
    menu.Append(item)
    return item

class MyTaskBarIcon(TaskBarIcon):
    def __init__(self, frame):
        self.AC = AudioController()
        self.frame = frame
        super(TaskBarIcon, self).__init__()
        self.set_icon()
        self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)

    def CreatePopupMenu(self):
        menu = wx.Menu()
        create_menu_item(menu, "Open Sound Panel", self.AC.open_sound_panel)
        menu.AppendSeparator()
        create_menu_item(menu, "Exit", self.on_exit)
        return menu

    def set_icon(self):
        default_device_name = self.AC.get_default_device_name()
        logging.debug(f"Current default device name: {default_device_name}")
        if default_device_name == self.AC.name_device_a:
            path = self.AC.icon_device_a
            tooltip = self.AC.name_device_a
        else:
            path = self.AC.icon_device_b
            tooltip = self.AC.name_device_b
        logging.debug(f"Setting icon to: {path}")
        icon = wx.Icon(wx.Bitmap(path))
        self.SetIcon(icon, tooltip)
        logging.debug(f"Icon set")

    def on_left_down(self, event):
        self.AC.toggle_between_devices()
        # Wait a bit to make sure nircmd finish toggling the sound device before updating the icon
        wx.CallLater(int(500), self.set_icon)

    def on_exit(self, event):
        wx.CallAfter(self.Destroy)
        self.frame.Close()

class App(wx.App):
    def OnInit(self):
        frame = wx.Frame(None)
        self.SetTopWindow(frame)
        MyTaskBarIcon(frame)
        return True

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
                        prog = 'ToggleAudioTrayIcon',
                        description = 'A tray icon to quickly toggle default audio device.')
    parser.add_argument('-d', '--debug', action='store_true', help="print debug message to a log file")
    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(
            filename="ToggleAudioTrayIcon_debug_logs.txt",
            filemode="a",
            format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
            datefmt="%H:%M:%S",
            level=logging.DEBUG,
        )
        logging.debug("START")

    app = App(False)
    app.MainLoop()


import concurrent.futures
import pandas as pd
import xlrd
import os
import re
import sqlalchemy as sa
from itertools import repeat
from sqlalchemy import create_engine, inspect, text
from sqlalchemy import types
from sqlalchemy import exc

SERVER = 'zam-SPC-rey-db'
DATABASE = 'SPC-Rey'
conn_string = f'mssql+pyodbc://@{SERVER}/{DATABASE}?trusted_connection=yes&driver=ODBC+Driver+17+for+SQL+Server'
sql_engine = create_engine(conn_string, fast_executemany=True)
sql_inspector = inspect(sql_engine)

pd.options.display.max_columns = None

DIRNAME = 'C:/Users/Z0205784/Downloads/'
EXT = 'xls'
COLUMNS_PRUEBAS = ["test", "serial_number", "evaluation", "sample_value", "test_result", "made_by", "equipment",
                   'sample_plan', 'plan_result', 'plan_date', 'plan_hour', "lat_ticket"]
COLUMNS_TICKETS = ["lat_ticket", "lote", "line", "shift", "state", "ticket_result", "comments", "ticket_date",
                   "ticket_hour", "TRWNumber", "PartNumber", "LessFinish", "model", "serial_number"]

pruebas_dtypes = {
    "test": types.VARCHAR(),
    "serial_number": types.VARCHAR(length=50),
    "evaluation": types.VARCHAR(length=50),
    "sample_value": types.FLOAT,
    "test_result": types.VARCHAR(length=20),
    "made_by": types.BIGINT(),
    "equipment": types.VARCHAR(length=50),
    'sample_plan': types.VARCHAR(length=100),
    'plan_result': types.VARCHAR(length=20),
    'plan_date': types.DATE,
    'plan_hour': types.TIME,
    "lat_ticket": types.VARCHAR(length=50),
    'usl': types.FLOAT(),
    'lsl': types.FLOAT()
}

ticket_dtypes = {
    "lat_ticket": types.VARCHAR(length=50),
    "lote": types.BIGINT(),
    "line": types.VARCHAR(length=50),
    "shift": types.SMALLINT(),
    "state": types.VARCHAR(length=50),
    "ticket_result": types.VARCHAR(length=20),
    "comments": types.VARCHAR(),
    "ticket_date": types.DATE(),
    "ticket_hour": types.TIME(),
    "TRWNumber": types.VARCHAR(length=50),
    "PartNumber": types.NVARCHAR(length=50),
    "LessFinish": types.VARCHAR(length=50),
    "model": types.VARCHAR(length=50),
    "serial_number": types.VARCHAR(length=50)
}

COL_ID_PRUEBAS = [3, 7, 9, 12, 15, 17, 20]  # [D, H, J, M, P, R, U]
LAT_LIST = [file for file in os.listdir(DIRNAME) if file.endswith(EXT)]
planes_df = pd.DataFrame()
pruebas_df = pd.DataFrame()
tickets_df = pd.DataFrame()

# Todo. Refactor this bitch
def extract_ticket_info(file_path, worksheet) -> pd.DataFrame:
    row_indices = [7, 8, 9, 10, 11, 12, 16]
    col_index = 4
    ticket_info_keys = [
        "Ticket",
        "Lote",
        "Linea",
        "Turno",
        "Estado",
        "Resultado",
        "Comentarios"
    ]

    ticket_info = {key: [worksheet.cell(row, col_index).value] for row, key in zip(row_indices, ticket_info_keys)}

    col_index = 10
    row_indices = [7, 8, 9, 10, 11, 12, 15]
    ticket_info_keys = ["Fecha de Creacion", "Hora de Creacion", "Numero de TRW", "Numero de Parte", "LessFinish",
                        "Modelo", "Numero de Serie"]

    ticket_info.update({key: [worksheet.cell(row, col_index).value] for row, key in zip(row_indices, ticket_info_keys)})
    ticket_info = pd.DataFrame().from_dict(ticket_info)
    # FIXME ...
    ticket_info['Numero de Serie'] = ""

    return ticket_info

# TODO. Refactor this bitch
def read_excel_file(file_name: str) -> list:
    ticket_info_df = pd.DataFrame(columns=COLUMNS_TICKETS)
    file_path = f"{DIRNAME}{file_name}"
    workbook = xlrd.open_workbook(file_path, logfile=open(os.devnull, 'w'))
    worksheet = workbook.sheet_by_index(0)

    ticket_info_df = extract_ticket_info(file_path, worksheet)

    # Gets a list of each row that contains "Plan de pruebas" as cell value.
    plan_rows = [i for i in range(21, worksheet.nrows) if worksheet.cell_value(i, 1) == 'Plan de Pruebas']
    # Gets the last row that has a 'prueba'
    last_prueba_row = max([i for i in range(0, worksheet.nrows) if worksheet.cell_value(i, 3) != ''])

    plan_list = []
    prueba_list = []
    ticket = ticket_info_df['Ticket'][0]
    for i in range(0, len(plan_rows)):
        plan = [worksheet.cell_value(plan_rows[i] + 1, col) for col in range(1, 20) if
                worksheet.cell_value(plan_rows[i] + 1, col) != ""]
        plan.append(ticket)
        # plan.append(ticket + " " + plan[0])
        plan_list.append(plan)

        row_start = plan_rows[i] + 3
        row_end = plan_rows[i + 1] if i + 1 < len(plan_rows) else last_prueba_row + 1
        for j in range(row_start, row_end):
            prueba = [worksheet.cell_value(j, col_id) for col_id in COL_ID_PRUEBAS]
            prueba.extend(plan)
            prueba_list.append(prueba)

    temp_pruebas_df = pd.DataFrame(prueba_list, columns=COLUMNS_PRUEBAS)
    return [temp_pruebas_df, ticket_info_df]

def get_spec_limits(evaluacion):
    lsl = None
    usl = None
    expression = r'[-+]?\d*\.\d+|\d+'

    values =  re.findall(expression, evaluacion)

    if 'Entre' in evaluacion and len(values) > 1:
        lsl = values[0]
        usl = values[1]
        return [lsl, usl]

    if 'Menor' in evaluacion:
        usl = float(re.findall(expression, evaluacion)[0])
        return [lsl, usl]

    if 'Mayor' in evaluacion:
        lsl = float(re.findall(expression, evaluacion)[0])
        return [lsl, usl]

    if 'Igual' in evaluacion:
        return [lsl, usl]

    return [lsl, usl]

count = 0
if __name__ == '__main__':
    pruebas_df = pd.DataFrame()
    planes_df = pd.DataFrame()
    tickets_df = pd.DataFrame()

    with concurrent.futures.ProcessPoolExecutor() as executor:
        results = executor.map(read_excel_file, LAT_LIST)
        for result in results:
            count += 1
            print(count)
            pruebas_df = pd.concat([pruebas_df, result[0]], ignore_index=True)
            tickets_df = pd.concat([tickets_df, result[1]], ignore_index=True)

    # * Cleaning lat_pruebas
    pruebas_df['sample_value'] = pruebas_df['sample_value'].astype(str).str.extract(r'(\d+\.\d+|\d+)').astype(float)
    USL = []
    LSL = []
    for index, row in pruebas_df.iterrows():
        lsl, usl = get_spec_limits(pruebas_df['evaluation'].iloc[index])
        LSL.append(lsl)
        USL.append(usl)

    pruebas_df['lsl'] = LSL
    pruebas_df['usl'] = USL
    pruebas_df['lsl'] = pd.to_numeric(pruebas_df['lsl'], errors='coerce')
    pruebas_df['usl'] = pd.to_numeric(pruebas_df['usl'], errors='coerce')

    tickets_df.columns = COLUMNS_TICKETS
    pruebas_df['plan_date'] = pd.to_datetime(pruebas_df['plan_date'], errors='coerce')
    pruebas_df['plan_hour'] = pd.to_datetime(pruebas_df['plan_hour'], errors='coerce')
    tickets_df['ticket_date'] = pd.to_datetime(tickets_df['ticket_date'], errors='coerce')
    tickets_df['ticket_hour'] = pd.to_datetime(tickets_df['ticket_hour'], errors='coerce')

    print(pruebas_df.info())
    print(tickets_df.info())

    pruebas_df.dropna(subset=['sample_value'], inplace=True)
    output_path = r'C:\Repos\CSPM\LAT\Output Files'

    # Save into csv
    pruebas_df.to_csv(output_path + r'\\lat_pruebas.csv')
    tickets_df.to_csv(output_path + r'\\lat_tickets.csv')

    tickets_df.to_sql('lat_tickets', sql_engine, if_exists='append', index=False, dtype=ticket_dtypes)
    pruebas_df.to_sql('lat_samples', sql_engine, if_exists='append', index=False, dtype=pruebas_dtypes)

    print("Done")


from django.contrib import admin
from . import models
# Register your models here.

@admin.register(models.Purchase)
class PurchaseAdmin(admin.ModelAdmin):
    fieldsets = (("Custom Profile", {"fields": ("title","host", "closed")}),)

    list_display = (
       "title",
       "host",
       "closed",
    )


from ts3plugin import ts3plugin, PluginHost
from bluscream import *
from ts3enums import ContactStatus
from configparser import ConfigParser
from getvalues import getValues, ValueType
from pytsonui import setupUi
from pytson import getPluginPath, getCurrentApiVersion
from PythonQt.QtGui import QDialog, QTableWidgetItem, QComboBox, QCheckBox
from PythonQt.QtCore import Qt
from traceback import format_exc
import ts3defines, ts3lib, ts3client, time

def countChannels(schid, find:str, case_sensitive=False):
    if not case_sensitive: find = find.lower()
    (error, cids) = ts3lib.getChannelList(schid)
    ret = {}
    for cid in cids:
        (err, name) = ts3lib.getChannelVariable(schid, cid, ts3defines.ChannelProperties.CHANNEL_NAME)
        if not case_sensitive: name = name.lower()
        if find in name: ret[cid] = name
    return ret

class countContacts(ts3plugin):
    name = "Count Contacts"
    try: apiVersion = getCurrentApiVersion()
    except: apiVersion = 21
    requestAutoload = False
    version = "1"
    author = "Bluscream"
    description = "Gives you numbers"
    offersConfigure = True
    commandKeyword = "ccount"
    infoTitle = "[b]Contacts:[/b]"
    menuItems = [(ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0, name, ""),
                 (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 1, "Online Contacts", ""),
                 (ts3defines.PluginItemType.PLUGIN_CHANNEL, 0, "Send Contact Stats", ""),
                 (ts3defines.PluginItemType.PLUGIN_CLIENT, 0, "Send Contact Stats", "")]
    hotkeys = []
    count = 0
    ini = os.path.join(getPluginPath(), "scripts", "countContacts", "settings.ini")
    ui = os.path.join(getPluginPath(), "scripts", "countContacts", "filters.ui")
    cfg = ConfigParser()
    cfg.optionxform=str
    dlg = None

    def __init__(self):
        if os.path.isfile(self.ini): self.cfg.read(self.ini)
        else:
            self.cfg['filters'] = { "Male": "m/", "Female": "f/" }
            with open(self.ini, 'w') as configfile: self.cfg.write(configfile)
        if PluginHost.cfg.getboolean("general", "verbose"): ts3lib.printMessageToCurrentTab("{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded.".format(timestamp(), self.name, self.author))

    def configure(self, qParentWidget):
        if not self.dlg: self.dlg = contactStatsFilters(self)
        self.dlg.show()
        self.dlg.raise_()
        self.dlg.activateWindow()
        return QDialog.Rejected
        d = dict()
        for k in self.cfg['filters']:
            d[k] = (ValueType.string, k, self.cfg['filters'][k], None, 1)
        getValues(None, "Count Contacts Prefixes", d, self.configDialogClosed)

    def configDialogClosed(self, r, vals):
        if r == QDialog.Rejected: return
        for val in vals:
            self.cfg.set("general", val, vals[val])
        with open(self.ini, 'w') as configfile:
            self.cfg.write(configfile)

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if atype == ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL:
            if menuItemID == 0: self.printContacts()
            elif menuItemID == 1: ts3lib.printMessageToCurrentTab("{}{}".format(timestamp(), self.onlineContacts(schid, False)))
        elif atype == ts3defines.PluginItemType.PLUGIN_CHANNEL:
            ts3lib.requestSendChannelTextMsg(schid, self.contactStats(), selectedItemID)
        elif atype == ts3defines.PluginItemType.PLUGIN_CLIENT:
            ts3lib.requestSendPrivateTextMsg(schid, self.contactStats(), selectedItemID)

    def processCommand(self, schid, command):
        command = command.split(' ')
        if command[0].lower() == "chans":
            cids = countChannels(schid, command[1])
            msg = "Found [b]{}[/b] channels with \"{}\" in name: ".format(len(cids), command[1])
            for cid, name in cids.items(): msg += "{}, ".format(channelURL(schid, cid, name))
            ts3lib.printMessageToCurrentTab(msg)
        else: self.printContacts()
        return True

    def printContacts(self):
        ts3lib.printMessageToCurrentTab("{}{}".format(timestamp(), self.contactStats(True)))

    def checkFilters(self, counters, nick):
        for k in self.cfg['filters']:
            tmp = self.cfg.get('filters', k).split('|', 2)
            case = bool(int(tmp[0]));mode = tmp[1];text = tmp[2]
            if case: nick = nick.lower(); text = text.lower()
            if mode == "Prefix":
                if nick.startswith(text): counters[k] += 1
            elif mode == "Suffix":
                if nick.endswith(text): counters[k] += 1
            elif mode == "Contains":
                if text in nick: counters[k] += 1
            elif mode == "Equals":
                if text == nick: counters[k] += 1

    def onlineContacts(self, schid, neutral=list()):
        contacts = getContacts()
        lst = {}
        for contact in contacts:
            lst[contact["IDS"]] = contact["Friend"]
        del contacts
        (err, clist) = ts3lib.getClientList(schid)
        buddies = [];blocked = [];unknown = []
        for clid in clist:
            (err, uid) = ts3lib.getClientVariable(schid, clid, ts3defines.ClientProperties.CLIENT_UNIQUE_IDENTIFIER)
            if not uid in lst: continue
            if lst[uid] == ContactStatus.FRIEND: buddies.append(clientURL(schid, clid, uid))
            elif lst[uid] == ContactStatus.BLOCKED: blocked.append(clientURL(schid, clid, uid))
            elif lst[uid] == ContactStatus.NEUTRAL:
                if neutral: neutral.append(clientURL(schid, clid, uid))
            else: unknown.append(clientURL(schid, clid, uid))
        _sum = len(buddies)+len(blocked)+len(unknown)
        if neutral: _sum += len(neutral)
        msg = ["[u]My Online Contacts [/u]: [b]{}[/b]".format(_sum)]
        if len(buddies) > 0: msg.append("[b]{}[/b] [color=green]Buddies[/color]: {}".format(len(buddies), " | ".join(buddies)))
        if len(blocked) > 0: msg.append("[b]{}[/b] [color=red]Blocked[/color]: {}".format(len(blocked), " | ".join(blocked)))
        if neutral and len(neutral) > 0: msg.append("[b]{}[/b] Neutral: {}".format(len(neutral), " | ".join(neutral)))
        if len(unknown) > 0: msg.append("[b]{}[/b] [color=orange]Unknown[/color]: {}".format(len(unknown), " | ".join(unknown)))
        return "\n".join(msg)

    def contactStats(self,detailed=False):
        buddies = 0;blocked = 0;neutral = 0;unknown = 0
        counters = {};bcounters = {};blcounters = {};ncounters = {}; ucounters = {}
        for k in self.cfg['filters']:
            counters[k] = 0;bcounters[k] = 0;blcounters[k] = 0;ncounters[k] = 0;ucounters[k] = 0
        contacts = getContacts()
        if detailed:
            first = round(time.time()); last = 0
            firstc = None; lastc = None
        for contact in contacts:
            nick = contact["Nickname"].decode("utf-8")
            for k in self.cfg['filters']:
                tmp = self.cfg.get('filters', k).split('|', 2)
                case = bool(int(tmp[0]));mode = tmp[1];text = tmp[2]
                if case: nick = nick.lower(); text = text.lower()
                if mode == "Prefix":
                    if nick.startswith(text): counters[k] += 1
                elif mode == "Suffix":
                    if nick.endswith(text): counters[k] += 1
                elif mode == "Contains":
                    if text in nick: counters[k] += 1
                elif mode == "Equals":
                    if text == nick: counters[k] += 1
            status = contact["Friend"]
            if status == ContactStatus.FRIEND:
                buddies += 1
                for k in self.cfg['filters']:
                    tmp = self.cfg.get('filters', k).split('|', 2)
                    case = bool(int(tmp[0]));mode = tmp[1];text = tmp[2]
                    if case: nick = nick.lower(); text = text.lower()
                    if mode == "Prefix":
                        if nick.startswith(text): bcounters[k] += 1
                    elif mode == "Suffix":
                        if nick.endswith(text): bcounters[k] += 1
                    elif mode == "Contains":
                        if text in nick: bcounters[k] += 1
                    elif mode == "Equals":
                        if text == nick: bcounters[k] += 1
            elif status == ContactStatus.BLOCKED:
                blocked += 1
                for k in self.cfg['filters']:
                    tmp = self.cfg.get('filters', k).split('|', 2)
                    case = bool(int(tmp[0]));mode = tmp[1];text = tmp[2]
                    if case: nick = nick.lower(); text = text.lower()
                    if mode == "Prefix":
                        if nick.startswith(text): blcounters[k] += 1
                    elif mode == "Suffix":
                        if nick.endswith(text): blcounters[k] += 1
                    elif mode == "Contains":
                        if text in nick: blcounters[k] += 1
                    elif mode == "Equals":
                        if text == nick: blcounters[k] += 1
            elif status == ContactStatus.NEUTRAL:
                neutral += 1
                for k in self.cfg['filters']:
                    tmp = self.cfg.get('filters', k).split('|', 2)
                    case = bool(int(tmp[0]));mode = tmp[1];text = tmp[2]
                    if case: nick = nick.lower(); text = text.lower()
                    if mode == "Prefix":
                        if nick.startswith(text): ncounters[k] += 1
                    elif mode == "Suffix":
                        if nick.endswith(text): ncounters[k] += 1
                    elif mode == "Contains":
                        if text in nick: ncounters[k] += 1
                    elif mode == "Equals":
                        if text == nick: ncounters[k] += 1
            else:
                unknown += 1
                for k in self.cfg['filters']:
                    tmp = self.cfg.get('filters', k).split('|', 2)
                    case = bool(int(tmp[0]));mode = tmp[1];text = tmp[2]
                    if case: nick = nick.lower(); text = text.lower()
                    if mode == "Prefix":
                        if nick.startswith(text): ucounters[k] += 1
                    elif mode == "Suffix":
                        if nick.endswith(text): ucounters[k] += 1
                    elif mode == "Contains":
                        if text in nick: ucounters[k] += 1
                    elif mode == "Equals":
                        if text == nick: ucounters[k] += 1
            if "LastSeenEpoch" in contact and detailed:
                if contact["LastSeenEpoch"] < first:
                    first = contact["LastSeenEpoch"]
                    firstc = contact
                if contact["LastSeenEpoch"] > last:
                    last = contact["LastSeenEpoch"]
                    lastc = contact
        sum = buddies+blocked+neutral+unknown
        msg = ["[u]My Contact Stats[/u]:"]
        tmp = []
        for c in counters: tmp.append("{}: {} ({}%)".format(c.title(), counters[c], percentage(counters[c], sum)))
        msg.append("Sum: [b]{}[/b] {}".format(sum, " | ".join(tmp)))
        if buddies > 0:
            tmp = []
            for c in bcounters: tmp.append("{}: {} ({}%)".format(c.title(), bcounters[c], percentage(bcounters[c], sum)))
            msg.append("[color=green]Buddies[/color]: [b]{}[/b] ({}%) {}".format(buddies, percentage(buddies, sum), " | ".join(tmp)))
        if blocked > 0:
            tmp = []
            for c in blcounters: tmp.append("{}: {} ({}%)".format(c.title(), blcounters[c], percentage(blcounters[c], sum)))
            msg.append("[color=red]Blocked[/color]: [b]{}[/b] ({}%) {}".format(blocked, percentage(blocked, sum), " | ".join(tmp)))
        if neutral > 0:
            tmp = []
            for c in ncounters: tmp.append("{}: {} ({}%)".format(c.title(), ncounters[c], percentage(ncounters[c], sum)))
            msg.append("Neutral: [b]{}[/b] ({}%) {}".format(neutral, percentage(neutral, sum), " | ".join(tmp)))
        if unknown > 0:
            tmp = []
            for c in ucounters: tmp.append("{}: {} ({}%)".format(c.title(), ucounters[c], percentage(ucounters[c], sum)))
            msg.append("[color=orange]Unknown[/color]: [b]{}[/b] ({}%) {}".format(unknown, percentage(unknown, sum), " | ".join(tmp)))
        if detailed and first:
            msg.append("First: {} {} {} on {}".format(
            firstc["LastSeen"].replace("T", " "), self.readableContactStatus(firstc), clientURL(1, 0, firstc["IDS"], firstc["Nickname"].decode("utf-8", "ignore")), channelURL(1, 0, firstc["LastSeenServerName"].decode("utf-8", "ignore"))))
        if detailed and last:
            msg.append("Last: {} {} {} on {}".format(
            lastc["LastSeen"].replace("T", " "), self.readableContactStatus(firstc), clientURL(1, 0, lastc["IDS"], lastc["Nickname"].decode("utf-8", "ignore")), channelURL(1, 0, lastc["LastSeenServerName"].decode("utf-8", "ignore"))))
        return "\n".join(msg)

    def readableContactStatus(self, contact):
        if contact["Friend"] == ContactStatus.FRIEND: return "[color=green]Friend[/color]"
        elif contact["Friend"] == ContactStatus.BLOCKED: return "[color=red]Blocked[/color]"
        elif contact["Friend"] == ContactStatus.NEUTRAL: return "Neutral"
        else: return "[color=orange]Unknown[/color]"

    def infoData(self, schid, id, atype):
        if self.count < 3: self.count += 1; return None
        clist = list()
        if atype == ts3defines.PluginItemType.PLUGIN_SERVER:
            (err, clist) = ts3lib.getClientList(schid)
        elif atype == ts3defines.PluginItemType.PLUGIN_CHANNEL:
            return None
            (err, clist) = ts3lib.getChannelClientList(schid, id)
        else: return None
        sum = 0;buddies = 0;blocked = 0;neutral = 0;unknown = 0
        uidlist = []
        for clid in clist:
            (err, uid) = ts3lib.getClientVariable(schid, clid, ts3defines.ClientProperties.CLIENT_UNIQUE_IDENTIFIER)
            uidlist.append(uid)
        db = ts3client.Config()
        q = db.query("SELECT * FROM contacts")
        while q.next():
            sum += 1
            val = q.value("value").split('\n')
            uid = ""
            for line in val:
                if line.startswith('IDS='):
                    uid = line.split('IDS=')[1]
            if not uid in uidlist: continue
            for line in val:
                if line.startswith('Friend='):
                    status = int(line[-1])
                    if status == ContactStatus.FRIEND: buddies += 1
                    elif status == ContactStatus.BLOCKED: blocked += 1
                    elif status == ContactStatus.NEUTRAL: neutral += 1
                    else: unknown += 1
        del db
        _return = list()
        _sum = buddies+blocked+neutral+unknown
        _return.append("Online: {} / {} ({}%)".format(_sum, sum, percentage(_sum, sum)))
        _return.append("[color=green]Buddies[/color]: {} ({}%)".format(buddies, percentage(buddies, _sum)))
        _return.append("[color=red]Blocked[/color]: {} ({}%)".format(blocked, percentage(blocked, _sum)))
        _return.append("Neutral: {} ({}%)".format(neutral, percentage(neutral, _sum)))
        if unknown > 0: _return.append("[color=orange]Unknown[/color]: {} ({}%)".format(unknown, percentage(unknown, _sum)))
        return _return

class contactStatsFilters(QDialog):
    listen = False
    def __init__(self, script, parent=None):
        try:
            super(QDialog, self).__init__(parent)
            setupUi(self, script.ui)
            self.cfg = script.cfg
            self.ini = script.ini
            self.reloadPlugin = script.__init__
            self.setAttribute(Qt.WA_DeleteOnClose)
            self.setWindowTitle("Count Contacts Filters")
            self.setupTable()
            self.listen = True
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def setupTable(self):
        try:
            self.tbl_filters.clearContents()
            self.tbl_filters.setRowCount(0)
            for o in self.cfg.options('filters'):
                pos = self.tbl_filters.rowCount
                self.tbl_filters.insertRow(pos)
                tmp = self.cfg.get('filters', o).split('|', 2)
                chk_case = QCheckBox()
                chk_case.setChecked(bool(int(tmp[0])))
                self.tbl_filters.setCellWidget(pos, 0, chk_case)
                box_type = QComboBox()
                box_type.addItems(["Prefix", "Suffix", "Contains", "Equals"])
                box_type.connect("currentIndexChanged(int)", self.currentIndexChanged)
                box_type.setCurrentText(tmp[1])
                self.tbl_filters.setCellWidget(pos, 1, box_type)
                self.tbl_filters.setItem(pos, 2, QTableWidgetItem(o))
                self.tbl_filters.setItem(pos, 3, QTableWidgetItem(tmp[2]))
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def currentIndexChanged(self, i):
        if PluginHost.cfg.getboolean("filters", "verbose"): print("test", i)
        row = self.tbl_filters.currentRow()
        if PluginHost.cfg.getboolean("filters", "verbose"): print("row:", row)
        # item = self.tbl_members.itemAt(const QPoint &point)
        # item = self.tbl_members.selectedItems()
        # print("item:", item)
        # self.tbl_members.at
        # ts3lib.requestSetClientChannelGroup(self.schid, [item.itemData], [self.channel], [self.dbid])

    def on_btn_apply_clicked(self):
        items = []
        for i in range(self.tbl_filters.rowCount):
             uid = self.lst_active.item(i)
             items.append(uid)
        self.grp_active.setTitle("{} Active".format(self.lst_active.count))
        self.cfg.set('general', 'badges', ','.join(items))
        self.setCustomBadges()

    def on_btn_save_clicked(self):
        with open(self.ini, 'w') as configfile: self.cfg.write(configfile)


try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import argparse

def ocr_core(filename):
    """
    This function will handle the core OCR processing of images.
    """
    text = pytesseract.image_to_string(Image.open(filename))  # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image
    return text

# print(ocr_core('images/ocr_example_1.png'))

def ArgChecker():
    parser = argparse.ArgumentParser()
    parser.add_argument("filename", nargs='?')
    args = parser.parse_args()
    if args.filename is None:
        parser.error("This python program requires a full filepath to run")
    else:
        print(ocr_core(args.filename))

if __name__ == '__main__':
    ArgChecker()


#!/usr/bin/env python3 -u

import scipy
from scipy.stats import norm
import numpy
import random
import shelve

import pickle
import csv

import os
import os.path

import sys
from pathlib import Path
home_dir=str(Path.home())
git_dir='/QstarFromTidalSynchronization/MCMC/combined'
if home_dir=='/home/rxp163130':current_directory=home_dir+git_dir
if home_dir=='/home/ruskin':current_directory=home_dir+'/projects'+git_dir
if home_dir=='/home1/06850/rpatel23':
    work_dir='/work/06850/rpatel23/stampede2'
    current_directory=work_dir+git_dir

from uncorrelated_sampling import UncorrelatedSampling

from evolution_class import evolution
from stellar_evolution.manager import StellarEvolutionManager
from orbital_evolution.evolve_interface import library as\
    orbital_evolution_library

class ModelTesting:

    def ModelCalculations(self,
                          parameter_set=None):

        parameter_array=[]
        for key in parameter_set:
            parameter_array=numpy.append(parameter_array,parameter_set[key])

        with open('model_16.pickle','rb') as f:
            s=pickle.load(f)
        parameter_array=numpy.append(parameter_array,parameter_set['primary_mass']*self.mass_ratio)
        result=s.predict(parameter_array.reshape(1,-1))
        self.Porb_iML,self.ecc_iML=result[0][0],result[0][1]

    def POETCalculations(self,
                    parameter_set=None):

        for key,value in self.sampling_parameters.items():
            if value['dist']=='Uniform':
                if numpy.logical_or(parameter_set[key]<self.sampling_parameters[key]['min'],
                                    parameter_set[key]>self.sampling_parameters[key]['max']):
                    return scipy.nan
                    break

        solve_for_spin = evolution(self.interpolator,
                                   parameter_set,
                                   self.fixed_parameters,
                                   self.mass_ratio,
                                   self.instance,
                                   self.output_directory
                                   )

        self.spin=solve_for_spin()
        if numpy.isnan(self.spin) or numpy.isinf(self.spin):return scipy.nan

    def propose_parameters(self):

        proposed = dict()

        self.proposing=UncorrelatedSampling(self.system,self.samples_file,self.sampling_parameters,self.proposed_parameters)
        proposed=self.proposing()
        self.proposed_parameters=proposed

    def write_header(self):

        f_name='system_output_'+self.instance+'.txt'
        header = []
        header.append('Iteration_step')

        for key in self.sampling_parameters.keys():
            header.append(key)

        ext = [ 'secondary_mass',
                'Porb_iPOET',
                'ecc_iPOET',
                'Porb_fPOET',
                'ecc_fPOET',
                'spinPOET',
                'delta_e',
                'delta_p',
                'bad_solution_flag',
                'gsl_flag',
                'binary_destroyed'
               ]

        for a in ext:
            header.append(a)

        with open(f_name, 'w', 1) as fheader:
            for name in header:
                fheader.write('%s\t' % name)
            fheader.write('\n')

    def write_output(self):

        f_name='system_output_'+self.instance+'.txt'

        load_solver_file = self.output_directory+'solver_results_'+self.instance+'.pickle'

        if os.path.isfile(load_solver_file) == True:
            with open(load_solver_file,'rb') as f:
                initial_orbital_period=pickle.load(f)
                intial_eccentricity=pickle.load(f)
                current_Porb=pickle.load(f)
                current_e=pickle.load(f)
                current_spin=pickle.load(f)
                delta_e=pickle.load(f)
                delta_p=pickle.load(f)
                bad_solution=pickle.load(f)
                gsl_flag=pickle.load(f)
                binary_destroyed=pickle.load(f)

        with open(f_name, 'a', 1) as f:

            f.write('%s\t' %self.iteration_step)

            for key, value in self.proposed_parameters.items():
                f.write('%s\t' % value)
            f.write(repr(self.proposed_parameters['primary_mass']*self.mass_ratio)+'\t')

            f.write(repr(self.Porb_iML)+'\t'+
                    repr(self.ecc_iML)+'\t')

            if os.path.isfile(load_solver_file) == True:
                f.write(
                    repr(initial_orbital_period)+'\t'+
                    repr(intial_eccentricity)+'\t'+
                    repr(current_Porb)+'\t'+
                    repr(current_e)+'\t'+
                    repr(current_spin)+'\t'+
                    repr(delta_e)+'\t'+
                    repr(delta_p)+'\t'+
                    repr(bad_solution)+'\t'+
                    repr(gsl_flag)+'\t'+
                    repr(binary_destroyed)+
                    '\n')
            else:f.write('\n')

    def iterations(self):

        while True:

            if self.iteration_step==1:
                proposed=dict()
                for key,value in self.sampling_parameters.items():
                    proposed[key]=value['value']
                self.proposed_parameters=proposed
                print('\nSTARTING PROPOSED VALUES')
                print (self.proposed_parameters)
                sys.stdout.flush()
                self.write_header()

            self.propose_parameters()
            print ('\nPROPOSED VALUES')
            print (self.proposed_parameters)
            sys.stdout.flush()

            self.POETCalculations(self.proposed_parameters)

            self.ModelCalculations(self.proposed_parameters)

            self.write_output()

            self.iteration_step = self.iteration_step + 1

    def __init__(self,
                 system_number,
                 interpolator,
                 samples_file,
                 sampling_parameters,
                 fixed_parameters,
                 mass_ratio,
                 instance,
                 current_directory,
                 output_directory):

        self.system=system_number
        self.interpolator=interpolator
        self.samples_file=samples_file
        self.sampling_parameters=sampling_parameters
        self.fixed_parameters=fixed_parameters
        self.iteration_step=1
        self.mass_ratio=mass_ratio
        self.Porb_iML=0.0
        self.ecc_iML=0.0

        self.phi_keys=[]
        self.theta_keys=[]
        for key,value in self.sampling_parameters.items():
            if value['dist'] in ['Normal','Uniform']:
                self.theta_keys.append(key)
            if value['dist']=='Samples':
                self.phi_keys.append(key)
        self.check_age_neg = None

        self.instance = instance

        self.output_directory=output_directory


import copy
import time
from collections import deque

'''
Zadanie 3 zrealizowane podczas kursu Sztuczna Inteligencja.
Stad tyle kodu.
Pozostale zadanie znajduja sie na dole projektu, wraz z wywolaniami.
'''
def read_input():
    with open("zad_input.txt") as file:
        imp = []
        rows = []
        cols = []

        for line in file:
            imp.append(line.split())

        ro = int(imp[0][0])

        for i in range(1, ro + 1):
            rows.append(list(map(int, imp[i])))

        for i in range(ro + 1, len(imp)):
            cols.append(list(map(int, imp[i])))

    return rows, cols

def image_printer(img):
    image = copy.deepcopy(img)
    for i in range(len(image)):
        for j in range(len(image[i])):
            if image[i][j]:
                image[i][j] = '#'
            else:
                image[i][j] = '.'
    return image

def porownaj_listy(l1, l2):
    zmienionych_bitow = 0
    for i in range(len(l1)):
        if l1[i] != l2[i]:
            zmienionych_bitow += 1
    return zmienionych_bitow

def column(m, o):
    return [row[o] for row in m]

def multi_validator(li, lv):
    blocks_max_index = len(lv) - 1
    if li[0] == 0:
        block = -1
        one_or_zero = 0
    else:
        block = 0
        one_or_zero = 1

    current_len_of_subsequence = 1

    for i in range(1, len(li)):
        if li[i] != one_or_zero:
            # 1111110
            one_or_zero = 0
            if li[i] == 0:
                if current_len_of_subsequence != lv[block]:
                    return False
                current_len_of_subsequence = 1
            # 0000001
            if li[i] == 1:
                one_or_zero = 1
                if blocks_max_index == block:
                    return False
                block += 1
                current_len_of_subsequence = 1
        elif li[i] == 1:
            current_len_of_subsequence += 1
    if one_or_zero == 1 and lv[len(lv) - 1] != current_len_of_subsequence:
        return False
    if blocks_max_index != block:
        return False
    return True

# generates combinations of all possible rows/columns from given [list of 1 and 0] and [value list]
# for multi([0,1,1,0,1,1], [1, 3]) generates: [[0, 1, 0, 1, 1, 1], [1, 0, 1, 1, 1, 0], [1, 0, 0, 1, 1, 1]]
def generate_combinations(row, lv):
    spaces = [1 for _ in range(len(lv) + 1)]
    spaces[0] = 0
    spaces[len(lv)] = 0
    sum_of_chars = sum(spaces) + sum(lv)
    spaces_to_generate = len(row) - sum_of_chars

    def adding_one_space(combs, s):  # list of combinations of spacing ex. [(0,1,1,0),(0,0,1,0)]
        res = []
        for j in range(len(combs)):
            copy_spaces = copy.deepcopy(combs[j])
            for i in range(len(combs[j])):
                copy_spaces[i] += 1
                res.append(copy.copy(copy_spaces))
                copy_spaces[i] -= 1

        for r in range(len(res)):
            res[r] = tuple(res[r])
        res = list(set(res))
        for r in range(len(res)):
            res[r] = list(res[r])
        if s == 1:
            return res
        else:
            s -= 1
            return adding_one_space(res, s)

    if spaces_to_generate == 0:
        combinations = [spaces]
    else:
        combinations = adding_one_space([spaces], spaces_to_generate)

    rows_generated = []
    for c in combinations:
        result = [0 for _ in range(len(row))]
        res_iter = 0
        value_iter = 1
        for i in range(len(c)):
            for k in range(c[i]):
                result[res_iter] = 0
                res_iter += 1
            if i < len(c) - 1:
                current_value = lv[value_iter - 1]
                value_iter += 1
                for val in range(current_value):
                    result[res_iter] = 1
                    res_iter += 1
        rows_generated.append(result)
    return rows_generated

# MAIN ######################################

def logic_image_solver(width, height, data_w, data_h):
    image = [[0 for _ in range(width)] for _ in range(height)]

    # find all possible combinations for all rows/columns and do it once before running a loop
    row_combinations = [generate_combinations(image[i], data_h[i]) for i in range(len(image))]
    col_combinations = [generate_combinations(column(image, i), data_w[i]) for i in range(len(image[0]))]
    checked = [[0 for _ in range(width)] for _ in range(height)]
    not_valid = deque()

    def find_solution(y, x, combs):
        row_point = combs[0][x]

        if all(row[x] == row_point for row in combs):
            checked[y][x] = row_point
            col_combinations[x] = [col for col in col_combinations[x] if col[y] == checked[y][x]]

        else:
            column_point = col_combinations[x][0][y]

            if all(column[y] == column_point for column in col_combinations[x]):
                checked[y][x] = column_point
                row_combinations[y] = [row for row in row_combinations[y] if row[x] == checked[y][x]]
            else:
                not_valid.append((y, x))

    for y in range(height):
        current_rows = row_combinations[y]
        for x in range(width):
            find_solution(y, x, current_rows)

    while len(not_valid) > 0:
        y, x = not_valid.popleft()
        current_rows = row_combinations[y]
        find_solution(y, x, current_rows)

    # image_printer(checked)
    return checked

def zad3():
    r = read_input()
    res = image_printer(logic_image_solver(len(r[1]), len(r[0]), r[1], r[0]))
    for c in res:
        print(*c)

def zad1():
    def doskonale_imperatywna(n):
        def doskonala(n):
            dzielniki = []
            for i in range(1, n):
                if n % i == 0:
                    dzielniki.append(i)
            if sum(dzielniki) == n:
                return True
            return False
        ans = []
        for i in range(1, n):
            if doskonala(i):
                ans.append(i)
        return ans

    def doskonale_iterowanaa(n):
        def doskonala(n):
            dzielniki = []
            for i in range(1, n):
                if n % i == 0:
                    dzielniki.append(i)
            if sum(dzielniki) == n:
                return True
            return False

        for i in range(1, n):
            if doskonala(i):
                yield i

    def doskonale_skladana(n):
        def dosk(n):
            return [i for i in range(1, n) if n % i == 0]
        return [i for i in range(1, n) if sum(dosk(i)) == i]

    def doskonale_funkcyjna(n):
        def summy(n):
            return sum(filter(lambda y: n % y == 0, range(1, n)))

        return list(filter(lambda x: x == summy(x), range(1, n + 1)))

    for i in range(2, 5):
        x = pow(10, i)
        print()
        print('N = {}'.format(x))
        t = time.time()
        doskonale_imperatywna(x)
        print("Czas imperatytwnie: {}".format(round(time.time() - t, 4)))
        t = time.time()
        doskonale_skladana(x)
        print("Czas składanie: {}".format(round(time.time() - t, 4)))
        t = time.time()
        doskonale_funkcyjna(x)
        print("Czas funkcyjnie: {}".format(round(time.time() - t, 4)))
        t = time.time()
        list(doskonale_iterowanaa(x))
        print("Czas iterowalnie: {}".format(round(time.time() - t, 4)))

zad1()


from setuptools import setup

with open('README.md', 'r') as f:
        long_description = f.read()

setup(
    name='file_organizer',
    py_modules=['organize'],
    version='0.2.3',
    description='A file organizer based on file suffixes and user chosen file extensions',
    long_description=long_description,
    long_description_content_type='text/markdown',
    author='Gilson de Paula',
    author_email='gilsonsvieira93@gmail.com',
    url='https://github.com/xlbruce/file-organizer',
    license='MIT',
    keywords=['file', 'organizer'],
    install_requires=[
        'Click',
    ],
    entry_points='''
        [console_scripts]
        organize=organize:main
    ''',
    classifiers=[
        "Programming Language :: Python :: 3.7",
        "Operating System :: POSIX",

    ]
)


from django.urls import path
from . import views
from .views import *

urlpatterns = [
    path('', views.home, name='school-home'),
    path('profile/', views.profile, name='school-profile'),
    path('teacher/', views.teachers, name='school-teachers'),
    path('resource/', views.resources, name='school-resources'),
    path('set_profile/', SetProfileCreateView.as_view(), name='set-school-profile'),
    path('add_profile/', SchoolCreateView.as_view(), name='add-school-profile'),
    path('add_teacher/', SchoolTeacherCreateView.as_view(), name='add-school-teacher'),
    path('register_teacher/', TeacherCreateView.as_view(), name='register-teacher'),
    path('view_teachers/', SchoolTeacherListView.as_view(), name='view-school-teachers'),
    path('profile/<int:pk>/update/', SchoolProfileUpdateView.as_view(), name='update-school-profile'),
    path('teacher/<int:pk>/update/', SchoolTeacherUpdateView.as_view(), name='update-school-teacher'),
    path('teacher/<int:pk>/', SchoolTeacherDetailView.as_view(), name='school-teacher-details'),
    path('add_resource/', SchoolResourceCreateView.as_view(), name='add-school-resource'),
    path('resource/<int:pk>/update/', SchoolResourceUpdateView.as_view(), name='update-school-resource'),
    path('view_resources/', SchoolResourceListView.as_view(), name='view-school-resources'),
    path('resource/<int:pk>/', SchoolResourceDetailView.as_view(), name='school-resource-details'),
    path('student/', views.students, name='students'),
    path('add_students/enrolments/', views.add_students, name='add-students'),
    path('add_students/repeaters/', views.add_repeaters, name='add-repeaters'),
    path('view_students/repeaters/', views.view_repeaters, name='view-repeaters'),
    path('add_students/nationality/', views.add_nationality, name='add-nationality'),
    path('view_students/nationality/', views.view_nationality, name='view-nationality'),
    path('add_students/physical_streams/', views.add_physical_streams, name='add-physical-streams'),
    path('view_students/physical_streams/', views.view_physical_streams, name='view-physical-streams'),
    path('add_students/orphans/', views.add_orphans, name='add-orphans'),
    path('view_students/orphans/', views.view_orphans, name='view-orphans'),
    path('add_students/special_needs/', views.add_special_needs, name='add-special-needs'),
    path('view_students/special_needs/', views.view_special_needs, name='view-special-needs'),
    path('add_students/seating_and_writing_space/', views.add_seating_and_writing_space, name='add-seating-and-writing-space'),
    path('view_students/seating_and_writing_space/', views.view_seating_and_writing_space, name='view-seating-and-writing-space'),
    path('add_students/transfered_students/', views.add_transfered_students, name='add-transfered-students'),
    path('view_students/transfered_students/', views.view_transfered_students, name='view-transfered-students'),
    path('add_students/examinations/', views.add_examinations, name='add-examinations'),
    path('view_students/examinations/', views.view_examinations, name='view-examinations'),
    path('add_students/proposed_intake/', views.add_proposed_intake, name='add-proposed-intake'),
    path('view_students/proposed_intake/', views.view_proposed_intake, name='view-proposed-intake'),
    path('add_students/new_entrants/', views.add_new_entrants, name='add-new-entrants'),
    path('view_students/new_entrants/', views.view_new_entrants, name='view-new-entrants'),
    path('student/<int:pk>/update/', StudentUpdateView.as_view(), name='update-student'),
    path('view_students/enrolments/', views.view_students, name='view-students'),
    path('left_teachers/', views.add_left_teachers, name='add-left-teachers'),
    path('non_teaching_staff/', views.add_non_teaching_staff, name='add-non-teaching-staff'),
    path('teacher_allocation/', views.teacher_allocation, name='teacher-allocation'),
    path('add_buildings/', views.add_buildings, name='add-buildings'),
    path('add_buildings_under_construction/', views.add_buildings_under_construction,
        name='add-buildings-under-construction'),
    path('add_buildings_needed/', views.add_rooms_needed, name='add-buildings-needed'),
    path('add_latrines/', views.add_latrines, name='add-latrines'),
    path('add_water_and_energy/', views.add_water_and_energy_sources, name='add-water-and-energy-sources'),
    path('request_teacher/', RequestTeacherCreateView.as_view(), name='request-teacher'),
    path('request_teacher/<int:pk>/update/', RequestTeacherUpdateView.as_view(), name='update-teacher-request'),
    path('request_teacher/view/', RequestTeacherListView.as_view(), name='teacher-requests'),
]


'''
Author: Kristopher Buote

Neural Network that trains on philosophy text sequences to predict the most likely next word.
Embeddings are learned.
'''
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from keras import Sequential
from keras.layers import Embedding, LSTM, Dense
import pickle

filename = 'republic_clean'
print('Loading data...')
data = open('./philosophy_data/' + filename + '.txt', 'r').read()  # should be simple plain text file
lines = data.split('\n')
lines = lines[0:5]
print('Done.')

# Integer encoding sequences of words
tokenizer = Tokenizer()
print('Tokenizing...')
tokenizer.fit_on_texts(lines)
sequences = tokenizer.texts_to_sequences(lines)
vocab_size = len(tokenizer.word_index) + 1
print('Done.')

# Separate into input (X) and output (Y)
print("Splitting into X and Y...")
sequences = np.array(sequences)
X, Y = sequences[:,0:-1], sequences[:,-1]
# Y = to_categorical(Y, num_classes=vocab_size)
seq_length = X.shape[1]
print('Done.')

# Create Model
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=100, input_length=seq_length)) # Consider input_length = None
model.add(LSTM(100, return_sequences=True))
model.add(LSTM(100))
model.add(Dense(100, activation='relu'))
model.add(Dense(vocab_size, activation='softmax'))
model.summary()

# Compile model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Fit model
epochs = 1
for e in range(epochs):
    model.fit(X, Y, batch_size=512, epochs=1)
    # if e % 10 == 0:
    model.save('./models/philosopher-king-epoch' + str(e) +'.h5')
    # save the tokenizer
    pickle.dump(tokenizer, open('./models/tokenizer.pkl', 'wb'))


# -*- coding: utf-8 -*-
"""This module provide method to return stolen bikes by distance"""
import logging

from django.views.decorators.csrf import csrf_exempt
from django.db.models import Func, F
from django.http import JsonResponse, HttpResponse
from django.core import serializers

from APP.models import StolenBike, Bicycle, Image
from ..utils.need_token import need_token

logger = logging.getLogger(__name__)

class Sin(Func):
    function = 'SIN'

class Cos(Func):
    function = 'COS'

class Acos(Func):
    function = 'ACOS'

class Radians(Func):
    function = 'RADIANS'

@csrf_exempt
def get(request):
    """Return stolen bikes sorted by distance.

    Take get params:
    lat - center latitude
    long - center longitude
    distance - radius of data
    distancemin - minimum distance

    Author: Olexii
    """
    if request.method != "GET":
        logger.info("Unsupported method returned")
        return HttpResponse(status=405)

    lat = float(request.GET.get('lat'))
    lng = float(request.GET.get('lng'))
    distance = request.GET.get('distance')
    distance_min = request.GET.get('distance_min', 0)
    radlat = Radians(lat)
    radlong = Radians(lng)
    radflat = Radians(F('lat'))
    radflong = Radians(F('lng'))

    expression = 6371.0 * Acos(Cos(radlat) * Cos(radflat) *
                               Cos(radflong - radlong) +
                               Sin(radlat) * Sin(radflat))

    query = StolenBike.objects.annotate(
        distance=expression)
    query = query.filter(distance__range=(distance_min, distance))
    query = query.order_by('distance')

    result = []
    for stolen in query:
        bike = Bicycle.objects.get(pk=stolen.pk)
        image = Image.objects.get(bike=bike.pk)
        result.append({
            "description": stolen.description,
            "lat": stolen.lat,
            "lng": stolen.lng,
            "id": stolen.id,
            "bike": {
                "id": bike.id,
                "name": bike.name,
                "image": image.url
            }
        })

    return JsonResponse({
        "data": result,
        "count": len(result),
        "count_all": StolenBike.objects.count()
    })