from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.mssql_operator import MsSqlOperator
from datetime import datetime
import pandas as pd

from utils import load_df_to_sql
from variables import sql_connid
from airflow.hooks.mssql_hook import MsSqlHook

default_args = {
    'owner': 'Clinicos',
    'depends_on_past': False,
    'start_date': datetime(2015, 6, 1),
    # 'retries': 1,
    # 'retry_delay': timedelta(minutes=5),
}

def mssql_func(**kwargs):
    conn = MsSqlHook.get_connection(sql_connid)
    hook = conn.get_hook()
    print('connection OK')
    df = hook.get_pandas_df(sql="SELECT * FROM [dbo].[BI_Ecopetrol_Queues]")
    print(df)
    print('termine')

with DAG('dag_test_db_clinicos',
         default_args=default_args,
         schedule_interval=None,
         max_active_runs=1) as dag:

    start_task = DummyOperator(task_id='dummy_start2')

    reading_db = PythonOperator(
        task_id='reading_db2',
        python_callable=mssql_func,
    )

start_task >> reading_db


# Generating a JSON object having a lot of fields:
# {"f1": 1, "f2": 2, ... }
import json
import tempfile
from typing import Dict

field_num = 100
column_mapping_list = []
for num in range(field_num):
    column_name = f'column{num}'
    column_mapping_dict: Dict[str, object] = {
        'dataFrameColumnName': column_name,
        'tableColumnName': column_name,
        'tableColumnType': 'VARCHAR',
        'checked': True,
        'tableColumnFormat': '255'
    }
    column_mapping_list.append(column_mapping_dict)

out_file: str = tempfile.mkstemp(suffix='.json')[1]
print(f'Output file: "{out_file}"')
with open(out_file, 'w') as fp:
    json.dump(column_mapping_list, fp)


import tkinter as tk
import show_message as mes #メッセージボックスを表示するモジュール
import convert_widget_state as conWid #ウィジェットを無効化するモジュール

def text_off(memo): #「異常なし」のボタンを押した場合
    #テキストに書き込めない状態にする
    conWid.to_disabled_widget([memo])

def text_on(memo): #「不具合あり」のボタンを押した場合
    #テキストに書き込める状態にする
    conWid.to_normal_widget([memo])

def text_delete(window, memo_text, var):
    #入力内容を削除するかの確認画面の表示
    memo_delete_confirmation = mes.askokcancel("テキストの削除",
     "入力した内容を全て削除しますか？", window)

    if memo_delete_confirmation: #「OK」を押した場合
        text_on(memo_text) #テキストを編集可能にする
        memo_text.delete("1.0",tk.END) #内容を全て削除する

        #削除した際に「異常なし」を選んでいた場合
        if var.get() == "OK":
            text_off(memo_text) #テキストを編集不可にする


class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        dict1 = {}
        dict2 = {}
        answer = 0

        for num1 in nums1:
            for num2 in nums2:
                num = num1 + num2
                cnt = dict1.get(num, 0) + 1
                dict1[num] = cnt

        for num3 in nums3:
            for num4 in nums4:
                num = num3 + num4
                cnt = dict2.get(num, 0) + 1
                dict2[num] = cnt

        for k in dict1.keys():
            cnt = dict2.get(-k, 0)
            answer += dict1[k] * cnt

        return answer


##########################################
#                                        #
#            NE HASZNÁLD!!!!             #
#                                        #
##########################################

##########################################
#               Használata:              #
#                                        #
# a packages-be írd be az összes         #
# szükséges import-ot                    #
# majd futtad le a setap.py-t:           #
# python3 setup.py build                 #
##########################################

from cx_Freeze import setup, Executable

base = None

executables = [Executable("main.py", base=base)]

packages = ["idna", "time", "turtle"]
options = {
    'build_exe': {
        'packages': packages,
    },
}

setup(
    name="EGER_2019_1_E_Katica",
    options=options,
    version="Beta 0.41",
    description='EGER_2019_1_E_Katica',
    executables=executables
)


from cement2.core import controller
from dmirr.cli.controllers.base import dMirrResourceController
from dmirr.core import exc

class ProtocolController(dMirrResourceController):
    class Meta:
        label = 'protocols'
        description = 'dMirr Protocols Controller'
        arguments = [
            (['-l', '--label'],
             dict(action='store', dest='label', metavar='STR',
                  help='protocol label (unique identifier)')),
            (['-p', '--port'],
             dict(action='store', dest='port', metavar='STR',
                  help='protocol port')),
            (['resource'],
             dict(action='store', nargs='?',
                  help='resource label to work with')),
            (['-y', '--no-prompt'],
             dict(dest='no_prompt', action='store_true',
                  help='do not prompt for approval')),
            ]
        defaults = {}

    @controller.expose(help="create a new protocol resource")
    def create(self):
        self.validate_unique_resource(self.pargs.label)
        protocol = dict(label=self.pargs.label, port=self.pargs.port)
        response, data = self.hub.protocols.create(protocol)
        self.app.log.info("Protocol '%s' created." % protocol['label'])


import os
import csv
import json
from tqdm import tqdm

def label_trans(cls_label: str):
    # convert cls --> det
    DET_CLASSES = ['F5', 'P7', 'F2', 'W1', 'S4', 'T1', 'C14', 'B3', 'A7', 'A8', 'C2', 'P3', 'F8', 'C8', 'W2', 'S7',
                   'C13', 'T7', 'L3', 'Y1', 'M2', 'S5', 'V1', 'T2', 'S6', 'C10', 'S1', 'R2', 'D2', 'V2', 'C9', 'P2',
                   'H1', 'U2', 'H3', 'N1', 'T5', 'A9', 'D1', 'C6', 'C5', 'T8', 'P5', 'K2', 'P4', 'H2', 'A3', 'B1', 'E2',
                   'K3', 'C12', 'C15', 'L4', 'S2', 'R1', 'W3', 'T9', 'C11', 'M5', 'E4', 'R3', 'F7', 'U1', 'C3', 'K1',
                   'M1', 'A6', 'F3', 'E3', 'C1', 'B2', 'T6', 'P1', 'K5', 'K4', 'A4', 'L2', 'C16', 'S3', 'C4', 'A5',
                   'I1', 'A1', 'E1', 'P6', 'F6', 'C7', 'M4', 'F1', 'T10', 'T3', 'L1', 'Z1', 'A2', 'T4', 'M3', 'R4',
                   'T11']

    CLS_CLASSES = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', 'C1', 'C10', 'C11', 'C12',
                   'C13', 'C14', 'C15', 'C16', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'D1', 'D2', 'E1', 'E2',
                   'E3', 'E4', 'F1', 'F2', 'F3', 'F5', 'F6', 'F7', 'F8', 'H1', 'H2', 'H3', 'I1', 'K1', 'K2', 'K3', 'K4',
                   'K5', 'L1', 'L2', 'L3', 'L4', 'M1', 'M2', 'M3', 'M4', 'M5', 'N1', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6',
                   'P7', 'R1', 'R2', 'R3', 'R4', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'T1', 'T10', 'T11', 'T2',
                   'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'U1', 'U2', 'V1', 'V2', 'W1', 'W2', 'W3', 'Y1', 'Z1']
    # print(len(DET_CLASSES))
    # print(len(CLS_CLASSES))

    index = CLS_CLASSES.index(cls_label)
    return DET_CLASSES[index]

def read_json():
    json_path = './class_indices.json'
    assert os.path.exists(json_path), "file: '{}' dose not exist.".format(json_path)

    with open(json_path, "r") as f:
        class_indict = json.load(f)
    class_list = []
    for i in range(0, 98):
        class_list.append(class_indict[str(i)])
    return class_list

def main():
    csv_root = '/workspace/pycharm_project/mmrotate/2023df/'
    csv_file = os.path.join(csv_root, 'example_extra_ft_1.csv')
    with open('out2.csv', 'w') as csv_f:
        writer = csv.writer(csv_f)
        writer.writerow(['ImageID', 'LabelName', 'Conf', 'X1', 'Y1', 'X2', 'Y2', 'X3', 'Y3', 'X4', 'Y4'])
    with open('out1.csv', encoding='utf-8-sig') as f:
        for row in tqdm(csv.reader(f, skipinitialspace=True)):
            final_data = []
            # print(row)
            tif_name = row[0]
            cls_label = row[1]
            det_cls = label_trans(cls_label)
            conf = row[2]
            # tif_path = os.path.join(test_data_root, tif_name)  # 图像路径
            pos_list = []
            for i in range(3, 11):
                pos_list.append(float(row[i]))
            # outimg, cls = crop(tif_path, pos_list, cls)  # 剪裁图像
            # new_cls_index = predict_single(outimg)  # 图像分类预测
            # new_cls = label_trans(new_cls_index)
            final_data.append(tif_name)
            final_data.append(det_cls)
            final_data.append(conf)
            final_data = final_data + pos_list
            with open('out2.csv', 'a', newline='') as csv_f:
                # with open('example.csv', 'w') as csv_file:
                writer = csv.writer(csv_f)
                writer.writerow(final_data)
            # exit()
    print("finish")

if __name__ == '__main__':
    main()


# Print double-deck pyramid

# Descripition：
# Output double-deck Pyramid.

# Iutput：
# Multiple test data, each input is one integer n( 2 <= n <= 9).
# Multiple inputs ended by entering EOF (Ctrl+D on Mac, Ctrl-Z on Win)

# Output：
# One double-deck pyramid for each input

