import numpy as np
import os

def batch_make(batchsize,max_num=2400):
    texts=[]
    mels=[]
    inputs=[]
    mellens=[]
    textlens=[]
    npy_path='./kaede/'
    npy_list = os.listdir(npy_path)
    for _ in range(batchsize):
        filename=np.random.choice(npy_list)
        number=filename[:-7]
        mel_name=npy_path+number+'mel.npy'
        txt_name=npy_path+number+'txt.npy'

        mel=np.load(mel_name)
        mel=mel.astype(np.float32)
        mels.append(mel)
        mellens.append(mel.shape[1])

        x=np.zeros((mel.shape[0],1)).astype(np.float32)
        x=np.concatenate((x,mel[:,:-1]),axis=1)
        inputs.append(x)

        text=np.load(txt_name)
        text=text.astype(np.int32)
        texts.append(text)
        textlens.append(text.shape[0])

        cmels=[]
        ctxts=[]
        cxs=[]

    for mel,x,txt in zip(mels, inputs, texts):
        cmel=np.pad(mel,((0, 0), (0, max(mellens)-mel.shape[1])),'constant',constant_values=0)
        cx=np.pad(x,((0, 0), (0, max(mellens)-x.shape[1])),'constant',constant_values=0)
        ctxt=np.pad(txt,(0,max(textlens)-txt.shape[0]),'constant',constant_values=31)

        cmels.append(cmel)
        ctxts.append(ctxt)
        cxs.append(cx)

    mels=np.array(cmels)
    inputs=np.array(cxs)
    txts=np.array(ctxts)

    return txts,inputs,mels,textlens,mellens


'''
Reference File for building CNN
'''

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data', one_hot=True, reshape=False)

X = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])
Y_Label = tf.placeholder(tf.float32, shape=[None,10])

#커널(필터)은 (4x4x1)의 필터를 4장 사용하기 위해 shape을 설정하고, tf.truncated_normal()을 통해 초기화 (initialize)
#이 Kernel이 학습이 될 변수 (Weight 값)을 의미함 -> 계속 업데이트될 변수이기 때문에 tf.Variable로 지정
Kernel1 = tf.Variable(tf.truncated_normal(shape=[4,4,1,4], stddev=0.1))

#이미지와 커널을 Convolution한 이후 같은 사이즈 만큼 더해주기 위핸 변수를 의미, 커널이 4장 있었기 때문에 똑같이 shape=[4]
Bias1 = tf.Variable(tf.truncated_normal(shape=[4], stddev=0.1))

#Convolution 연산 시작
#X라는 이미지에 Kernel1 값을 그대로 컨볼루젼 곱을 실행하고, 패딩 사이즈는 출력 사이즈에 맞게 알아서 세팅됨
Conv1 = tf.nn.conv2d(X, Kernel1, strides=[1,1,1,1], padding='SAME') + Bias1

#ReLU Activation Function
Activation1 = tf.nn.relu(Conv1)

#Max_Pooling 사용
Pool1 = tf.nn.max_pool(Activation1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

#첫 번째 Convolution Layer와 유사하게 기능
Kernel2 = tf.Variable(tf.truncated_normal(shape=[4,4,4,8], stddev=0.1))
Bias2 = tf.Variable(tf.truncated_normal(shape=[8], stddev=0.1))
Conv2 = tf.nn.conv2d(Pool1, Kernel2, strides=[1,1,1,1], padding='SAME') + Bias2
Activation2 = tf.nn.relu(Conv2)
Pool2 = tf.nn.max_pool(Activation2, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

W1 = tf.Variable(tf.truncated_normal(shape=[8*7*7,10]))
B1 = tf.Variable(tf.truncated_normal(shape=[10]))
Pool2_flat = tf.reshape(Pool2, [-1, 8*7*7])
OutputLayer = tf.matmul(Pool2_flat, W1) + B1

Loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y_Label, logits=OutputLayer))
train_step = tf.train.AdamOptimizer(0.005).minimize(Loss)