# Sample input：
# 2
# 5

# Sample output：
#  *
# ***
#  *
#     *
#    ***
#   *****
#  *******
# *********
#  *******
#   *****
#    ***
#     *

# Note：
# Use while (cin>>n) to keep receiving input until EOF is entered.
lines = []
while True:
    try:
        line = int(input())
        lines.append(line)
    except EOFError:
        break

def pyramid(lines):
  for i in lines:
    for j in range(1, i+1):
        output =  ' ' * (i-j) + '*' * (2*j - 1)
        print(output)
    for j in range(i-1, 0, -1):
        output =  ' ' * (i-j) + '*' * (2*j - 1)
        print(output)

pyramid(lines)


import requests
from bs4 import BeautifulSoup
import lxml
#url="https://www.amazon.in/Airdopes-121v2-Bluetooth-Immersive-Assistant/dp/B08JQN8DGZ?ref_=Oct_DLandingS_D_7a07edf6_60&smid=A14CZOWI0VEHLG"

#headers={

	#"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
	#"Accept-Language":"en",
#}

#r=requests.get(url,headers=headers)

#soup=BeautifulSoup(r.text,"lxml")

#print(soup.prettify())

#price=soup.select_one(selector="#priceblock_dealprice").getText()
#name=soup.select_one(selector="#productTitle").getText()
#name=name.strip()
#price=price.strip()
#priceblock_dealprice
#productTitle
#print(name)
#print(price)

def get_link_data(url):

	headers={

		"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
		"Accept-Language":"en",
	}

	r=requests.get(url,headers=headers)

	soup2=BeautifulSoup(r.text,"lxml")

	#print(soup.prettify())

	price=soup2.select_one(selector="#priceblock_ourprice").getText()
	name=soup2.select_one(selector="#productTitle").getText()
	name=name.strip()
	price=price.strip()
	price=price.replace(",","")
	price=float(price[1:])
	return name,price


from flask import Flask, request, jsonify
from flask_restful import Api
from flask_cors import CORS, cross_origin

import uuid

app = Flask(__name__)
api = Api(app)
CORS(app)

# Dashboard Data

dashboardData = {
    '1a': [{
        "id": uuid.uuid4().hex,
        "title": "Zacs Comment",
        'userName': "Zac",
        'description': "Did somthing",
        'time': "1/2/1",
        'content': 'DGFHGVJHBKJ'
    },
        {
        "id": uuid.uuid4().hex,
        "title": "Sams Card",
        'userName': "Sam",
        'description': "vgjhbk",
        'time': "5/5/86",
        'content': 'fghj'
    }, {
        "id": uuid.uuid4().hex,
        "title": "Sarahs Card",
        'userName': "Sarah",
        'description': "did more",
        'time': "1/4/5",
        'content': 'tejgvvhst'
    }],
    '1b': [
        {
            "id": uuid.uuid4().hex,
            "title": "Add commit counter for project section",
            'userName': "Zac Andrerson",
            'description': "",
            'time': "1/4/5",
            'content': 'tejgvvhst'
        }
    ],
    '1c': [

    ]
}

dashboard = [
    {
        'id': '1',
        'type': "gc",
        'title': "Notes",
        'data_id': '1a',
        'cardSettings': {
            'cardTextColor': '#222',
            'cardHeaderColor': '#eaeaea'
        }
    },
    {
        'id': '2',
        'type': "dc",
        'title': "Deadline",
        'data_id': '1b',
        'cardSettings': {
            'cardTextColor': '#222',
            'cardHeaderColor': '#eaeaea'
        }
    },
    {
        'id': '3',
        'type': "lc",
        'title': "Notifications",
        'data_id': '1c',
        'cardSettings': {
            'cardTextColor': '#222',
            'cardHeaderColor': '#eaeaea'
        }
    },
    # {
    #     'id': '4',
    #     'type': "dc",
    #     'title': "Deadline Card",
    #     'data_id': '1c',
    #     'cardSettings': {
    #         'cardTextColor': '#222',
    #         'cardHeaderColor': '#eaeaea'
    #     }
    # },
]

# APP ROUTE DIR

@app.route('/', methods=['GET'])
def getAllAppRoutes():
    return jsonify(
        {
            "/Dashboard": {

            },
            "/Projects": {

            }
        }
    )

# Dashboard Routing

@app.route('/Dashboard', methods=['GET', 'POST'])
def getAllDashboard():

    # GET Request
    if request.method == 'GET':
        return {"dashboard": dashboard}

    # POST Request
    if request.method == 'POST':
        posted_data = request.get_json()

        # Edge cases to make sure request is proper
        if len(posted_data) != 2:
            return {"message": "Invalid request"}
        if 'type' not in posted_data:
            return {"message": "Missing required parameter type"}
        if 'title' not in posted_data:
            return {"message": "Missing required parameter title"}

        ### NOTE: ADD CHECK FOR CARD TYPES HERE IN THE FUTURE ###

        posted_data['id'] = uuid.uuid4().hex
        posted_data['data_id'] = uuid.uuid4().hex
        posted_data['cardSettings'] = {
            'cardTextColor': '#222',
            'cardHeaderColor': '#eaeaea'
        }

        dashboard.append(posted_data)
        dashboardData[posted_data['data_id']] = []

        # Return json for dashboarc element creation
        return jsonify(posted_data)

@app.route('/Dashboard/<string:widget_id>', methods=['GET', 'DELETE', 'PUT'])
def getSpecificDashboardWidget(widget_id):

    # GET Request
    if request.method == 'GET':
        try:
            # Search each item in list for matchng id and return first matching
            widget = next(
                (item for item in dashboard if item['id'] == widget_id))
            return jsonify(widget)

        except StopIteration:
            return jsonify({"message": "id does not exist"})

    # DELETE Request
    if request.method == 'DELETE':
        try:
            # Search each item in list for matchng id and return first matching
            widget = next(
                (item for item in dashboard if item['id'] == widget_id))
            data_id = widget['data_id']

            # Get the index for the widget and delete it from the list
            i = dashboard.index(widget)

            dashboard.pop(i)
            dashboardData.pop(data_id)
            return jsonify(dashboard)
        except StopIteration:
            return jsonify({"message": "id does not exist"})

@app.route('/Dashboard/Data', methods=['GET'])
def getAllDashboardData():
    return {'card_data': dashboardData}

@app.route('/Dashboard/Data/<string:data_id>', methods=['GET'])
def getSpecificDashboardData(data_id):
    return {'card_data': dashboardData[data_id]}