correct_prediction = tf.equal(tf.argmax(OutputLayer, 1), tf.argmax(Y_Label, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
    print("Start....")
    sess.run(tf.global_variables_initializer())
    for i in range(10000):
        trainingData, Y = mnist.train.next_batch(64)
        sess.run(train_step, feed_dict={X: trainingData, Y_Label: Y})
        if i % 100 :
            print(sess.run(accuracy, feed_dict={X: mnist.test.images, Y_Label: mnist.test.labels}))


# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import ruamel.yaml.comments
import six
import warnings

import orquesta.expressions.base

from orquestaconvert.expressions import jinja
from orquestaconvert.expressions import yaql as yql
from orquestaconvert.utils import type_utils

class ExpressionConverter(object):

    @classmethod
    def convert(cls, expr, **kwargs):
        if (isinstance(expr, type_utils.dict_types)):
            return cls.convert_dict(expr, **kwargs)
        elif isinstance(expr, list):
            return cls.convert_list(expr, **kwargs)
        elif isinstance(expr, six.string_types):
            return cls.convert_string(expr, **kwargs)
        elif isinstance(expr, bool):
            return expr
        elif expr is None:
            # Note: The only point to explicitly converting None is to skip
            #       emitting the warning. Otherwise we would remove this elif
            #       and let the function return the input. Also, ruamel doesn't
            #       explicitly serialize null to None, it just leaves the key
            #       blank (in other words, it "implicitly" serializes it).
            #       Example:
            #
            #           next:
            #             - when: ...
            #               publish:
            #                 - continue:
            #               ...
            #
            #       See this link for more information:
            #       https://bitbucket.org/ruamel/yaml/issues/169/roundtripdumper-dumps-null-values
            return None
        elif isinstance(expr, int):
            return expr
        else:
            warnings.warn("Could not recognize expression '{}'; results may not "
                          "be accurate.".format(expr), SyntaxWarning)
            return expr

    @classmethod
    def expression_type(cls, expr):
        for name, evaluator in six.iteritems(orquesta.expressions.base.get_evaluators()):
            if evaluator.has_expressions(str(expr)):
                return name
        return None

    @classmethod
    def get_converter(cls, expr):
        expr_type = cls.expression_type(expr)
        if expr_type == 'jinja':
            return jinja.JinjaExpressionConverter
        elif expr_type == 'yaql':
            return yql.YaqlExpressionConverter
        return None

    @classmethod
    def unwrap_expression(cls, expr):
        converter = cls.get_converter(expr)
        if converter:
            return converter.unwrap_expression(expr)
        # this isn't a Jinja or YAQL expression, so return the raw string
        return expr

    @classmethod
    def convert_string(cls, expr, **kwargs):
        # - task('xxx').result -> result()
        #    if 'xxx' != current task name, error
        # - _. -> ctx().
        # - $. -> ctx().
        # - st2kv. -> st2kv('xxx')
        # others?
        converter = cls.get_converter(expr)
        if converter:
            return converter.convert_string(expr, **kwargs)
        # this isn't a Jinja or YAQL expression, so return the raw string
        return expr

    @classmethod
    def convert_dict(cls, expr_dict, **kwargs):
        converted = ruamel.yaml.comments.CommentedMap()
        for k, expr in six.iteritems(expr_dict):
            converted[cls.convert(k, **kwargs)] = cls.convert(expr, **kwargs)
        return converted

    @classmethod
    def convert_list(cls, expr_list, **kwargs):
        return [cls.convert(expr, **kwargs) for expr in expr_list]


'''
    Simple demo that get the number of highway
'''

import osmium as o
import sys

if o:
    print('Success to load osmium!\n')
else:
    print('Failed to load osmium\n')

class HighwayInfoHandler(o.SimpleHandler):
    def __init__(self):
        o.SimpleHandler.__init__(self)
        self.way_num = 0
        self.highway_num = 0

    def count_highway(self, tags):
        if 'highway' in tags:
            self.highway_num += 1

    def way(self, w):
        self.way_num += 1
        self.count_highway(w.tags)

def main(osmfile):
    infoHandler = HighwayInfoHandler()
    infoHandler.apply_file(osmfile)
    print('Way number: %d ' %infoHandler.way_num)
    print('Highway number: %d ' %infoHandler.highway_num)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('Usage: python %s <osmfile>' % sys.argv[0])
        sys.exit(-1)

    exit(main(sys.argv[1]))


#! /usr/bin/python

import json
import requests

url = 'http://127.0.0.1:8080/wm/onos/datagrid/add/intents/json'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

for i in range(6,16):
	srcMac = '00:00:00:00:00:'+ str(hex(i)[2:]).zfill(2)
	dstMac = '00:00:00:00:00:'+ str(hex(i+10)[2:])
	srcSwitch = '00:00:00:00:00:00:10:'+ str(i).zfill(2)
	dstSwitch = '00:00:00:00:00:00:20:'+ str(i+25)
	srcPort = 1
	dstPort = 1

	intent = [{'intent_id': '%d' %(i),'intent_type':'shortest_intent_type','intent_op':'add','srcSwitch':srcSwitch,'srcPort':srcPort,'srcMac':srcMac,'dstSwitch':dstSwitch,'dstPort':dstPort,'dstMac':dstMac}]
	r = requests.post(url, data=json.dumps(intent, sort_keys=True), headers = headers)
	#print json.dumps(intent, sort_keys = True)

	intent = [{'intent_id': '%d' %(i+10),'intent_type':'shortest_intent_type','intent_op':'add','srcSwitch':dstSwitch,'srcPort':dstPort,'srcMac':dstMac,'dstSwitch':srcSwitch,'dstPort':srcPort,'dstMac':srcMac}]
	#print json.dumps(intent, sort_keys = True)
	r = requests.post(url, data=json.dumps(intent, sort_keys=True), headers = headers)


from Day2 import getPuzzleinput
from Day4 import customiter
import re

def reaction(polymer):
    # polymercopy=polymer
    reactive=True
    while reactive:

        index=0
        startlen=len(polymer)
        while index < len(polymer)-1:
            if polymer[index].lower()==polymer[index+1].lower() and polymer[index] != polymer[index+1]:
                del polymer[index + 1]
                del polymer[index]

            else:
                pass
            index+=1
        endlen=len(polymer)
        if startlen==endlen:
            reactive=False

    return polymer

def badunit(reducedpolymer):
    char='abcdefghijklmnopqrstuvwxyz'
    polymerlength={}
    for c in char:
        reduced=[i for i in reducedpolymer if i.casefold() != c]
        #reduced=re.sub('c','',reducedpolymer)
        shortpoly=reaction(reduced)
        polymerlength[c]=len(shortpoly)
    return polymerlength
if __name__=="__main__":

    string=getPuzzleinput(5)
    string=[i for i in string[0]]
    #string=['a','a','b','c','C','c','d','D','B','A','x']
    # polymerraw=getPuzzleinput(5)[0]
    # polymer=[i for i in polymerraw]
    # # twoiters=customiter(polymer)
    reaction(string)
    bestdelete=badunit(string)


#!/usr/bin/env python

from __future__ import (
    absolute_import,
    division,
    print_function,
    unicode_literals,
)

import ast
import collections

Flake8Result = collections.namedtuple(
    'Flake8Result',
    ['lineno', 'col_offset', 'message']
)

class BaseLinter(ast.NodeVisitor):
    def __init__(self, *args, **kwargs):
        self.results = []

        super(BaseLinter, self).__init__(*args, **kwargs)

    def get_results(self):

        return self.results


#!/usr/bin/env python3

from __future__ import print_function

import datetime
import functools
import os
import socket
import sys
import time

import packet

project = os.environ["PACKET_PROJECT_ID"]
token = os.environ["PACKET_API_TOKEN"]
hostname = os.environ["DEVICE_HOSTNAME"]
ipxe_script_url = os.environ["DEVICE_IPXE_SCRIPT_URL"]
plan = os.environ["DEVICE_PLAN"]
facility = os.environ["DEVICE_FACILITY"]

timeout = 600

if sys.version_info[0] == 2:
    oldprint = print

    def myprint(*args, **kwargs):
        flush = kwargs.pop("flush", False)
        f = kwargs.get("file", sys.stdout)

        oldprint(*args, **kwargs)

        if flush:
            f.flush()

    print = functools.update_wrapper(myprint, print)

print = functools.partial(print, hostname + ":", flush=True)

class Device:
    def __init__(self, manager):
        self.m = manager
        self.dev = None
        self.id = None
        self.ip = None

    def __until(self, func):
        """
        Runs `func` in a loop until timeout or func returns Falsy. Will handle
        504 errors in a way that makes sense. Stop is indicated as Falsy so that
        funcs do not have to explicitly return anything, Python's implicit None
        will break the loop.
        """
        end = time.time() + timeout
        while end > time.time():
            try:
                if not func():
                    return
            except packet.baseapi.Error as e:
                if "504" in str(e):
                    print("504")
                    time.sleep(30)
                    continue
                print(e)
                sys.exit(1)

            time.sleep(10)

        print("timed out")
        sys.exit(1)

    def create(self, project, hostname, plan, facility, ipxe_script_url):
        def __create():
            tt = datetime.datetime.utcnow() + datetime.timedelta(hours=2)
            d = self.m.create_device(
                project,
                hostname,
                plan,
                facility,
                "custom_ipxe",
                ipxe_script_url=ipxe_script_url,
                spot_instance=True,
                spot_price_max=20,
                termination_time=tt.isoformat(),
            )

            self.dev = d
            self.id = d.id

        self.__until(__create)

    def refresh(self):
        def __refresh():
            d = self.m.get_device(self.id)
            self.dev = d
            if d.ip_addresses and not self.ip:
                ips = [
                    ip
                    for ip in d.ip_addresses
                    if ip["address_family"] == 4 and ip["public"]
                ]
                if ips:
                    self.ip = ips[0]["address"]

        self.__until(__refresh)

    def state(self):
        self.refresh()
        return self.dev.state

    def wait_for_ssh(self):
        def __wait_for_ssh():
            if self.state() != "active":
                print(self, "state is not active")
                return

            s = socket.socket()
            s.settimeout(10)
            try:
                s.connect((self.ip, 22))
                msg = s.recv(100).decode()
            except socket.error:
                return True

            if "ssh" in msg.lower():
                print(self, msg.strip())
                return

            print(self, "not ssh greeting")

        self.__until(__wait_for_ssh)

    def delete(self):
        def __delete():
            self.dev.delete()

        self.__until(__delete)

    def __repr__(self):
        state = None
        if self.dev:
            state = self.dev.state
        return "{} {} {}".format(self.id, state, self.ip)

def main():
    print("instantiating manager")
    m = packet.Manager(token)
    print("instantiating device")
    d = Device(m)
    print("creating device")
    d.create(project, hostname, plan, facility, ipxe_script_url)
    start = time.time()
    print(d)

    state = None
    while True:
        state, oldstate = d.state(), state
        if state != oldstate:
            print(d)
        if state == "active":
            break
        time.sleep(30)

    d.wait_for_ssh()
    print(d, "time-to-active", time.time() - start)
    print(d, "deleting")
    d.delete()
    print(d, "test-time", time.time() - start)

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(hostname + ":", e)


import numpy as np
import pandas as pd
import glob
from sys import platform

#importing KERAS
import keras
from keras.layers import Embedding, Input, Flatten, Dense, Activation
from keras.models import Model, Sequential
from keras.optimizers import SGD
from keras.utils import to_categorical
from keras.wrappers.scikit_learn import KerasClassifier

from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve
from sklearn.metrics import auc

import matplotlib
from matplotlib import pyplot as plt

#=========================data import and preprocessing
def load_data(dnnType,varlist):

    if platform == "linux" or platform == "linux2":
        pathwithwildcard = '../csv/2017/forBDTtraining/*/*.csv'
    elif platform == "darwin":
        pathwithwildcard = '../csv/2017/forBDTtraining/*/*.csv'
    elif platform == "win32":
        pathwithwildcard = '..\\csv\\2017\\forBDTtraining\\*\\*.csv'

    paths = glob.glob(pathwithwildcard)
    df1_signal_dict = {}
    df1_TT_dict = {}
    df1_TTV_dict = {}

    for path in paths:
        if 'ttHToNonbb' in path:
            df1_signal_dict[path] = pd.read_csv(path)
    for path in paths:
        if not (('ttHToNonbb' in path) or ('PSweights' in path)):
            if 'TTTo' in path:
                df1_TT_dict[path] = pd.read_csv(path)
            elif 'TTW' in path or 'TTZ' in path:
                df1_TTV_dict[path] = pd.read_csv(path)
            else:
                continue

    tmp_sig = []
    for keys in df1_signal_dict.keys():
        tmp_sig.append(df1_signal_dict[keys])
    tmp_TT = []
    for keys in df1_TT_dict.keys():
        tmp_TT.append(df1_TT_dict[keys])
    tmp_TTV = []
    for keys in df1_TTV_dict.keys():
        tmp_TTV.append(df1_TTV_dict[keys])
    df1_signal = pd.concat(tmp_sig)
    df1_TT = pd.concat(tmp_TT)
    df1_TTV = pd.concat(tmp_TTV)

    print (df1_signal.shape, df1_TT.shape, df1_TTV.shape)

    df1_signal = df1_signal[varlist]
    df1_signal_target = [0]*df1_signal.shape[0]
    df1_TT = df1_TT[varlist]
    df1_TT_target = [1]*df1_TT.shape[0]
    df1_TTV = df1_TTV[varlist]
    df1_TTV_target = [1]*df1_TTV.shape[0]

    tmp0 = []
    if dnnType == 'TT':
        tmp0 = [df1_signal,df1_TT]
        target = df1_signal_target+df1_TT_target
    if dnnType == 'TTV':
        tmp0 = [df1_signal,df1_TTV]
        target = df1_signal_target+df1_TTV_target
    if dnnType == 'sum':
        tmp0 = [df1_signal,df1_TT,df1_TTV]
        target = df1_signal_target+df1_TT_target+df1_TTV_target

    df1 = pd.concat(tmp0)
    return df1, target

#===========================data training

def train_pyKeras(df1, target, descrip, num_epochs, sizeofepoch):
    df1_train, df1_test, df1_train_target, df1_test_target = train_test_split(df1, target, test_size=0.5)

    df1_train_target_cat = to_categorical(df1_train_target)
    df1_test_target_cat = to_categorical(df1_test_target)

    print ('(#events,#vars)[train, test]=', df1_train_target_cat.shape, df1_train.shape, df1_test.shape, df1_test_target_cat.shape)

    print (df1_train.columns.values)

    #===============================defining keras model
    model = Sequential()

    for iterator in range(0,len(descrip)):
        if iterator == 0:
            model.add(Dense(descrip[iterator],activation='relu',input_dim=len(varlist)))
            continue
        elif iterator == len(descrip)-1:
            model.add(Dense(descrip[iterator],activation='softmax'))
            break
        else:
            model.add(Dense(descrip[iterator],activation='relu'))

    model.summary()

    model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['binary_accuracy'])

    model.fit(df1_train,df1_train_target_cat,
                 batch_size=sizeofepoch,
                 epochs=num_epochs,
                 validation_data=(df1_test,df1_test_target_cat),
                 verbose = 1
                 )

    #===================================roc curve
    fpr_keras, tpr_keras, thresholds_keras = roc_curve(df1_test_target_cat[:,0],model.predict(df1_test)[:,0])
    fpr_keras_train, tpr_keras_train, thresholds_keras_train = roc_curve(df1_train_target_cat[:,0],model.predict(df1_train)[:,0])
    auc_keras = auc(fpr_keras, tpr_keras)
    auc_keras_train = auc(fpr_keras_train, tpr_keras_train)
    plt.figure(1)
    plt.plot(fpr_keras, tpr_keras, label='pyKeras_test (area = {:.3f})'.format(auc_keras))
    plt.plot(fpr_keras_train, tpr_keras_train, label='pyKeras_train (area = {:.3f})'.format(auc_keras_train))
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.title('ROC curve')
    plt.legend(loc='best')
    #plt.savefig('pyKeras_batch_size'+str(sizeofepoch)+'_epochs'+str(num_epochs)+'__'+str(len(varlist))+'vars'+'__depth'+str(len(descrip))+'.pdf')
    plt.show()
    return model, plt

#========================variable selection
varlist=[
    #'AK12_lead_mass',
    #'AK12_lead_pt',
    #'DR_AK12_tau',
    'avg_dr_jet',
    'b1_loose_pt',
    'b1_pt',
    'b2_loose_pt',
    'b2_pt',
    #'detabb',
    #'detabb_loose',
    'dr_lep1_tau_os',
    'dr_leps',
    'drbb',
    'drbb_loose',
    'htmiss',
    'lep1_conePt',
    'lep1_eta',
    'lep1_fake_prob',
    'lep1_pt',
    'lep2_conePt',
    'lep2_eta',
    'lep2_genLepPt',
    'lep2_pt',
    'mT_lep1',
    'mT_lep2',
    'mTauTauVis',
    'max_lep_eta',
    'mbb',
    'mbb_loose',
    'minDR_AK12_L',
    'minDR_AK12_lep',
    'minDR_HTTv2_L',
    'minDR_HTTv2_lep',
    'minDR_HTTv2_tau',
    'mindr_lep1_jet',
    'mindr_lep2_jet',
    'mindr_tau_jet',
    'ptbb',
    'ptbb_loose',
    'ptmiss',
    'tau_eta',
    'tau_mva',
    'tau_pt',
    'N_jetAK12',
    'nBJetLoose',
    'nJet',
    'nMuon'
]

dnnType = 'TT'
descrip = [100,10,2]
num_epochs = 25
sizeofepoch = 100
filename = dnnType+'pyKeras_batch_size'+str(sizeofepoch)+'_epochs'+str(num_epochs)+'__'+str(len(varlist))+'vars'+'__depth'+str(len(descrip))+'.pdf'

data_from_dataloader = load_data(dnnType,varlist)
hist = train_pyKeras(data_from_dataloader[0], data_from_dataloader[1], descrip, num_epochs, sizeofepoch )
hist[1].savefig(filename)


import responder
from starlette.websockets import WebSocket, WebSocketDisconnect
from typing import Dict
import asyncio
from threading import Thread, Lock
from queue import Queue, Empty, Full

class WebSocketServer(object):
    def __init__(self, *, address: str = '0.0.0.0', port: int = 8080, location: str = '/'):
        self.address = address
        self.port = port
        self.location = location

        self.clients: Dict[str, WebSocket] = {}
        self.locker = Lock()

        self.elo = asyncio.get_event_loop()  # Eventloop Object
        self.bcPutTimeoutSecs = 5
        self.bcGetTimeoutSecs = 5
        self.bcCounter = 0
        self.bcQueue = Queue()  # Queue for message
        self.bcThread = Thread(target=self._bcWatcher, daemon=True)
        self.bcThread.start()

        self.api = responder.API()
        self.api.add_route(route=self.location, endpoint=self.wsSession, websocket=True)

        self.api.run(address=self.address, port=self.port)

    async def wsSession(self, ws: WebSocket):
        await ws.accept()
        key = ws.headers['sec-websocket-key']
        with self.locker:
            if key not in self.clients.keys():
                self.clients[key] = ws
        while True:
            try:
                message = await ws.receive_text()
            except (WebSocketDisconnect,) as e:
                break
            else:
                for k, v in self.clients.items():
                    if k != key:
                        await v.send_text(data=message)  # no exception ???

        with self.locker:
            if key in self.clients.keys():
                del self.clients[key]
        await ws.close()

    async def _onAir(self, *, message: str) -> None:
        with self.locker:
            for k, v in self.clients.items():
                await v.send_text(data=message)

    def _bcWatcher(self):
        while True:
            try:
                message = self.bcQueue.get(timeout=self.bcGetTimeoutSecs)
            except (Empty,) as e:
                self.broadCast(message='Queue is empty!')  # for debug
            else:
                self.elo.run_until_complete(future=self._onAir(message=message))
                self.bcCounter += 1

    # ---------------------------------------------------------------------------------
    def broadCast(self, *, message: str):
        try:
            self.bcQueue.put(item=message, timeout=self.bcPutTimeoutSecs)
        except (Full,) as e:
            print(e)
            pass
    # ---------------------------------------------------------------------------------

if __name__ == '__main__':
    def main():
        S = WebSocketServer()
        pass

    main()


from tkinter import *
from math import *
import statistics
import random
import datetime
from tkinter import  messagebox

W = Tk()
W.title('Phy-Cal version 1.0')
W.iconbitmap('c:/PP/b.ico')
W.geometry("1250x700")
W.resizable(0, 0)

menu = Menu(W)
W.config(menu=menu)

File = Menu(menu, tearoff=0)
menu.add_cascade(label="File", menu=File)
File.add_command(label="New")
File.add_command(label="Open")
File.add_command(label="Save")
File.add_command(label="Save as...")
File.add_separator()
File.add_command(label="print  Ctrl+P")
File.add_separator()
File.add_command(label="Close", command=W.quit)

Edit = Menu(menu, tearoff=0)
menu.add_cascade(label="Edit", menu=Edit)

Tool = Menu(menu, tearoff=0)
menu.add_cascade(label="Tool", menu=Tool)

Help = Menu(menu, tearoff=0)
menu.add_cascade(label="Help", menu=Help)
Help.add_command(label="View Help")
Help.add_separator()
Help.add_command(label="About Phy-Cal")
Help.add_command(label="SB")

lf = Frame(W, width=400 , height=900 , bg="WHITE" ).place(x=2 , y=1)

L1 = Label(lf, text="Select Form the following", font="Times 20 bold" , bg="WHITE", fg="Black")
L1.place(x=30 , y=10)

# v = Scrollbar(lf)
# tf = Frame(lf, width = 15, height = 15, wrap = NONE, yscrollcommand = v.set)

# v.pack(side = RIGHT, fill = Y)
# v.config(command=lf.yview)
# # Scrollbar
# scrol = Scrollbar(lf, orient=VERTICAL)

# Function to calculate the speed=distance/time
lspeed = Label(lf,text="Calculate Speed", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=80 , y=47)

# del keywords

l = IntVar()
t = IntVar()
# a = StringVar()

def sd():
	global a
	length= l.get()
	time = t.get()
	answer = length/time
	a = Label(lf, text=answer, font="Times 13 bold", bg="Black", fg="WHITE" )
	a.place(x = 100 , y = 160)

def clear():
	l.set('')
	t.set('')
	a.configure(text="")
	# a.delete(0,'END')
	# a.destroy()
	# a.set('')

ll = Entry(lf, width=30, textvariable=l , border=5).place(x=150 , y=90)
le = Label(lf, text="Enter Length :" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=10 , y = 88 )

tt = Entry(lf, width=30, textvariable=t , border=5).place(x=150 , y=130)
ti = Label(lf, text="Enter Time :" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=10 , y = 128 )

ans = Label(lf, text="Speed = " , font="Times 16 bold", bg="WHITE", fg="Black" ).place(x = 10 , y = 160)

spd = Button(lf,text="Calculate Speed",width=20, command=sd , bg="Black", fg="WHITE" , border = 4 ).place(x=30 , y = 190 )
cl = Button(lf,text="Clear Text",width=20, command=clear , bg="Black", fg="WHITE" , border = 4 ).place(x=200 , y = 190 )

# Function to calculate the Velocity= displacement/timetaken using string variable and EXCEPTION

velocity = Label(lf,text="Calculate Velocity ", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=80 , y=230)

ve = IntVar()
dis = IntVar()
vel = IntVar()

def velocity():
	global vel
	velo = ve.get()/dis.get()
	vel = Label(lf, text=velo, font="Times 13 bold", bg="Black", fg="WHITE" )
	vel.place(x = 110 , y = 345)

def clear():
	dis.set('')
	ve.set('')
	vel.destroy()

ll = Entry(lf, width=30, textvariable=ve, border=5).place(x=150 , y=270)
le = Label(lf, text="Displacement :" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=10 , y = 270 )

tt = Entry(lf, width=30, textvariable=dis , border=5).place(x=150 , y=310)
ti = Label(lf, text="Time Taken :" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=10 , y = 310 )

vel = Label(lf, text="Velocity = " , font="Times 16 bold", bg="WHITE", fg="Black" ).place(x = 10 , y = 345)

calvel = Button(lf,text="Calculate Velocity",width=20, command=velocity , bg="Black", fg="WHITE" , border = 4 ).place(x=30 , y = 380 )
clear = Button(lf,text="Clear Text",width=20, command= clear, bg="Black", fg="WHITE" , border = 4 ).place(x=200 , y = 380 )

# Calculating Averaage

averagevelocity = Label(lf,text="Average Velocity ", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=80 , y=415)

td = IntVar()
tt = IntVar()

def averagevelocity():
	global av
	avg = td.get()/tt.get()
	av = Label(lf, text=avg, font="Times 13 bold", bg="Black", fg="WHITE" )
	av.place(x = 185 , y = 523)

def clear():
	td.set('')
	tt.set('')
	av.destroy()

ll = Entry(lf, width=30, textvariable= td, border=5).place(x=150 , y=450)
le = Label(lf, text="Total Displace:" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=10 , y = 450 )

ll = Entry(lf, width=30, textvariable= tt, border=5).place(x=150 , y=490)
le = Label(lf, text="Total Time :" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=10 , y = 490)

av = Label(lf, text="Average Velocity= " , font="Times 16 bold", bg="WHITE", fg="Black" ).place(x = 10 , y = 520)

avgvel = Button(lf,text="Calculate Velocity",width=20, command=averagevelocity, bg="Black", fg="WHITE" , border = 4 ).place(x=30 , y = 560)
clear = Button(lf,text="Clear Text",width=20, command= clear, bg="Black", fg="WHITE" , border = 4 ).place(x=200 , y = 560)

#  Middle Frame

md = Frame(W, width=400 , height=900 , bg="WHITE" ).place(x=410 , y=1)

# Calculating force

at = IntVar()
mm = IntVar()

def force():
	global aa
	forc = mm.get()*at.get()
	aa = Label(md, text=forc, font="Times 13 bold", bg="Black", fg="WHITE" )
	aa.place(x = 490 , y = 80)
    # except Exception: messagebox.showinfo("Phy-Cal","Enter number")

def clear():
	at.set('')
	mm.set('')
	aa.destroy()

calculateforce = Label(md,text="Calculate Force", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=500 , y=10)

mee = Entry(md, width=15, textvariable= at , border=5).place(x=470 , y=50)
mass = Label(md, text="Mass:" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=415 , y = 50 )

ac = Entry(md, width=15, textvariable= mm , border=5).place(x=700, y=50)
acc = Label(md, text="Acceleration:" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=580 , y = 50 )

foorce = Label(md, text="Force = " , font="Times 16 bold", bg="WHITE", fg="Black" ).place(x =415 , y = 80)

btn = Button(md,text="Calculate force",width=20, command=force, bg="Black", fg="WHITE" , border = 4 ).place(x=435 , y = 115 )
clean = Button(md,text="Clear Text",width=20, command=clear , bg="Black", fg="WHITE" , border = 4 ).place(x=600 , y = 115 )

# Calculate Pressure

pressure = Label(md,text="Calculate Pressure", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=500 , y=155)

ar = IntVar()
fy = IntVar()

def pressure():
	global ans
	pr = fy.get()/ar.get()
	ans = Label(md, text=pr, font="Times 13 bold", bg="Black", fg="WHITE" )
	ans.place(x = 515 , y = 220)

def clear():
    ar.set('')
    fy.set('')
    ans.destroy()

fd = Entry(md, width=15, textvariable= fy , border=5).place(x=485, y=190)
frc = Label(md, text="Force :" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=415 , y = 190 )

aaaa = Entry(md, width=15, textvariable= ar , border=5).place(x=680, y=190)
area = Label(md, text="Area :" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=610 , y = 190 )

aea = Label(md, text="Pressure = " ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=415 , y = 220 )

btn_pressure = Button(md,text="Calculate Pressure",width=20, command=pressure, bg="Black", fg="WHITE" , border = 4 ).place(x=435 , y = 255 )
clean = Button(md,text="Clear Text",width=20, command=clear , bg="Black", fg="WHITE" , border = 4 ).place(x=600 , y = 255 )

# Moment of a Force
l2 = Label(md,text="Calculate Moment of a Force", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=470 , y=295)

# pd = IntVar()
# fo = IntVar()

pd = DoubleVar()
fo = DoubleVar()

def momentforce():
    try:
	    global att
	    mf = pd.get()*fo.get()
	    att = Label(md, text=mf, font="Times 13 bold", bg="Black", fg="WHITE" )
	    att.place(x = 645 , y = 362)
    except Exception: messagebox.showinfo("Phy-Cal","Enter number")

def clear():
	pd.set('')
	fo.set('')
	att.destroy()

perdis = Entry(md, width=15, textvariable= pd, border=5).place(x=650, y=330)
per = Label(md,text="Perpendicular Distance :", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=420 , y=330)

f = Entry(md, width=15, textvariable= fo , border=5).place(x=485, y=363)
lf = Label(md, text="Force :" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=415 , y = 360 )

btn = Button(md,text="Calculate force",width=20, command=momentforce, bg="Black", fg="WHITE" , border = 4 ).place(x=435 , y = 400 )
clean = Button(md,text="Clear Text",width=20, command=clear , bg="Black", fg="WHITE" , border = 4 ).place(x=600 , y = 400 )

mmm = Label(md, text="MoF =", font="Times 13 bold", bg="WHITE", fg="Black" ).place(x = 590 , y = 365)

# Recoil velocity v2= -(m1/m2)v1.
R = Label(md,text="Recoil Velocity", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=550 , y=435)

mb = DoubleVar()
mr = DoubleVar()
vb = DoubleVar()
vr = DoubleVar()
ecoil = StringVar()

def rv():
    try:
    	vr = (mb.get()/mr.get())*vb.get()
    	eciol = Label(md, text=vr, font="Times 13 bold", bg="Black", fg="WHITE" )
    	ecoil.place(x=690,y=510)
    except Exception: messagebox.showinfo("Phy-Cal","Enter number")

def clear():
	mb.set('')
	mr.set('')
	vb.set('')
	ecoil.set("")

v1 = Entry(md, width=15, textvariable= mb, border=5).place(x=510, y=470)
L1 = Label(md, text="MoBullet:" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=415 , y = 470 )

v1 = Entry(md, width=15, textvariable= mr, border=5).place(x=697, y=470)
L2 = Label(md, text="MoRifle:" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=613 , y = 470 )

v1 = Entry(md, width=15, textvariable= vb, border=5).place(x=509, y=510)
L3 = Label(md, text="VoBullet:" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=415 , y = 510)

L4= Label(md, text="Recoil :" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=610 , y = 510)

btn = Button(md,text="Calculate force",width=20, command=rv, bg="Black", fg="WHITE" , border = 4 ).place(x=435 , y = 550 )
clean = Button(md,text="Clear Text",width=20, command=clear , bg="Black", fg="WHITE" , border = 4 ).place(x=600 , y = 550 )

# Right Frame

rf = Frame(W, width=400 , height=900 , bg="WHITE" ).place(x=819 , y=1)

#muzzle vlocity v.exp()=2ad    ::(a= acceleration , d= distance)

Muz = Label(rf,text="Muzzle Velocity", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=950 , y=10)

acl = DoubleVar()
dis = DoubleVar()

def mv():
    try:
    	global mz
    	mvel = 2*acl.get()*dis.get()
    	mz = Label(rf,text=mvel, font="Times 16 bold" , bg="Black", fg="WHITE" )
    	mz.place(x=1010 , y=80)
    except Exception: messagebox.showinfo("Phy-Cal","Enter number")

def clear():
	acl.set('')
	dis.set('')
	# mz.configure(text="")
	mz.destroy()

mee = Entry(rf, width=15, textvariable= acl , border=5).place(x=895 , y=50)
mass = Label(rf, text="Acc:" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y = 50 )

ac = Entry(rf, width=15, textvariable= dis , border=5).place(x=1100, y=50)
acc = Label(rf, text="Distacne:" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=1010 , y = 50 )

mass = Label(rf, text="Muzzule velocity:" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y = 80 )

btn = Button(rf,text="Calculate force",width=20, command=mv, bg="Black", fg="WHITE" , border = 4 ).place(x=850 , y = 112 )
clean = Button(rf,text="Clear Text",width=20, command=clear , bg="Black", fg="WHITE" , border = 4 ).place(x=1020 , y = 112 )

#kinetics energy of bullets  same fromulat as kinetic energy.
keob = Label(rf,text="Kinetic energy of a bullet", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=900 , y=150)

ma = DoubleVar()
vol = DoubleVar()

def ke():
	try:
		global gy
		eng = 1/2*ma.get()*vol.get()**2
		gy = Label(rf,text=eng, font="Times 16 bold" , bg="Black", fg="WHITE" )
		gy.place(x=980 , y=210)
	except Exception: messagebox.showinfo("Phy-Cal","Enter number")

def clear():
	ma.set('')
	vol.set('')
	gy.destroy()

mee = Entry(rf, width=15, textvariable= ma , border=5).place(x=905 , y=180)
mass = Label(rf, text="Mass :" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y = 180 )

ac = Entry(rf, width=15, textvariable= vol , border=5).place(x=1100, y=180)
acc = Label(rf, text="Velocity:" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=1005 , y = 180 )

mass = Label(rf, text="Energy =" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y = 210 )

btn = Button(rf,text="Calculate force",width=20, command=ke, bg="Black", fg="WHITE" , border = 4 ).place(x=850 , y = 252 )
clean = Button(rf,text="Clear Text",width=20, command=clear , bg="Black", fg="WHITE" , border = 4 ).place(x=1020 , y = 252 )

#presure inside the barrel

keob = Label(rf,text="Pressure in A barrel", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=900 , y=295)

pm = DoubleVar()
pv = DoubleVar()
ba = DoubleVar()
lb = DoubleVar()

def pb():
	try:
		global psi
		prs = pm.get()*pv.get()**2/8*ba.get()*lb.get()
		psi = Label(rf, text= prs, font= "Times 16 bold", bg="WHITE", fg="Black")
		psi.place(x=1050 , y =465)
	except Exception: messagebox.showinfo("Phy-Cal","Enter Number")

def cln():
	pm.set('')
	pv.set('')
	ba.set('')
	lb.set('')
	psi.destroy()

prjtmas = Entry(rf, width=15, textvariable= pm , border=5).place(x=1020 , y=325)
mas = Label(rf, text="Projectile Mass:" , font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y=325 )

prhtveloc = Entry(rf, width=15, textvariable= pv , border=5).place(x=1020, y=360)
pvv = Label(rf, text="Projectile Velocity:" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y=360 )

borear = Entry(rf, width=15, textvariable= ba , border=5).place(x=1020, y=395)
brr = Label(rf, text="Bore Area:" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y=395 )

lenbrl = Entry(rf, width=15, textvariable= lb , border=5).place(x=1020, y=430)
lbbb = Label(rf, text="Lenght of Barrel:" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y=430 )

lbbb = Label(rf, text="Pressure in Barrel =" ,font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=840 , y=465 )

btn = Button(rf,text="Calculate force",width=20, command=pb, bg="Black", fg="WHITE" , border = 4 ).place(x=850 , y = 500 )
clean = Button(rf,text="Clear Text",width=20, command=cln , bg="Black", fg="WHITE" , border = 4 ).place(x=1020 , y = 500 )

#projectile friction

#compresson of the spring

# keob = Label(rf,text="Compression of a Spring", font="Times 16 bold" , bg="WHITE", fg="Black" ).place(x=900 , y=540)

W.mainloop()