# Project KANBAN Data
projectData = {
    '2a': [
        {
            'id': uuid.uuid4().hex,
            'name': "Todo",
            'items': [
                {"id": uuid.uuid4().hex, "title": "test1", "content": "One", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
                {"id": uuid.uuid4().hex, "title": "test2", "content": "Two", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
                {"id": uuid.uuid4().hex, "title": "test3", "content": "Three", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, }
            ]
        },
        {
            'id': uuid.uuid4().hex,
            'name': "In Progress",
            'items': [
                {"id": uuid.uuid4().hex, "title": "test1", "content": "One", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
                {"id": uuid.uuid4().hex, "title": "test2", "content": "Two", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
            ]
        },
        {
            'id': uuid.uuid4().hex,
            'name': "Completed",
            'items': [
                {"id": uuid.uuid4().hex, "title": "test1", "content": "One", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
                {"id": uuid.uuid4().hex, "title": "test2", "content": "Two", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
            ],
        },
    ],
    '2b': [{
        'id': uuid.uuid4().hex,
        'name': "Todo",
        'items': [
                {"id": uuid.uuid4().hex, "title": "test1", "content": "One", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
            {"id": uuid.uuid4().hex, "title": "test2", "content": "Two", 'cardSettings': {
                'cardTextColor': "#222",
                'cardHeaderColor': "#eaeaea",
            }, },
            {"id": uuid.uuid4().hex, "title": "test3", "content": "Three", 'cardSettings': {
                'cardTextColor': "#222",
                'cardHeaderColor': "#eaeaea",
            }, }
        ]
    },
        {
            'id': uuid.uuid4().hex,
            'name': "In Progress",
            'items': [
                {"id": uuid.uuid4().hex, "title": "test1", "content": "One", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
                {"id": uuid.uuid4().hex, "title": "test2", "content": "Two", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
            ]
    },
        {
            'id': uuid.uuid4().hex,
            'name': "Completed",
            'items': [
                {"id": uuid.uuid4().hex, "title": "test1", "content": "One", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
                {"id": uuid.uuid4().hex, "title": "test2", "content": "Two", 'cardSettings': {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }, },
            ],
    }, ],
    '2c': []
}

projects = [
    {
        "id": 1,
        "name": "Project 1",
        "data": "2a"
    },
    {
        "id": 2,
        "name": "Project 2",
        "data": "2b"
    },

]

##### PROJECTS ENDPOINTS ####

# ALL PROJECTS

@app.route('/Projects', methods=['GET'])
def getAllProjects():
    return jsonify(projects)

# INDIVIDUAL PROJECT
@app.route('/Projects/<int:project_id>', methods=['GET'])
def getSpecificProject(project_id):
    # Search each item in list for matchng id and return first matching
    project = next((item for item in projects if item['id'] == project_id))
    return jsonify(project)

# INDIVIDUAL PROJECT DATA

@app.route('/Projects/Data/<string:data_id>', methods=['GET', 'POST', 'DELETE'])
def getSpecificProjectData(data_id):
    if request.method == 'GET':
        return jsonify(projectData[data_id])

    if request.method == 'POST':
        posted_data = request.get_json()

        projectData[data_id] = posted_data
        return 'Posted'

# INDIVIDUAL PROJECT SECTION DATA
@app.route('/Projects/Data/<string:data_id>/<string:section_id>', methods=['GET', 'POST', 'DELETE'])
def getProjectCardData(data_id, section_id):
    if request.method == 'GET':
        data = projectData[data_id]
        # return jsonify(data)
        found = False

        for item in data:
            if item['id'] == section_id:
                found = True
        if found == True:
            return jsonify(item)
        else:
            return jsonify({"message": "Id does not exist"})

    if request.method == 'POST':
        data = projectData[data_id]
        # return jsonify(data)
        found = False

        for item in data:
            if item['id'] == section_id:
                found = True
                posted_data = request.get_json()
                posted_data['id'] = uuid.uuid4().hex
                posted_data['cardSettings'] = {
                    'cardTextColor': "#222",
                    'cardHeaderColor': "#eaeaea",
                }

                item['items'] = [posted_data] + item['items']

        if found == True:
            return jsonify(item)
        else:
            return jsonify({"message": "Id does not exist"})

if __name__ == '__main__':
    app.run(debug=True)


import cv2, pickle
import numpy as np
from sqlalchemy import modifier
from cnn import get_image_size
import sqlite3
import pyttsx3
import os

engine = pyttsx3.init()

# set the speaking rate
engine.setProperty('rate', 100)

def process_img(img, img_x, img_y):
    img = cv2.resize(img, (img_x, img_y))
    img = np.array(img, dtype=np.float32)
    img = np.reshape(img, (1, img_x, img_y, 1))
    return img

def model_predict(model, img):
    img_x, img_y = get_image_size()
    processed = process_img(img, img_x, img_y)
    pred_prob = model.predict(processed)[0]
    pred_class = list(pred_prob).index(max(pred_prob))
    return max(pred_prob), pred_class

def get_pred_text(pred_class):
    connect_db = sqlite3.connect("gesture_db.db")
    cmd = "SELECT g_name FROM gesture WHERE g_id="+str(pred_class)
    cursor = connect_db.execute(cmd)
    for row in cursor:
        return row[0]

def split_sentence(text, num_of_words):
    '''
	Splits a text into group of num_of_words
	'''
    list_words = text.split(" ")
    length = len(list_words)
    splitted_sentence = []
    begin_ind = 0
    end_ind = num_of_words
    while length > 0:
        part = ""
        for word in list_words[begin_ind:end_ind]:
            part = part + " " + word
        splitted_sentence.append(part)
        begin_ind += num_of_words
        end_ind += num_of_words
        length -= num_of_words
    return splitted_sentence

def put_text_in_blackboard(blackboard, splitted_text):
    # cv2.putText(影像, 文字, 座標, 字型, 大小, 顏色, 線條寬度, 線條種類)
    y = 200
    for text in splitted_text:
        cv2.putText(blackboard, "Predicted text :" + text, (8, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255))
        cv2.putText(blackboard, text, (4, y), cv2.FONT_HERSHEY_TRIPLEX, 2, (255, 255, 255))
        y += 50

def get_hand_hist():
    with open("hist", "rb") as f:
        hist = pickle.load(f)
    return hist

def say_sentence(sentence):
    while engine._inLoop:
        pass
    engine.say(sentence)
    engine.runAndWait()

def recognize(model):
    cap = cv2.VideoCapture(1)
    if cap.read()[0] == False:
        cap = cv2.VideoCapture(0)

    hist = get_hand_hist()
    x, y, w, h = 300, 100, 300, 300

    times = 0
    clear_times = 0
    sentence = ""
    text = ""
    while True:
        img = cap.read()[1]

        if img is None:
            continue

        img = cv2.flip(img, 1)
        img = cv2.resize(img, (640, 480))
        # imgCrop = img[y:y+h, x:x+w]
        imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

        # img projection
        dst = cv2.calcBackProject([imgHSV], [0, 1], hist, [0, 180, 0, 256], 1)
        disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
        # Convolution
        cv2.filter2D(dst, -1, disc, dst)

        blur = cv2.GaussianBlur(dst, (11, 11), 0)
        blur = cv2.medianBlur(blur, 15)
        thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
        thresh = cv2.merge((thresh, thresh, thresh))
        thresh = cv2.cvtColor(thresh, cv2.COLOR_BGR2GRAY)
        thresh = thresh[y:y+h, x:x+w]

        # check openCV version
        (openCV_ver, _, _) = cv2.__version__.split(".")
        if openCV_ver == '3':
            contours = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
        elif openCV_ver == '4':
            contours = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]
        if len(contours) > 0:
            contour = max(contours, key = cv2.contourArea)
            if cv2.contourArea(contour) > 10000:
                x1, y1, w1, h1 = cv2.boundingRect(contour)
                save_img = thresh[y1:y1+h1, x1:x1+w1]

                if w1 > h1:
                    save_img = cv2.copyMakeBorder(save_img, int((w1-h1)/2), int((w1-h1)/2), 0, 0, cv2.BORDER_CONSTANT, (0, 0, 0))
                elif h1 > w1:
                    save_img = cv2.copyMakeBorder(save_img, 0, 0, int((h1-w1)/2) , int((h1-w1)/2) , cv2.BORDER_CONSTANT, (0, 0, 0))

                pred_prob, pred_class = model_predict(model, save_img)

                if pred_prob*100 > 80:
                    old_text = text
                    text = get_pred_text(pred_class)
                    print(old_text ,text)
                    clear_times = 0
                    if old_text == text:
                        times += 1
                    else:
                        times = 0
                    if times >= 10:
                        sentence += text
                        times = 0
                        if sentence.startswith('I/Me'):
                            sentence = sentence.replace('I/Me', 'I')
                        elif sentence.endswith('I/Me'):
                            sentence.replace('I/Me', 'me')
            else:
                clear_times += 1
                if clear_times >= 10:
                    sentence = ""
                    text = ""
                    clear_times = 0
            blackboard = np.zeros((480, 640, 3), dtype=np.uint8)
            cv2.putText(blackboard, " ", (180, 50), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (255, 0,0))
            cv2.putText(blackboard, "Predicted text- " + text, (30, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 0))
            cv2.putText(blackboard, sentence, (30, 240), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255))
            cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
            res = np.hstack((img, blackboard))
            cv2.imshow("Recognizing gesture", res)
            cv2.imshow("thresh", thresh)
            keyboard_input = cv2.waitKey(1)
            if keyboard_input == 32:
                sentence += " "
            if keyboard_input == ord('m'):
                while True:
                    modify = cv2.waitKey(1)
                    if modify == ord('d'):
                        sentence = sentence[:-1]
                    if modify == ord('q'):
                        break
                    blackboard = np.zeros((480, 640, 3), dtype=np.uint8)
                    cv2.putText(blackboard, " ", (180, 50), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (255, 0,0))
                    cv2.putText(blackboard, "Press d to delete ", (30, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 0))
                    cv2.putText(blackboard, sentence, (30, 240), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255))
                    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
                    res = np.hstack((img, blackboard))
                    cv2.imshow("Recognizing gesture", res)
                    cv2.imshow("thresh", thresh)
            if keyboard_input == ord('s'):
                say_sentence(sentence)
            if keyboard_input == ord('q'):
                print(sentence)
                break
    # print("Ans: ", sentence)

""" model_predict(model, np.zero((50, 50), dtype=np.uint8))
recognize() """


n = int(input())

answer = list(map(int, input().split()))
score = 0
count = 0
for i in range(n):
    if answer[i] == 1:
        count += 1
        score += count
    else:
        count = 0

print(score)


import numpy as np
import pytest

import colorio
from colorio.illuminants import whitepoints_cie1931

ob2 = colorio.observers.cie_1931_2()

@pytest.mark.parametrize(
    "illuminant,decimals,values",
    [
        (colorio.illuminants.a(5), 5, [0.93048, 1.35769, 1.92508]),
        (colorio.illuminants.d50(), 3, [0.019, 2.051, 7.778]),
        (colorio.illuminants.d55(), 3, [0.024, 2.072, 11.224]),
        (colorio.illuminants.d65(), 4, [0.03410, 3.2945, 20.2360]),
        # 5.132 is different from the standard; 5.133 is listed there.
        # This is a false rounding.
        (colorio.illuminants.d75(), 3, [0.043, 5.132, 29.808]),
    ],
)
def test_values(illuminant, decimals, values):
    rdata = np.around(illuminant.data, decimals=decimals)
    print(illuminant)
    print(list(rdata[:6:2]))
    assert np.all(rdata[:6:2] == values)

# Don't try to match compute_whitepoint() with the actual whitepoints given in the
# standard. Too many things are not clear:
#
#   - What's the underlying data?
#   - How are the values interpolated?
#   - How are the products integrated?
#
# The methods for interpolation/integration given in the standard are quite dubious,
# too. Don't get into that.
#
@pytest.mark.parametrize(
    "illuminant,observer,ref",
    [
        (colorio.illuminants.a(), ob2, whitepoints_cie1931["A"]),
        (colorio.illuminants.d50(), ob2, [96.424, 100.0, 82.513]),
        (colorio.illuminants.d65(), ob2, [95.047, 100.0, 108.883]),
        (colorio.illuminants.d75(), ob2, [94.972, 100.0, 122.619]),
        # Should all sum up to 100, but the standard doesn't actually provide values
        # that do so. There's a newer not-yet-standard, CIE 2012, where this condition
        # is fulfilled up to approx 1.0e-6.
        (colorio.illuminants.e(), ob2, [100.008, 100.0, 100.033]),
        (colorio.illuminants.f2(), ob2, [103.755, 100.0, 49.864]),
        (colorio.illuminants.f7(), ob2, [95.019, 100.0, 108.639]),
        (colorio.illuminants.f11(), ob2, [100.904, 100.0, 64.284]),
    ],
)
def test_white_point(illuminant, observer, ref):
    print(illuminant)
    print(observer)
    values = colorio.illuminants.compute_whitepoint(illuminant, observer)
    print(list(values))
    print(list(np.round(values, 3)))
    assert np.all(np.round(values, 3) == ref)

def test_spectrum_to_xyz100():
    spectrum = colorio.illuminants.d65()
    observer = colorio.observers.cie_1931_2()
    out = colorio.illuminants.spectrum_to_xyz100(spectrum, observer)
    out = out / out[1] * 100
    print(list(out))
    ref = [95.04698658153113, 100.0, 108.88271743218647]
    assert np.all(np.abs(out - ref) < 1.0e-13 * np.abs(ref))

if __name__ == "__main__":
    test_white_point(
        colorio.illuminants.d50(), ob2, colorio.illuminants.whitepoints_cie1931["D50"]
    )


import json
import requests
from settings import SETTINGS

def get_access_token():
    response = requests.get(
        'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (
            SETTINGS['account_id'], SETTINGS['secret_key']))
    if response.status_code != 200:
        raise Exception('Failed to get access token')
    return json.loads(response.text)['access_token']

def upload_image(img_filename):
    files = {'media': open(img_filename, 'rb')}
    response = requests.post(
        'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=' + get_access_token(),
        files=files)
    if response.status_code != 200:
        raise Exception('Failed to upload image ' + img_filename)
    data = json.loads(response.text)
    if "url" not in data:
        raise Exception('Failed to upload image ' + img_filename + ' ' + response.text)
    return data['url']

def upload_article(article):
    title = article['title']
    content = article['content']
    author = '人生经理Charlene'
    thumb_media_id = 'Tbt5DXSqC3bfid5UxqErjLRd9i4NQfbQSaTu73gTVYs'  # lifecoachbanner
    post_url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=' + get_access_token()
    post_body = {
        "articles": [{
            "title": title,
            "thumb_media_id": thumb_media_id,
            "author": author,
            "show_cover_pic": 0,
            "content": content,
            "content_source_url": '',
        },
        ],
    }
    headers = {"Content-type": "application/json", "charset": "UTF-8"}
    response = requests.post(post_url, data=bytes(json.dumps(post_body, ensure_ascii=False), encoding='utf-8'),
                             headers=headers)
    print('Article upload: ' + response.text)


#!/usr/bin/env python
import rospy
import roslib
from std_msgs.msg import Empty, Int8
from geometry_msgs.msg import Twist, Vector3
from ardrone_autonomy.srv import FlightAnim

if __name__ == '__main__':
    rospy.init_node('example_node', anonymous=True)

    # publish commands (send to quadrotor)
    pub_takeoff = rospy.Publisher('/ardrone/takeoff', Empty)
    pub_land = rospy.Publisher('/ardrone/land', Empty)
    pub_reset = rospy.Publisher('/ardrone/reset', Empty)

    print("ready!")
    rospy.sleep(1.0)

    print("takeoff..")
    pub_takeoff.publish(Empty())

    rospy.sleep(3.0)

    #t = Twist()
    #t.angular.z = 0.1

    #pub_velocity = rospy.Publisher('/cmd_vel', t)

    rospy.sleep(2.0)

    print("land..")
    pub_land.publish(Empty())

    print("done!")


import settings
import dataset
import json
import sklearn.cluster as cluster
import numpy as np
from sqlalchemy.exc import ProgrammingError

db = dataset.connect(settings.CONNECTION_STRING)
result = db.query("SELECT lat,lng FROM geocoords")

data = []
for row in result:
	data.append([float(row['lat']),float(row['lng'])])

kmeans = cluster.KMeans(n_clusters=100).fit(data)
centers =  kmeans.cluster_centers_.tolist()
blank, count = np.unique(kmeans.labels_, return_counts= True)
size = count.tolist()
size = [float(i)/max(size) for i in size]
for row in range(len(centers)):
	try:
		db['heatmap'].insert(dict(
		    lat=centers[row][0],
		    lng=centers[row][1],
		    size=size[row]
		))
	except ProgrammingError as err:
		print(err)


from __future__ import division

import math
import logging
import numpy as np

from gnuradio.filter import window

import consts
import utils

class configuration(object):
    """Container for configurable settings."""
    def __init__(self, args):
        # Set logging levels
        self.logger = logging.getLogger('gr-analyzer')
        console_handler = logging.StreamHandler()
        logfmt = logging.Formatter("%(levelname)s:%(funcName)s: %(message)s")
        console_handler.setFormatter(logfmt)
        self.logger.addHandler(console_handler)
        if args.debug:
            loglvl = logging.DEBUG
        else:
            loglvl = logging.INFO
        self.logger.setLevel(loglvl)

        # If set to True, raw data from next run of flowgraph will be exported
        self.export_raw_time_data = False
        self.export_raw_fft_data = False

        # Add command line argument values to config namespace
        self.__dict__.update(args.__dict__)
        self.overlap = self.overlap / 100.0 # percent to decimal
        self.requested_span = self.span
        self.cpu_format = 'fc32'            # hard coded for now

        # configuration variables set by update():
        self.span = None               # width in Hz of total area to sample
        self.deltaf = None             # width in Hz of one fft bin (delta f)
        self.freq_step = None          # step in Hz between center frequencies
        self.min_freq = None           # lowest sampled frequency
        self.max_freq = None           # highest sampled frequency
        self.center_freqs = None       # cached nparray of center (tuned) freqs
        self.n_segments = None         # number of rf frontend retunes required
        self.bin_freqs = None          # cached nparray of all sampled freqs
        self.bin_start = None          # array index of first usable bin
        self.bin_stop = None           # array index of last usable bin
        self.bin_offset = None         # offset of start/stop index from center
        self.max_plotted_bin = None    # absolute max bin in bin_freqs to plot
        self.update()

        # commented-out windows require extra parameters that we're not set up
        # to handle at this time
        self.windows = {
            'Bartlett':         window.bartlett,
            'Blackman':         window.blackman,
            'Blackman2':        window.blackman2,
            'Blackman3':        window.blackman3,
            'Blackman4':        window.blackman4,
            'Blackman-Harris':  window.blackman_harris,
            'Blackman-Nuttall': window.blackman_nuttal,
            #'Cosine':           window.coswindow,
            #'Exponential':      window.exponential,
            'Flattop':          window.flattop,
            'Hamming':          window.hamming,
            'Hann':             window.hann,
            'Hanning':          window.hanning,
            #'Kaiser':           window.kaiser,
            'Nuttall':          window.nuttal,
            'Nuttall CFD':      window.nuttal_cfd,
            'Parzen':           window.parzen,
            'Rectangular':      window.rectangular,
            'Riemann':          window.riemann,
            'Welch':            window.welch
        }
        self.window = None # Name of window, set by set_window
        self.window_coefficients = None # Set by set_window
        self.set_window('Blackman-Harris')

    def set_wire_format(self, fmt):
        """Set the ethernet wire format between the USRP and host."""
        if fmt in consts.WIRE_FORMATS:
            self.wire_format = str(fmt) # ensure not unicode str

    def set_fft_size(self, size):
        """Set the fft size in bins (must be 2^n between 32 and 8192)."""
        if size in consts.FFT_SIZES:
            self.fft_size = size
        else:
            msg = "Unable to set fft size to {}, must be one of {!r}"
            self.logger.warn(msg.format(size, sorted(list(consts.FFT_SIZES))))

        self.logger.debug("fft size is {} bins".format(self.fft_size))

    def set_window(self, fn_name):
        """Set the window"""
        if fn_name in self.windows.keys():
            self.window = fn_name

        self.window_coefficients = self.windows[self.window](self.fft_size)

    def update(self):
        """Convencience function to update various variables and caches"""
        self.update_deltaf()
        self.update_freq_step()
        self.update_span()
        self.update_min_max_freq()
        self.update_tuned_freq_cache()
        self.update_bin_freq_cache()
        self.update_bin_indices()

    def update_deltaf(self):
        """Update the bin width"""
        self.deltaf = self.sample_rate / self.fft_size

    def update_freq_step(self):
        """Set the freq_step to a percentage of the actual data throughput.

        This allows us to discard bins on both ends of the spectrum.
        """
        self.freq_step = self.adjust_rate(self.sample_rate,
                                          self.deltaf,
                                          self.overlap)

    def update_span(self):
        """If no requested span, set max span using only one center frequency"""
        if self.requested_span:
            self.span = self.requested_span
        else:
            self.span = self.freq_step

    def update_min_max_freq(self):
        """Calculate actual start and end of requested span"""
        self.min_freq = self.center_freq - (self.span / 2) + (self.deltaf / 2)
        self.max_freq = self.min_freq + self.span - self.deltaf

    def update_tuned_freq_cache(self):
        """Cache center (tuned) frequencies.

        Sets:
          self.center_freqs     - array of all frequencies to be tuned
          self.n_segments       - length of self.center_freqs
        """
        # calculate min and max center frequencies
        min_fc = self.min_freq + (self.freq_step / 2)
        if self.span <= self.freq_step:
            self.center_freqs = np.array([min_fc])
        else:
            initial_n_segments = math.floor(self.span / self.freq_step)
            max_fc = min_fc + (initial_n_segments * self.freq_step)
            self.center_freqs = np.arange(min_fc, max_fc + 1, self.freq_step)

        self.n_segments = len(self.center_freqs)

    def update_bin_freq_cache(self):
        """Cache frequencies at the center of each FFT bin"""
        # cache all fft bin frequencies
        max_fc = self.center_freqs[-1]
        max_bin_freq = max_fc + (self.freq_step / 2)
        self.bin_freqs = np.arange(self.min_freq, max_bin_freq, self.deltaf)

    def update_bin_indices(self):
        """Update common indices used in cropping and overlaying DFTs"""
        self.bin_start = int(self.fft_size * (self.overlap / 2))
        self.bin_stop = int(self.fft_size - self.bin_start)
        self.max_plotted_bin = utils.find_nearest(self.bin_freqs, self.max_freq) + 1
        self.bin_offset = (self.bin_stop - self.bin_start) / 2

    @staticmethod
    def adjust_rate(samp_rate, deltaf, overlap):
        """Reduce rate by a user-selected percentage and round it.

        The adjusted sample size is used to calculate a smaller frequency
        step. This allows us to overlap a percentage of bins which are most
        affected by filter rolloff.

        The adjusted sample size is then rounded so that a whole number of bins
        of size deltaf go into it.
        """
        ratio_valid_bins = 1.0 - overlap
        return int(round((samp_rate * ratio_valid_bins) / deltaf) * deltaf)

    def export_to_matlab(self):
        """Export current configuration settings to .settings.mat"""
        e = """TODO: Export config and raw bin data, then use octave script to
               translate it into matlab format"""
        raise NotImplementedError(e)


# main
from processors import*
from utils import*
from statistics import*
import matplotlib.pyplot as plt

nb_iterations = 10

# Computations for the first version of the processor allocation algorithm (minimizing alpha)

#compute_and_save('regular','Results_V1/Regular/',nb_iterations,version=0)
#compute_and_save('density','Results_V1/Density/',nb_iterations,version=0)
#compute_and_save('Fat','Results_V1/Fat/',nb_iterations,version=0)
#compute_and_save('jump','Results_V1/Jump/',nb_iterations,version=0)
compute_and_save('n','Results_V1/n/',nb_iterations,version=0)
compute_and_save('p','Results_V1/P/',nb_iterations,version=0)

# Computations for the second version of the processor allocation algorithm (minimizing beta)

#compute_and_save('regular','Results_V3/Regular/',nb_iterations,version=1)
#compute_and_save('density','Results_V3/Density/',nb_iterations,version=1)
#compute_and_save('Fat','Results_V3/Fat/',nb_iterations,version=1)
#compute_and_save('jump','Results_V3/Jump/',nb_iterations,version=1)
compute_and_save('n','Results_V3/n/',nb_iterations,version=1)
compute_and_save('p','Results_V3/P/',nb_iterations,version=1)

# Displaying the results for the first version of the algorithm

#display_results('regular','Results_V1/Regular/')
#display_results('density','Results_V1/Density/')
#display_results('Fat','Results_V1/Fat/')
#display_results('jump','Results_V1/Jump/')
display_results('n','Results_V1/n/')
display_results('p','Results_V1/P/')

# Displaying the results for the second version of the algorithm

#display_results('regular','Results_V3/Regular/')
#display_results('density','Results_V3/Density/')
#display_results('Fat','Results_V3/Fat/')
#display_results('jump','Results_V3/Jump/')
display_results('n','Results_V3/n/')
display_results('p','Results_V3/P/')

# To compare the two version of the processor allocation algorithm

#display_multiple_results("V1","V3","Density","Merging_V1_and_V3")
#display_multiple_results("V1","V3","Fat","Merging_V1_and_V3")
#display_multiple_results("V1","V3","Jump","Merging_V1_and_V3")
#display_multiple_results("V1","V3","Regular","Merging_V1_and_V3")
display_multiple_results("V1","V3","n","Merging_V1_and_V3")
display_multiple_results("V1","V3","p","Merging_V1_and_V3")

# To compare the two version of the processor allocation algorithm with standard parameters

display_results_boxplot("V1","V3","Merging_V1_and_V3")


import copy
import unittest

from algoLabs.src.FloodFill import flood_fill

class TestFloodFill(unittest.TestCase):
    def test_basic_flood_fill(self):
        # Test Case 1: Basic test with a 3x3 matrix
        matrix1 = [
            ['A', 'A', 'A'],
            ['A', 'B', 'B'],
            ['A', 'B', 'B']
        ]
        start_x1, start_y1 = 1, 1
        target_color1 = 'B'
        replacement_color1 = 'C'
        expected_matrix1 = [
            ['A', 'A', 'A'],
            ['A', 'C', 'C'],
            ['A', 'C', 'C']
        ]
        flood_fill(matrix1, start_x1, start_y1, target_color1, replacement_color1)
        self.assertEqual(matrix1, expected_matrix1)

    def test_no_change_flood_fill(self):
        # Test Case 2: Test with a 4x4 matrix
        matrix2 = [
            ['A', 'B', 'B', 'B'],
            ['A', 'A', 'B', 'B'],
            ['B', 'A', 'A', 'B'],
            ['B', 'B', 'A', 'A']
        ]
        start_x2, start_y2 = 2, 3
        target_color2 = 'A'
        replacement_color2 = 'C'
        expected_matrix2 = [
            ['A', 'B', 'B', 'B'],
            ['A', 'A', 'B', 'B'],
            ['B', 'A', 'A', 'B'],
            ['B', 'B', 'A', 'A']
        ]

        # Create a deep copy of matrix2
        matrix_copy = copy.deepcopy(matrix2)

        flood_fill(matrix_copy, start_x2, start_y2, target_color2, replacement_color2)
        self.assertEqual(expected_matrix2, matrix_copy)

if __name__ == "__main__":
    unittest.main()


from collections import OrderedDict
import sys

import torch
from torch import nn
import torch.nn.init as nn_init
import torch.nn.functional as F
from torch.autograd import Variable

# CNN BASED MULTIDECODERS

# Simpler multidecoder design with convolutional encoder/decoder layers
class CNNMultidecoder(nn.Module):
    def __init__(self, freq_dim=40,
                       splicing=[5,5],
                       enc_channel_sizes=[],
                       enc_kernel_sizes=[],
                       enc_downsample_sizes=[],
                       enc_fc_sizes=[],
                       latent_dim=512,
                       dec_fc_sizes=[],
                       dec_channel_sizes=[],
                       dec_kernel_sizes=[],
                       dec_upsample_sizes=[],
                       activation="ReLU",
                       decoder_classes=[""],
                       use_batch_norm=False,
                       weight_init="xavier_uniform"):
        super(CNNMultidecoder, self).__init__()

        # Store initial parameters
        self.freq_dim = freq_dim
        self.splicing = splicing    # [left, right]
        self.time_dim = (sum(splicing) + 1)

        self.enc_channel_sizes = enc_channel_sizes
        self.enc_kernel_sizes = enc_kernel_sizes
        self.enc_downsample_sizes = enc_downsample_sizes
        self.enc_fc_sizes = enc_fc_sizes

        self.latent_dim = latent_dim

        self.dec_fc_sizes = dec_fc_sizes
        self.dec_channel_sizes = dec_channel_sizes
        self.dec_kernel_sizes = dec_kernel_sizes
        self.dec_upsample_sizes = dec_upsample_sizes

        self.activation = activation
        self.decoder_classes = decoder_classes
        self.use_batch_norm = use_batch_norm
        self.weight_init = weight_init

        # STEP 1: Construct encoder

        current_channels = 1
        current_height = self.time_dim
        current_width = self.freq_dim

        # Convolutional stage
        self.encoder_conv_layers = OrderedDict()
        for idx in range(len(enc_channel_sizes)):
            enc_channel_size = enc_channel_sizes[idx]
            enc_kernel_size = enc_kernel_sizes[idx]
            enc_downsample_size = enc_downsample_sizes[idx]

            # Pad signal to avoid edge effects in output
            padding = enc_kernel_size - 1
            self.encoder_conv_layers["conv2d_%d" % idx] = nn.Conv2d(current_channels,
                                                                    enc_channel_size,
                                                                    enc_kernel_size,
                                                                    padding=padding)
            self.init_weights(self.encoder_conv_layers["conv2d_%d" % idx], "conv2d")
            current_channels = enc_channel_size

            # Formula from http://pytorch.org/docs/master/nn.html#conv2d
            # Assumes stride = 1, dilation = 1
            current_height = (current_height + (2 * padding) - (enc_kernel_size - 1) - 1) + 1
            current_width = (current_width + (2 * padding) - (enc_kernel_size - 1) - 1) + 1

            if self.use_batch_norm:
                self.encoder_conv_layers["batchnorm2d_%d" % idx] = nn.BatchNorm2d(enc_channel_size)

            self.encoder_conv_layers["%s_%d" % (self.activation, idx)] = getattr(nn, self.activation)()

            if enc_downsample_size > 0:
                # Pool only in frequency direction (i.e. kernel and stride 1 in time dimension)
                # Return indices as well (useful for unpooling: see
                #   http://pytorch.org/docs/master/nn.html#maxunpool2d)
                self.encoder_conv_layers["maxpool2d_%d" % idx] = nn.MaxPool2d((1, enc_downsample_size),
                                                                              return_indices=True)

                # Formula from http://pytorch.org/docs/master/nn.html#maxpool2d
                # Assumes stride = enc_downsample_size (default), padding = 0, dilation = 1
                current_height = current_height     # No change in time dimension!
                current_width = int((current_width - (enc_downsample_size - 1) - 1) / enc_downsample_size) + 1

        self.encoder_conv = nn.Sequential(self.encoder_conv_layers)

        # Fully-connected stage
        self.encoder_fc_layers = OrderedDict()
        current_fc_dim = current_channels * current_height * current_width
        for idx in range(len(enc_fc_sizes)):
            enc_fc_size = enc_fc_sizes[idx]

            self.encoder_fc_layers["lin_%d" % idx] = nn.Linear(current_fc_dim, enc_fc_size)
            self.init_weights(self.encoder_fc_layers["lin_%d" % idx], self.activation)
            current_fc_dim = enc_fc_size

            if self.use_batch_norm:
                self.encoder_fc_layers["batchnorm1d_%d" % idx] = nn.BatchNorm1d(current_fc_dim)
            self.encoder_fc_layers["%s_%d" % (self.activation, idx)] = getattr(nn, self.activation)()

        self.encoder_fc_layers["lin_final"] = nn.Linear(current_fc_dim, self.latent_dim)
        self.init_weights(self.encoder_fc_layers["lin_final"], self.activation)
        # self.encoder_fc_layers["%s_final" % self.activation] = getattr(nn, self.activation)()
        self.encoder_fc = nn.Sequential(self.encoder_fc_layers)

        # STEP 2: Construct decoders

        self.decoder_fc = dict()
        self.decoder_fc_layers = dict()
        self.decoder_deconv = dict()
        self.decoder_deconv_layers = dict()

        # Save values from encoder stage
        input_channels = current_channels
        input_height = current_height
        input_width = current_width

        for decoder_class in self.decoder_classes:
            # Fully-connected stage
            self.decoder_fc_layers[decoder_class] = OrderedDict()
            current_fc_dim = self.latent_dim
            for idx in range(len(dec_fc_sizes)):
                dec_fc_size = dec_fc_sizes[idx]

                self.decoder_fc_layers[decoder_class]["%s_%d" % (self.activation, idx)] = getattr(nn, self.activation)()

                self.decoder_fc_layers[decoder_class]["lin_%d" % idx] = nn.Linear(current_fc_dim, dec_fc_size)
                self.init_weights(self.decoder_fc_layers[decoder_class]["lin_%d" % idx], self.activation)
                current_fc_dim = dec_fc_size

                if self.use_batch_norm:
                    self.decoder_fc_layers[decoder_class]["batchnorm1d_%d" % idx] = nn.BatchNorm1d(current_fc_dim)

            self.decoder_fc_layers[decoder_class]["%s_final" % self.activation] = getattr(nn, self.activation)()
            self.decoder_fc_layers[decoder_class]["lin_final"] = nn.Linear(current_fc_dim,
                                                                           input_channels * input_height * input_width)
            self.init_weights(self.decoder_fc_layers[decoder_class]["lin_final"], self.activation)

            self.decoder_fc[decoder_class] = nn.Sequential(self.decoder_fc_layers[decoder_class])
            self.add_module("decoder_fc_%s" % decoder_class, self.decoder_fc[decoder_class])

            # Deconvolution stage
            current_height = input_height
            current_width = input_width

            self.decoder_deconv_layers[decoder_class] = OrderedDict()
            for idx in range(len(dec_channel_sizes)):
                dec_channel_size = dec_channel_sizes[idx]
                dec_kernel_size = dec_kernel_sizes[idx]
                dec_upsample_size = dec_upsample_sizes[idx]

                self.decoder_deconv_layers[decoder_class]["%s_%d" % (self.activation, idx)] = getattr(nn, self.activation)()

                if dec_upsample_size > 0:
                    # Un-pool only in frequency direction (i.e. kernel and stride 1 in time dimension)
                    self.decoder_deconv_layers[decoder_class]["maxunpool2d_%d" % idx] = nn.MaxUnpool2d((1, dec_upsample_size))

                    # Formula from http://pytorch.org/docs/master/nn.html#maxunpool2d
                    # Assumes stride = dec_upsample_size (default), padding = 0, dilation = 1
                    current_height = current_height     # No change in time dimension!
                    current_width = current_width * dec_upsample_size

                output_channels = 1 if idx == len(dec_channel_sizes) - 1 else dec_channel_sizes[idx + 1]

                self.decoder_deconv_layers[decoder_class]["conv2d_%d" % idx] = nn.Conv2d(dec_channel_size,
                                                                        output_channels,
                                                                        dec_kernel_size)

                # Formula for length from http://pytorch.org/docs/master/nn.html#conv2d
                # Assumes stride = 1, dilation = 1
                current_height = current_height - (dec_kernel_size - 1)
                current_width = current_width - (dec_kernel_size - 1)

                if self.use_batch_norm and idx != len(dec_channel_sizes) - 1:
                    # Don't normalize if it's the output layer!
                    self.decoder_deconv_layers[decoder_class]["batchnorm2d_%d" % idx] = nn.BatchNorm2d(output_channels)

            self.decoder_deconv[decoder_class] = nn.Sequential(self.decoder_deconv_layers[decoder_class])
            self.add_module("decoder_deconv_%s" % decoder_class, self.decoder_deconv[decoder_class])

    def init_weights(self, layer, layer_name):
        if "xavier" in self.weight_init:
            try:
                gain = nn_init.calculate_gain(layer_name.lower())
                getattr(nn_init, self.weight_init)(layer.weight, gain=gain)
            except ValueError:
                # Happens if layer type isn't supported yet -- just use default gain
                getattr(nn_init, self.weight_init)(layer.weight)
        else:
            getattr(nn_init, self.weight_init)(layer.weight)

    def decoder_parameters(self, decoder_class):
        # Get parameters for just a specific decoder
        if decoder_class not in self.decoder_classes:
            print("Decoder class \"%s\" not found in decoders: %s" % (decoder_class, self.decoder_classes),
                  flush=True)
            sys.exit(1)
        decoder_deconv_parameters = self.decoder_deconv[decoder_class].parameters()
        for param in decoder_deconv_parameters:
            yield param
        decoder_fc_parameters = self.decoder_fc[decoder_class].parameters()
        for param in decoder_fc_parameters:
            yield param

    def encoder_parameters(self):
        # Get parameters for just the encoder
        encoder_fc_parameters = self.encoder_fc.parameters()
        for param in encoder_fc_parameters:
            yield param
        encoder_conv_parameters = self.encoder_conv.parameters()
        for param in encoder_conv_parameters:
            yield param

    def generator_parameters(self):
        # Get parameters for encoder and decoders (i.e., no adversaries)
        for decoder_class in self.decoder_classes:
            for param in self.decoder_parameters(decoder_class):
                yield param
        for param in self.encoder_parameters():
            yield param

    def encode(self, feats):
        # Need to go layer-by-layer to get pooling indices
        pooling_indices = []
        unpool_sizes = []
        conv_encoded = feats
        for i, (encoder_conv_layer_name, encoder_conv_layer) in enumerate(self.encoder_conv_layers.items()):
            if "maxpool2d" in encoder_conv_layer_name:
                unpool_sizes.append(conv_encoded.size())
                conv_encoded, new_pooling_indices = encoder_conv_layer(conv_encoded)
                pooling_indices.append(new_pooling_indices)
            else:
                conv_encoded = encoder_conv_layer(conv_encoded)
        fc_input_size = conv_encoded.size()
        conv_encoded_vec = conv_encoded.view(conv_encoded.size()[0], -1)

        return (self.encoder_fc(conv_encoded_vec), fc_input_size, unpool_sizes, pooling_indices)

    def decode(self, z, decoder_class, fc_input_size, conv_input_sizes=None, unpool_sizes=None, pooling_indices=None):
        fc_decoded = self.decoder_fc[decoder_class](z)
        fc_decoded_mat = fc_decoded.view(fc_input_size)

        # Need to go layer-by-layer to insert pooling indices into unpooling layers
        output = fc_decoded_mat
        for i, (decoder_deconv_layer_name, decoder_deconv_layer) in enumerate(self.decoder_deconv_layers[decoder_class].items()):
            if "maxunpool2d" in decoder_deconv_layer_name:
                current_pooling_indices = pooling_indices.pop()
                current_unpool_size = unpool_sizes.pop()
                output = decoder_deconv_layer(output,
                                              current_pooling_indices,
                                              output_size=current_unpool_size)
            else:
                output = decoder_deconv_layer(output)

        return output

    def forward_decoder(self, feats, decoder_class):
        latent, fc_input_size, unpool_sizes, pooling_indices = self.encode(feats.view(-1,
                                                                           1,
                                                                           self.time_dim,
                                                                           self.freq_dim))
        return self.decode(latent, decoder_class, fc_input_size, unpool_sizes=unpool_sizes, pooling_indices=pooling_indices)

# Includes an adversarial classifier for picking clean vs. dirty
class CNNDomainAdversarialMultidecoder(CNNMultidecoder):
    def __init__(self, freq_dim=40,
                       splicing=[5,5],
                       enc_channel_sizes=[],
                       enc_kernel_sizes=[],
                       enc_downsample_sizes=[],
                       enc_fc_sizes=[],
                       latent_dim=512,
                       dec_fc_sizes=[],
                       dec_channel_sizes=[],
                       dec_kernel_sizes=[],
                       dec_upsample_sizes=[],
                       activation="ReLU",
                       decoder_classes=[""],
                       use_batch_norm=False,
                       weight_init="xavier_uniform",
                       domain_adv_fc_sizes=[],
                       domain_adv_activation="Sigmoid"):
        super(CNNDomainAdversarialMultidecoder, self).__init__(freq_dim=freq_dim,
                                                         splicing=splicing,
                                                         enc_channel_sizes=enc_channel_sizes,
                                                         enc_kernel_sizes=enc_kernel_sizes,
                                                         enc_downsample_sizes=enc_downsample_sizes,
                                                         enc_fc_sizes=enc_fc_sizes,
                                                         latent_dim=latent_dim,
                                                         dec_fc_sizes=dec_fc_sizes,
                                                         dec_channel_sizes=dec_channel_sizes,
                                                         dec_kernel_sizes=dec_kernel_sizes,
                                                         dec_upsample_sizes=dec_upsample_sizes,
                                                         activation=activation,
                                                         decoder_classes=decoder_classes,
                                                         use_batch_norm=use_batch_norm,
                                                         weight_init=weight_init)

        self.domain_adv_fc_sizes = domain_adv_fc_sizes
        self.domain_adv_activation = domain_adv_activation

        # Construct domain_adversary
        # Simple linear classifier
        self.domain_adversary_layers = OrderedDict()
        current_dim = self.latent_dim
        for i in range(len(self.domain_adv_fc_sizes)):
            next_dim = self.domain_adv_fc_sizes[i]
            self.domain_adversary_layers["lin_%d" % i] = nn.Linear(current_dim, next_dim)
            self.domain_adversary_layers["%s_%d" % (self.domain_adv_activation, i)] = getattr(nn, self.domain_adv_activation)()
            current_dim = next_dim
        self.domain_adversary_layers["lin_final"] = nn.Linear(current_dim, 1)
        self.domain_adversary_layers["%s_final" % self.domain_adv_activation] = getattr(nn, self.domain_adv_activation)()
        self.domain_adversary = nn.Sequential(self.domain_adversary_layers)

    def domain_adversary_parameters(self):
        # Get parameters for just the domain_adversary
        domain_adversary_parameters = self.domain_adversary.parameters()
        for param in domain_adversary_parameters:
            yield param

# Includes an adversarial classifier for detecting real vs. fake utterances in each domain
class CNNGANMultidecoder(CNNMultidecoder):
    def __init__(self, freq_dim=40,
                       splicing=[5,5],
                       enc_channel_sizes=[],
                       enc_kernel_sizes=[],
                       enc_downsample_sizes=[],
                       enc_fc_sizes=[],
                       latent_dim=512,
                       dec_fc_sizes=[],
                       dec_channel_sizes=[],
                       dec_kernel_sizes=[],
                       dec_upsample_sizes=[],
                       activation="ReLU",
                       decoder_classes=[""],
                       use_batch_norm=False,
                       weight_init="xavier_uniform",
                       gan_fc_sizes=[],
                       gan_activation="Sigmoid"):
        super(CNNGANMultidecoder, self).__init__(freq_dim=freq_dim,
                                                 splicing=splicing,
                                                 enc_channel_sizes=enc_channel_sizes,
                                                 enc_kernel_sizes=enc_kernel_sizes,
                                                 enc_downsample_sizes=enc_downsample_sizes,
                                                 enc_fc_sizes=enc_fc_sizes,
                                                 latent_dim=latent_dim,
                                                 dec_fc_sizes=dec_fc_sizes,
                                                 dec_channel_sizes=dec_channel_sizes,
                                                 dec_kernel_sizes=dec_kernel_sizes,
                                                 dec_upsample_sizes=dec_upsample_sizes,
                                                 activation=activation,
                                                 decoder_classes=decoder_classes,
                                                 use_batch_norm=use_batch_norm,
                                                 weight_init=weight_init)

        self.gan_fc_sizes = gan_fc_sizes
        self.gan_activation = gan_activation

        # Construct adversary for each decoder class
        # Simple linear classifier
        self.gan_layers = dict()
        self.gans = dict()
        for decoder_class in self.decoder_classes:
            self.gan_layers[decoder_class] = OrderedDict()
            current_dim = self.freq_dim * self.time_dim
            for i in range(len(self.gan_fc_sizes)):
                next_dim = self.gan_fc_sizes[i]
                self.gan_layers[decoder_class]["lin_%d" % i] = nn.Linear(current_dim, next_dim)
                self.gan_layers[decoder_class]["%s_%d" % (self.gan_activation, i)] = getattr(nn, self.gan_activation)()
                current_dim = next_dim
            self.gan_layers[decoder_class]["lin_final"] = nn.Linear(current_dim, 1)
            # Skip in favor of more numerically stable BCEWithLogitsLoss
            # self.gan_layers[decoder_class]["Sigmoid_final"] = nn.Sigmoid()
            self.gans[decoder_class] = nn.Sequential(self.gan_layers[decoder_class])
            self.add_module("gan_%s" % decoder_class, self.gans[decoder_class])

    def gan_parameters(self, decoder_class):
        # Get parameters for just the adversary
        gan_parameters = self.gans[decoder_class].parameters()
        for param in gan_parameters:
            yield param

    def forward_gan(self, feats, decoder_class):
        return self.gans[decoder_class](feats.view((-1, self.time_dim * self.freq_dim)))

# Includes a phone classifier at the latent space
class CNNPhoneMultidecoder(CNNMultidecoder):
    def __init__(self, freq_dim=40,
                       splicing=[5,5],
                       enc_channel_sizes=[],
                       enc_kernel_sizes=[],
                       enc_downsample_sizes=[],
                       enc_fc_sizes=[],
                       latent_dim=512,
                       dec_fc_sizes=[],
                       dec_channel_sizes=[],
                       dec_kernel_sizes=[],
                       dec_upsample_sizes=[],
                       activation="ReLU",
                       decoder_classes=[""],
                       use_batch_norm=False,
                       weight_init="xavier_uniform",
                       phone_fc_sizes=[],
                       phone_activation="Sigmoid",
                       num_phones=1):
        super(CNNPhoneMultidecoder, self).__init__(freq_dim=freq_dim,
                                                splicing=splicing,
                                                enc_channel_sizes=enc_channel_sizes,
                                                enc_kernel_sizes=enc_kernel_sizes,
                                                enc_downsample_sizes=enc_downsample_sizes,
                                                enc_fc_sizes=enc_fc_sizes,
                                                latent_dim=latent_dim,
                                                dec_fc_sizes=dec_fc_sizes,
                                                dec_channel_sizes=dec_channel_sizes,
                                                dec_kernel_sizes=dec_kernel_sizes,
                                                dec_upsample_sizes=dec_upsample_sizes,
                                                activation=activation,
                                                decoder_classes=decoder_classes,
                                                use_batch_norm=use_batch_norm,
                                                weight_init=weight_init)

        self.phone_fc_sizes = phone_fc_sizes
        self.phone_activation = phone_activation
        self.num_phones = num_phones

        # Construct simple linear phone classifier
        self.phone_layers = OrderedDict()
        current_dim = self.latent_dim
        for i in range(len(self.phone_fc_sizes)):
            next_dim = self.phone_fc_sizes[i]
            self.phone_layers["lin_%d" % i] = nn.Linear(current_dim, next_dim)
            self.phone_layers["%s_%d" % (self.phone_activation, i)] = getattr(nn, self.phone_activation)()
            current_dim = next_dim
        self.phone_layers["lin_final"] = nn.Linear(current_dim, self.num_phones)
        self.phone_layers["LogSoftmax_final"] = nn.LogSoftmax(dim=1)
        self.phone_classifier = nn.Sequential(self.phone_layers)

    def generator_parameters(self):
        # Get parameters for generator and phone classifier
        for param in self.phone_classifier.parameters():
            yield param
        for decoder_class in self.decoder_classes:
            for param in self.decoder_parameters(decoder_class):
                yield param
        for param in self.encoder_parameters():
            yield param

    def forward_phones(self, feats):
        latent, fc_input_size, unpool_sizes, pooling_indices = self.encode(feats.view(-1,
                                                                           1,
                                                                           self.time_dim,
                                                                           self.freq_dim))

        return self.phone_classifier(latent)

# Includes a phone classifier at the output features -- trained end-to-end
class CNNEnd2EndMultidecoder(CNNMultidecoder):
    def __init__(self, freq_dim=40,
                       splicing=[5,5],
                       enc_channel_sizes=[],
                       enc_kernel_sizes=[],
                       enc_downsample_sizes=[],
                       enc_fc_sizes=[],
                       latent_dim=512,
                       dec_fc_sizes=[],
                       dec_channel_sizes=[],
                       dec_kernel_sizes=[],
                       dec_upsample_sizes=[],
                       activation="ReLU",
                       decoder_classes=[""],
                       use_batch_norm=False,
                       weight_init="xavier_uniform",
                       e2e_fc_sizes=[],
                       e2e_activation="Sigmoid",
                       num_phones=1):
        if len(decoder_classes) > 1 or decoder_classes[0] != "clean":
            raise RuntimeError("CNNEnd2EndMultidecoder only uses one decoder class (clean)")

        super(CNNEnd2EndMultidecoder, self).__init__(freq_dim=freq_dim,
                                                splicing=splicing,
                                                enc_channel_sizes=enc_channel_sizes,
                                                enc_kernel_sizes=enc_kernel_sizes,
                                                enc_downsample_sizes=enc_downsample_sizes,
                                                enc_fc_sizes=enc_fc_sizes,
                                                latent_dim=latent_dim,
                                                dec_fc_sizes=dec_fc_sizes,
                                                dec_channel_sizes=dec_channel_sizes,
                                                dec_kernel_sizes=dec_kernel_sizes,
                                                dec_upsample_sizes=dec_upsample_sizes,
                                                activation=activation,
                                                decoder_classes=decoder_classes,
                                                use_batch_norm=use_batch_norm,
                                                weight_init=weight_init)

        self.e2e_fc_sizes = e2e_fc_sizes
        self.e2e_activation = e2e_activation
        self.num_phones = num_phones

        # Construct simple linear phone classifier on top of reconstruction layer
        self.phone_layers = OrderedDict()
        current_dim = self.time_dim * self.freq_dim
        for i in range(len(self.e2e_fc_sizes)):
            next_dim = self.e2e_fc_sizes[i]
            self.phone_layers["lin_%d" % i] = nn.Linear(current_dim, next_dim)
            self.phone_layers["%s_%d" % (self.e2e_activation, i)] = getattr(nn, self.e2e_activation)()
            current_dim = next_dim
        self.phone_layers["lin_final"] = nn.Linear(current_dim, self.num_phones)
        self.phone_layers["LogSoftmax_final"] = nn.LogSoftmax(dim=1)
        self.phone_classifier = nn.Sequential(self.phone_layers)

    def generator_parameters(self):
        # Get parameters for generator and phone classifier
        for param in self.phone_classifier.parameters():
            yield param
        for param in self.decoder_parameters("clean"):
            yield param
        for param in self.encoder_parameters():
            yield param

    def forward_phones(self, feats):
        enhanced_feats = self.forward_decoder(feats, "clean")
        return self.phone_classifier(enhanced_feats.view((-1, self.time_dim * self.freq_dim)))


import os
import subprocess

repo_root = subprocess.check_output(["git", "rev-parse", "--show-toplevel"]).decode().strip()

from setuptools import setup, Extension
from torch.utils import cpp_extension

def compile_cpp_extension(extension_name, cpp_source_rel_paths, cpp_header_rel_paths, is_cuda_extension):
    abs_to_rel = lambda rel_path_list : [os.path.abspath(os.path.join(os.path.dirname(__file__), x)) for x in rel_path_list]

    cpp_source_abs_paths = abs_to_rel(cpp_source_rel_paths)
    assert all([os.path.exists(x) for x in cpp_source_abs_paths]), "Cannot locate all source files"

    cpp_header_abs_paths = abs_to_rel(cpp_header_rel_paths) if cpp_header_rel_paths else []
    assert all([os.path.exists(x) for x in cpp_header_abs_paths]), "Cannot locate all header files"

    ext_module = cpp_extension.CUDAExtension if is_cuda_extension else cpp_extension.CppExtension
    setup(name=extension_name,
        ext_modules=[
            ext_module(
                name=extension_name,
                sources=cpp_source_abs_paths,
                extra_compile_args=
                    [f"-I{include_path}" for include_path in cpp_header_abs_paths] +
                    ["-DCOMPILE_THROUGH_PYTORCH"]
            )
        ],
        cmdclass={'build_ext': cpp_extension.BuildExtension}
    )

if __name__ == "__main__":
    # Use ccache to speed up compilations
    os.environ["CC"] = os.path.join(repo_root, '../ccache-4.7.4-linux-x86_64/g++')

    extensions_cpp_sources = {
        "dummy_conv_cpu": {
            "sources": [
                os.path.join(repo_root, 'cuda/dummy_cpu/src/dummy_convolution.cpp')
            ],
            "headers": [],
            "is_cuda_extension": False,
        },
        "baseline_conv_cpu": {
            "sources": [
                os.path.join(repo_root, 'cuda/baseline_cpu/src/convolution.cpp')
            ],
            "headers": [],
            "is_cuda_extension": False,
        },
        "baseline_conv_gpu": {
            "sources": [
                os.path.join(repo_root, 'cuda/baseline_gpu/src/convolution.cu'),
            ],
            "headers": [],
            "is_cuda_extension": True,
        },
        "shapeshifter_conv_gpu": {
            "sources": [
                os.path.join(repo_root, 'cuda/shapeshifter_gpu/src/convolution.cu'),
            ],
            "headers": [],
            "is_cuda_extension": True,
        },
        "tensor_wrappers": {
            "sources": [
                os.path.join(repo_root, 'cuda/utils/pybind/QTensorWrappers.pybind.cpp'),
            ],
            "headers": [],
            "is_cuda_extension": False,
        }
    }

    common_sources = [
        os.path.join(repo_root, 'cuda/utils/src/Conv2dMetadata.cpp'),
        os.path.join(repo_root, 'cuda/utils/src/BaseQTensor.cpp'),
        os.path.join(repo_root, 'cuda/utils/src/UncompressedQTensor.cpp'),
        os.path.join(repo_root, 'cuda/utils/src/ShapeShifterCompressedQTensor.cpp'),
    ]
    common_headers = [
        os.path.join(repo_root, 'cuda/utils/h/'),
    ]

    for ext_name, ext_params in extensions_cpp_sources.items():
        sources = ext_params["sources"] + common_sources
        headers = ext_params["headers"] + common_headers
        is_cuda_extension = ext_params["is_cuda_extension"]
        print(f"Compiling extension: {ext_name}")
        try:
            compile_cpp_extension(ext_name, sources, headers, is_cuda_extension)
        except Exception as e:
            print("Compilation failed")
            print(e)
            break


import os
from typing import (
    Dict,
    List,
)

ZERO_BYTES32 = b'\x00' * 32

# Execution-spec constants taken from https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md
DOMAIN_DEPOSIT = bytes.fromhex('03000000')
DOMAIN_BLS_TO_EXECUTION_CHANGE = bytes.fromhex('0A000000')
BLS_WITHDRAWAL_PREFIX = bytes.fromhex('00')
ETH1_ADDRESS_WITHDRAWAL_PREFIX = bytes.fromhex('01')

ETH2GWEI = 10 ** 9
MIN_DEPOSIT_AMOUNT = 2 ** 0 * ETH2GWEI
MAX_DEPOSIT_AMOUNT = 2 ** 5 * ETH2GWEI

# File/folder constants
WORD_LISTS_PATH = os.path.join('staking_deposit', 'key_handling', 'key_derivation', 'word_lists')
DEFAULT_VALIDATOR_KEYS_FOLDER_NAME = 'validator_keys'
DEFAULT_BLS_TO_EXECUTION_CHANGES_FOLDER_NAME = 'bls_to_execution_changes'

# Internationalisation constants
INTL_CONTENT_PATH = os.path.join('staking_deposit', 'intl')

def _add_index_to_options(d: Dict[str, List[str]]) -> Dict[str, List[str]]:
    '''
    Adds the (1 indexed) index (in the dict) to the first element of value list.
    eg. {'en': ['English', 'en']} -> {'en': ['1. English', '1', 'English', 'en']}
    Requires dicts to be ordered (Python > 3.6)
    '''
    keys = list(d.keys())  # Force copy dictionary keys top prevent iteration over changing dict
    for i, key in enumerate(keys):
        d.update({key: ['%s. %s' % (i + 1, d[key][0]), str(i + 1)] + d[key]})
    return d

INTL_LANG_OPTIONS = _add_index_to_options({
    'ar': ['العربية', 'ar', 'Arabic'],
    'el': ['ελληνικά', 'el', 'Greek'],
    'en': ['English', 'en'],
    'fr': ['Français', 'Francais', 'fr', 'French'],
    'id': ['Bahasa melayu', 'Melayu', 'id', 'Malay'],
    'it': ['Italiano', 'it', 'Italian'],
    'ja': ['日本語', 'ja', 'Japanese'],
    'ko': ['한국어', '조선말', '韓國語', 'ko', 'Korean'],
    'pt-BR': ['Português do Brasil', 'Brasil', 'pt-BR', 'Brazilian Portuguese'],
    'ro': ['român', 'limba română', 'ro', 'Romainian'],
    'tr': ['Türkçe', 'tr', 'Turkish'],
    'zh-CN': ['简体中文', 'zh-CN', 'zh', 'Chinease'],
})
MNEMONIC_LANG_OPTIONS = _add_index_to_options({
    'chinese_simplified': ['简体中文', 'zh', 'zh-CN', 'Chinese Simplified'],
    'chinese_traditional': ['繁體中文', 'zh-tw', 'Chinese Traditional'],
    'czech': ['čeština', 'český jazyk', 'cs', 'Czech'],
    'english': ['English', 'en'],
    'italian': ['Italiano', 'it', 'Italian'],
    'korean': ['한국어', '조선말', '韓國語', 'ko', 'Korean'],
    # Portuguese mnemonics are in both pt & pt-BR
    'portuguese': ['Português', 'Português do Brasil', 'pt', 'pt-BR', 'Portuguese'],
    'spanish': ['Español', 'es', 'Spanish'],
})

# Sundry constants
UNICODE_CONTROL_CHARS = list(range(0x00, 0x20)) + list(range(0x7F, 0xA0))