from enum import IntEnum
import requests
import time
import json
import logging
import os
logger = logging.getLogger('charger')
logger.setLevel(logging.INFO)
from sink import Sink

data_override_file="debug_data.json"

MIN_AMP=6
TIMEOUT_DETECT_VEHICLE = 60
TIMEOUT_WAIT_FOR_PLUG_IN = 12
UPHYSTERESIS = 20
DOWNHYSTERESIS = -20
FINISHEDLIMIT = 100
SWITCHPHASEHYSTERESIS = 300
DEFAULTPHASESWITCHSTEP = 2100000 # just a high number

class Plug_states(IntEnum):
    INITIALIZE_CHARGER = 0
    RESTARTING = 1
    WAITING_FOR_VEHICLE_PLUGGING_IN = 2
    PLUGGED_IN = 3

plug_states=[
    "initialize charger",
    "restarting",
    "waiting for vehicle plugging in",
    "plugged in"
]

class Charge_states(IntEnum):
    UNPLUGGED = 0
    INITIALIZE_VEHICLE = 1
    WAITING_FOR_INITIALIZED_VEHICLE = 2
    CHARGING = 3
    WAITING_FOR_POWER = 4
    FINISHED = 5

charge_states=[
    "unplugged",
    "initialize vehicle",
    "waiting for initialized vehilce",
    "charging",
    "wait for power",
    "finished"
]

class Charger_modes(IntEnum):
    AUTOMATIC = 0 # use self generated power only
    MANUAL = 1 # use at least the amps given by button or app
    AMOUNT = 2 # charge manually given amount of energy and then switch back to automatic
    MARKET = 3 # reserved for later

charger_modes=[
    "automatic",
    "manual",
    "amount",
    "market"
]

class Charger(Sink):
    def __init__(self,name,config):
        super().__init__(name,config)
        self.address=config.get("address")
        self.config=config
        self._charge_state=None
        self._plug_state=None
        self.charge_state=Charge_states.UNPLUGGED
        self.plug_state=Plug_states.INITIALIZE_CHARGER
        self.min_amp=int(config.get("min_amp","6"))
        self.max_amp=int(config.get("max_amp","16"))
        self.amp=-1
        self.override_amp=0
        self._car_phase_count=0
        self._used_phase_count=0
        self.is_pluggedin=False
        self.connected_phase_count=0
        self.voltage=0
        self.charging_power=0
        self.step_power=0
        self.start_power=0
        self.switch_phase_power=DEFAULTPHASESWITCHSTEP
        self.charger_activated=False
        self.phases_set=-1
        #default for start and step power are 230V 3 phases
#        self.voltage=230
#        self.car_phase_count=3
        self.wait_for_kw_stop=False
        self.wait_for_car_timeout=0
        self.statemachine()

    def get_car_phase_count(self):
        return self._car_phase_count
    def set_car_phase_count(self,phases):
        self._car_phase_count=phases
        self.used_phase_count=phases
    car_phase_count=property(get_car_phase_count,set_car_phase_count)

    def get_used_phase_count(self):
        return self._used_phase_count
    def set_used_phase_count(self,phases):
        self._used_phase_count=min(phases,self._car_phase_count)
        self.step_power=int(self._used_phase_count*self.voltage)
        self.start_power=self.min_amp*self.step_power
    used_phase_count=property(get_used_phase_count,set_used_phase_count)

    def update_charge_mode(self,oldmode):
        newmode=self.get_charge_mode()
        if newmode!=oldmode:
            logger.info(self.name+" switched charger mode to "+charger_modes[newmode])

    def get_charge_mode(self):
        if self.wait_for_kw_stop:
            return Charger_modes.AMOUNT
        elif self.override_amp>0:
            return Charger_modes.MANUAL
        else:
            return Charger_modes.AUTOMATIC
    charge_mode=property(get_charge_mode)

    def get_plug_state(self):
        return self._plug_state
    def set_plug_state(self,state):
        if self._plug_state!=state:
            self._plug_state=state
            logger.info(self.name+" Switching to plug state "+plug_states[state])
    plug_state=property(get_plug_state,set_plug_state)

    def get_charge_state(self):
        return self._charge_state
    def set_charge_state(self,state):
        if self._charge_state!=state:
            if state==Charge_states.CHARGING:
                pass
            self._charge_state=state
            logger.info(self.name+" Switching to charge state "+charge_states[state])
    charge_state=property(get_charge_state,set_charge_state)

    def update(self):
        if self.nexttick<time.time():
            self.nextinterval()
#            if self.plug_state!=Plug_states.INITIALIZE_CHARGER:
            data=self.http_get("status")
            if not data is None:
                self.data=data
                self.read_data()
                self.statemachine()
            print(self.name+": "+str(self),end="")

    def set_amp(self,newvalue):
        if newvalue<self.min_amp:
            newvalue=self.min_amp
        if newvalue<self.override_amp:
            newvalue=self.override_amp
        if newvalue>self.max_amp:
            newvalue=self.max_amp
        if newvalue!=self.amp:
            cmd="amx" if self.capabilities["amx"] else "amp"
            # update self.amp before a call of read_data to
            # prevent interpretation as override amp
            self.amp=newvalue
            self.data=self.http_get("mqtt?payload="+cmd+"="+str(newvalue))

    def switch_phases(self,phase_count):
        if phase_count>1:
            if self.phases_set!=3:
                data=self.http_get("api/set?psm=2")
                self.phases_set=3
                self.used_phase_count=3
                logger.info(self.name+" switched used phases to "+str(self.used_phase_count))
        else:
            if self.phases_set!=1:
                data=self.http_get("api/set?psm=1")
                self.phases_set=1
                self.used_phase_count=1
                logger.info(self.name+" switched used phases to "+str(self.used_phase_count))

    def activate_charger(self,run):
        alw=int(self.data["alw"])
        if run!=(alw==1):
            self.data=self.http_get("mqtt?payload=alw="+str(1 if run else 0))

    def http_get(self,uri):
        print("trying to get data from", self.address)
        try:
            r = requests.get("http://"+str(self.address)+"/"+uri,timeout=3)
            self.reachable=True
        except:
            self.reachable=False
        if self.reachable:
            if r.status_code==200:
                data=r.text
                try:
                    data=r.json()
                except:
                    pass
                return data
            else:
                return None

    def read_data(self):
        if data_override_file!="":
            try:
                with open(os.path.dirname(os.path.abspath(__file__))+data_override_file) as json_file:
                    override_data = json.load(json_file)
                    res=override_data.get("res")
                    if not res is None:
                        self.reserve=int(res)
            except:
                override_data={}
            self.data={**self.data,**override_data}
        self.is_pluggedin=self.data["car"] in [2,3,4]
        self.connected_phase_count=0
        self.voltage=0
        for phase_number in range(3):
            if self.data["nrg"][phase_number]:
                self.voltage+=self.data["nrg"][phase_number]*self.correction_factor
                self.connected_phase_count+=1
        self.voltage=int(self.voltage//self.connected_phase_count)
        self.current_power=int(round(self.data["nrg"][11]*self.correction_factor*10,0))
        oldmode=self.get_charge_mode()
        if int(self.data["amp"])!=self.amp:
            # amp value was set outside via device button or app and will be used as
            # override value
            self.override_amp=int(self.data["amp"])
            self.wait_for_car_timeout=time.time()+TIMEOUT_WAIT_FOR_PLUG_IN
        # if amount to charge is set via app temporaryly set override_amp to
        # make sure the amount is charged before going back to automatic
        if int(self.data["dwo"])>0 and not self.wait_for_kw_stop:
            self.wait_for_kw_stop=True
            if self.override_amp==0:
                self.override_amp=int(self.data["amp"])
                if int(self.data["car"])==1:
                    # wait 2 minutes for plugin of a car before returning to automatic mode
                    self.wait_for_car_timeout=time.time()+TIMEOUT_WAIT_FOR_PLUG_IN
        if self.wait_for_kw_stop and int(self.data["dwo"])==0:
            self.wait_for_kw_stop=False
            self.override_amp=0
        self.amp=int(self.data["amp"])
        self.car=int(self.data["car"])
        self.charger_activated=int(self.data["alw"])==1
        self.charging_power=int(int(self.data["nrg"][11]*10*self.correction_factor))
        self.update_charge_mode(oldmode)

    def statemachine(self):
        if self.plug_state==Plug_states.INITIALIZE_CHARGER:
            self.reachable=False
            # older chargers tend to measure a too low volate
            # as power is measured voltage*current, power needs same correction
            self.correction_factor=1.05
            self.capabilities={"phaseswitch":False,"amx":False}
            if not self.address is None:
                data=self.http_get("api/status")
                if not data is None:
                    self.capabilities["phaseswitch"]=True
                    #HW3 ist more correct than deviation of 5% from HW2 and bef6ore
                    self.correction_factor=1
                self.correction_factor=float(self.config.get("correction_factor",str(self.correction_factor)))
                self.data=self.http_get("status")
                if not self.data is None:
                    self.set_amp(0)
                    if float(self.data["fwv"])>=40:
                        self.capabilities["amx"]=True
                    self.read_data()
                if self.reachable:
                    self.plug_state=Plug_states.RESTARTING
        if self.plug_state==Plug_states.RESTARTING:
            oldmode=self.get_charge_mode()
            # reset charger mode to automatic
            self.charger_mode=Charger_modes.AUTOMATIC
            self.switch_phase_power=DEFAULTPHASESWITCHSTEP
            # set phases to 3
            if self.connected_phase_count>1 and self.capabilities["phaseswitch"]:
                self.switch_phases(3)
            # reset override_amp if restarting
            self.override_amp=0
            self.wait_for_car_timeout=0
            # set amp to minimum to notice when it was changed
            self.set_amp(MIN_AMP)
            # activate pwm signal to make button work
            self.activate_charger(True)
            # find next state
            self.update_charge_mode(oldmode)
            if self.car==1:
                self.plug_state=Plug_states.WAITING_FOR_VEHICLE_PLUGGING_IN
                self.charge_state=Charge_states.UNPLUGGED
            else:
                self.plug_state=Plug_states.PLUGGED_IN
                self.charge_state=Charge_states.INITIALIZE_VEHICLE
        if self.plug_state==Plug_states.WAITING_FOR_VEHICLE_PLUGGING_IN:
            if self.car!=1:
                self.plug_state=Plug_states.PLUGGED_IN
                self.charge_state=Charge_states.INITIALIZE_VEHICLE
            else:
                if time.time()>self.wait_for_car_timeout:
                    oldmode=self.get_charge_mode()
                    self.override_amp=0
                    self.update_charge_mode(oldmode)
                    self.set_amp(MIN_AMP)
        if self.plug_state==Plug_states.PLUGGED_IN:
            if self.car==1:
                self.plug_state=Plug_states.RESTARTING
            elif self.charge_state==Charge_states.INITIALIZE_VEHICLE:
                #detect vehicle
                if self.connected_phase_count==1:
                    self.car_phase_count=1
                    self.charge_state=Charge_states.CHARGING
                else:
                    self.timeout=time.time()+TIMEOUT_DETECT_VEHICLE # wait 15 seconds to detect number of phases that the car uses
                    self.charge_state=Charge_states.WAITING_FOR_INITIALIZED_VEHICLE
            elif self.charge_state==Charge_states.WAITING_FOR_INITIALIZED_VEHICLE:
                if self.current_power<FINISHEDLIMIT:
                    # reset the timeout as long the vehicle does not draw power,
                    # e.g. because it is fully charged or in sleep mode
                    self.timeout=time.time()+TIMEOUT_DETECT_VEHICLE
                car_phase_count=0
                for index in [7,8,9]:
                    if self.data["nrg"][index]>0:
                        car_phase_count+=1
                # if all three phases are used or timeout is over proceed with charging
                if (car_phase_count>2) or ((time.time()>self.timeout) and (car_phase_count>0)):
                    self.timeout=0
                    self.car_phase_count=car_phase_count
                    self.used_phase_count=car_phase_count
                    self.switch_phase_power=self.start_power+SWITCHPHASEHYSTERESIS
                    self.charge_state=Charge_states.CHARGING
            if self.charge_state==Charge_states.CHARGING:
                if self.reserve<DOWNHYSTERESIS:
                    newamp=max(self.override_amp,self.amp)-1
                    self.set_amp(newamp)
                    if newamp<self.min_amp:
                        # not enough power available
                        # step 1: switch to single phase if possible
                        if self.used_phase_count>1 and self.capabilities["phaseswitch"]:
                            if self.reserve<-SWITCHPHASEHYSTERESIS:
                                self.switch_phases(1)
                        else:
                        # otherwise deactivate charger
                            self.activate_charger(False)
                            self.charge_state=Charge_states.WAITING_FOR_POWER
                    if self.current_power<FINISHEDLIMIT:
                        self.charge_state=Charge_states.FINISHED
                # check if switch to 3 phases is possible
                elif (self.phases_set<3) and ((self.reserve+self.current_power)>self.switch_phase_power):
                    self.set_amp(MIN_AMP)
                    self.switch_phases(3)
                elif (self.reserve>self.step_power+UPHYSTERESIS) and (self.current_power>(self.step_power*(self.amp-1))):
                    self.set_amp(self.amp+1)
            elif self.charge_state==Charge_states.WAITING_FOR_POWER:
                if (self.reserve>self.start_power) or (self.override_amp>0):
                    self.activate_charger(True)
                    self.charge_state=Charge_states.CHARGING
                else:
                    self.activate_charger(False)
            elif self.charge_state==Charge_states.FINISHED:
                if self.current_power>FINISHEDLIMIT:
                    # restart charging
                    self.charge_state=Charge_states.CHARGING

    def __str__(self):
        state=charge_states[self.charge_state] if self.plug_state==Plug_states.PLUGGED_IN else plug_states[self.plug_state]
        return str({
            "reachable":self.reachable,
            "state":state,
            "connected phases":self.connected_phase_count,
            "car_phases":self.car_phase_count,
            "used_phases":self.used_phase_count,
            "amp":self.amp,
            "override":self.override_amp,
            "power":self.charging_power,
            "step_power":self.step_power,
            "start_power":self.start_power,
            "switch_phase_power":self.switch_phase_power,
            "mode":charger_modes[self.charge_mode],
            "alw":self.charger_activated,
            "reserve":self.reserve
        })+"\n"
        """
            "voltage":self.voltage,
            "caps":self.capabilities,
        """


from futu import *
import csv

trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111)
ret, data1 = trd_ctx.position_list_query(trd_env=TrdEnv.SIMULATE)

if ret == RET_OK:

    with open('Holding_Stock_information.csv', 'w', newline='',encoding='utf_8_sig') as csvFile:

        headers = ['Position_side', 'Code', 'Stock_Name', 'Quantity', 'Can_sell_qty', 'Nominal_price', 'Cost_price',
                   'Cost_price_valid', 'Market_val', 'pl_ratio', 'pl_ratio_valid', 'pl_val', 'pl_val_valid',
                   'Today_pl_val', 'Today_buy_qty', 'Today_buy_val', 'Today_sell_qty', 'Today_sell_val','Unrealized_pl',
                   'Realized_pl']

        position_side = (data1['position_side'].values.tolist())
        code = (data1['code'].values.tolist())
        stock_name = (data1['stock_name'].values.tolist())
        qty = (data1['qty'].values.tolist())
        can_sell_qty = (data1['can_sell_qty'].values.tolist())
        nominal_price = (data1['nominal_price'].values.tolist())
        cost_price = (data1['cost_price'].values.tolist())
        cost_price_valid = (data1['cost_price_valid'].values.tolist())
        market_val = (data1['market_val'].values.tolist())
        pl_ratio = (data1['pl_ratio'].values.tolist())
        pl_ratio_valid = (data1['pl_ratio_valid'].values.tolist())
        pl_val = (data1['pl_val'].values.tolist())
        pl_val_valid = (data1['pl_val_valid'].values.tolist())
        today_pl_val = (data1['today_pl_val'].values.tolist())
        today_buy_qty = (data1['today_buy_qty'].values.tolist())
        today_buy_val = (data1['today_buy_val'].values.tolist())
        today_sell_qty = (data1['today_sell_qty'].values.tolist())
        today_sell_val = (data1['today_sell_val'].values.tolist())
        unrealized_pl = (data1['unrealized_pl'].values.tolist())
        realized_pl = (data1['realized_pl'].values.tolist())

        writer = csv.writer(csvFile)
        writer.writerow(headers)
        for i in range(len((position_side))):
            writer.writerow([position_side[i], code[i], stock_name[i], qty[i], can_sell_qty[i], nominal_price[i], cost_price[i],
                             cost_price_valid[i], market_val[i], pl_ratio[i], pl_ratio_valid[i], pl_val[i], pl_val_valid[i],
                             today_pl_val[i], today_buy_qty[i], today_buy_val[i], today_sell_qty[i], today_sell_val[i], unrealized_pl[i],
                             realized_pl[i]])

trd_ctx.close()


#!/usr/bin/env python
# coding: utf-8

# # Remarks
#
# * Data normalization
#     * Mobilenet expects data from -1 to 1
#         * Normalize Input Data or Include in Model
#         * TFLite Conversion must fit according to decision
#     * Ground Truth Data: for better inspection Data multiplied by 80. Undo the change in the Data Input Pipeline
# * Overview in Tutorials:
#     * tf.function
#     * Repeat addapted Version of using Build in methods for training, ...
#     * Save models using keras
#         * CaseNet first real model: check in implementation of Frey if a Layer needs to be written
#         * other Example: depth seperable dilated convolution,
# * Idea
#     * Loss
#         * Focal Loss: for imbalanced Data
#         * In general Loss: just now weight in each dependent on number of Edge Pixels

# # Libraries

# In[1]:

#!for a in /sys/bus/pci/devices/*; do echo 0 | sudo tee -a $a/numa_node; done

import tensorflow as tf
import numpy as np
import os
import time
from datetime import datetime
import sys
import matplotlib.pyplot as plt
import argparse

import DataProcessing.data_processing as data_processing
import Nets.backbones as backbones
import Nets.features as features
import Nets.losses as losses
import Nets.metrics as metrics
import Nets.visualize as visualize
import Nets.tools as tools

os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'

#np.set_printoptions(threshold=sys.maxsize)

# # Parser

# In[2]:

parser = argparse.ArgumentParser()

parser.add_argument('--model', type=str, required=False, default=None)
parser.add_argument('--data', type=str, required=False, default=None)

parser.add_argument('--bs', type=int, required=False, default=None)
parser.add_argument('--idx', type=int, required=False, default=None)
parser.add_argument('--epoch', type=int, required=False, default=None)
parser.add_argument('--noise', type=float, required=False, default=None)

parser.add_argument('--train_model', action='store_true', default=False)
parser.add_argument('--cache', action='store_true', default=False)
parser.add_argument('--save', action='store_true', default=False)
parser.add_argument('--sigmoid', action='store_true', default=False)
parser.add_argument('--focal', action='store_true', default=False)

parser.add_argument('--beta_upper', type=float, required=False, default=None)
parser.add_argument('--gamma', type=float, required=False, default=None)
parser.add_argument('--alpha', type=float, required=False, default=None)

file_name = None
try:
    file_name = __file__
except:
    print("Jupyter Notebook")

if file_name is None:
    args = parser.parse_args("")
    args.train_model = True
    args.cache = True
    #args.save = True
    args.save = False
    args.sigmoid = False
    args.focal = True
else:
    args = parser.parse_args()

# # Options

# In[3]:

# Generall Parameters
MODEL= 'CASENET_FOCAL_LOSS_0.7_g2_a2_random' if args.model is None else args.model
DATA= 'SceneNetFloorTiledTextureRandom' if args.data is None else args.data
#DATA = 'RealRed'
TRAIN_DS ='Train'
TEST_DS = 'Test'
HALF = True

# Dataset Loading Parameters
IMG_SIZE_HEIGHT = 1280
IMG_SIZE_WIDTH = 720
NUM_CLASSES = 3
MAX_IMG_TRAIN = 500
MAX_IMG_TEST = 300
SEED = None
BATCH_SIZE = 3 if args.bs is None else args.bs
CACHE = args.cache
NOISE_STD = 0.0 if args.noise is None else args.noise

# Model Parameters
BACKBONE = "RESNet50"
BACKBONE_OUTPUT = [0,1,2,4]
BACKBONE_WEIGHTS = "imagenet"
ALPHA = 1
FINE_TUNING = False
FINE_TUNE_EPOCHS = 10
TRAINABLE_IDX = 0 if args.idx is None else args.idx # (3-1), as indexing starts at 0
EPOCHS = 80 if args.epoch is None else args.epoch
SAVE = args.save
TRAIN_MODEL = args.train_model

#Model Callback
MODEL_SAVE_EPOCH_FREQ = 5
DEL_OLD_CHECKPOINTS = False
TENSORBOARD = False
DEL_OLD_TENSORBOARD = True

# LOSS
weighted_multi_label_sigmoid_edge_loss = args.sigmoid
focal_loss = args.focal

beta_upper = 0.7 if args.beta_upper is None else args.beta_upper
beta_lower = 1.0 - beta_upper
gamma=2.0 if args.gamma is None else args.gamma
alpha=2.0 if args.alpha is None else args.alpha
class_weighted = True
weighted_beta=True

# All Pixels have been labeled correctly and thus we don't need to account shifted labels
# and a protection band around the labels for the calculation of the metrics

# In the work of Frey he mentioned that state of the Art ? is 2% of diagonal.
# He takes 1%, I sugest to take a threshold of 3 Pixels.
#I don't think that I made more then 3 Pixel mistake in labeling and tracking. Thus this is 0.4%
THRESHOLD_EDGE_WIDTH_REAL = 2

# Data Augmentation:
aug_param = {"contrast_factor": 0.8, "brightness": 0.2, "hue": 0.05, "saturation": 0.8, "gaussian_value": 0.015,
            "value": 0.1, "strength_spot": 0.5, "blur": False, "sigma": 1.0}

#TESTING
test = False
if test:
    EPOCHS = 10
    MAX_IMG_TRAIN = 18
    MAX_IMG_TEST = 3

# # Load Dataset, Preprocess Images and Dataset

# In[5]:

tf.random.set_seed(SEED)

paths, files = data_processing.path_definitions(HALF, MODEL, DATA, TRAIN_DS, TEST_DS, make_dirs=True)

data_processing.clean_model_directories(paths, DEL_OLD_CHECKPOINTS, DEL_OLD_TENSORBOARD)

if TRAIN_MODEL:

    rng = tf.random.Generator.from_seed(123, alg='philox')

    train_ds, img_count_train = data_processing.load_dataset(paths,"TRAIN", IMG_SIZE_HEIGHT, IMG_SIZE_WIDTH, HALF,
                                                             MAX_IMG_TRAIN, noise_std=NOISE_STD)
    train_ds = data_processing.dataset_processing(train_ds, cache=CACHE, shuffle=True, batch_size=BATCH_SIZE, prefetch=True,
                                                  img_count=img_count_train, augment=True, rng=rng, aug_param=aug_param)

test_ds, img_count_test = data_processing.load_dataset(paths,"TEST", IMG_SIZE_HEIGHT, IMG_SIZE_WIDTH, HALF,
                                                       MAX_IMG_TEST, noise_std=None)
test_ds = data_processing.dataset_processing(test_ds, cache=CACHE, shuffle=False, batch_size=BATCH_SIZE, prefetch=True,
                                             img_count=img_count_test)

# In[6]:

DATA_REAL = 'RealRed'
TRAIN_REAL = 'Train'
TEST_REAL = 'Test'
TEST_HARD_REAL = 'Test Hard'
IMG_ONLY_REAL = 'Img Only'
BS_REAL = 8

paths_real, files_real = data_processing.path_definitions(HALF, MODEL, DATA_REAL, TRAIN_REAL, TEST_REAL, TEST_HARD_REAL, IMG_ONLY_REAL, make_dirs=False)

test_real_ds, img_count_test_real = data_processing.load_dataset(paths_real,"TEST", IMG_SIZE_HEIGHT, IMG_SIZE_WIDTH, HALF, MAX_IMG_TEST)
test_real_ds = data_processing.dataset_processing(test_real_ds, cache=False, shuffle=False, batch_size=BS_REAL, prefetch=False, img_count = img_count_test_real)

# In[8]:

#for image,label in train_ds.take(1):
#        image, mask = image,label
#plt.figure(figsize=(10,20))
#plt.imshow(tf.keras.preprocessing.image.array_to_img(image[0, :, :, :]))

#for image,label in train_ds.take(1):
#    sample_image, sample_mask = image,label
#
#visualize.plot_images(images=sample_image, labels=sample_mask, predictions=None, batch_size=3)

# # Model

# In[7]:

if weighted_multi_label_sigmoid_edge_loss:
    loss = lambda y_true, y_pred : losses.weighted_multi_label_sigmoid_loss(y_true,y_pred,beta_lower=beta_lower,beta_upper=beta_upper, class_weighted=class_weighted)
elif focal_loss:
    loss = lambda y_true, y_pred : losses.focal_loss_edges(y_true, y_pred, gamma=gamma, alpha=alpha, weighted_beta=weighted_beta,beta_lower=beta_lower,beta_upper=beta_upper, class_weighted=class_weighted)
else:
    raise ValueError("either FocalLoss or WeightedMultiLabelSigmoidLoss must be True")

# In[8]:

if TRAIN_MODEL:
    backbone, output_names = backbones.get_backbone(name=BACKBONE,weights=BACKBONE_WEIGHTS,
                                              height=IMG_SIZE_HEIGHT,width=IMG_SIZE_WIDTH,
                                              alpha=ALPHA, output_layer = BACKBONE_OUTPUT,
                                                            trainable_idx = TRAINABLE_IDX)

    upsample_side_1 = tf.keras.layers.Conv2D(1, kernel_size=1, strides=(1, 1), padding='same')(backbone.output[0])
    upsample_side_2 = features.side_feature_casenet(backbone.output[1],channels=1,kernel_size_transpose=4,stride_transpose=2)
    upsample_side_3 = features.side_feature_casenet(backbone.output[2],channels=1,kernel_size_transpose=8,stride_transpose=4)
    #upsample_side_5 = tf.image.resize(backbone.output[3],(int(IMG_SIZE_HEIGHT/16),int(IMG_SIZE_WIDTH/16)))
    upsample_side_5 = features.side_feature_casenet(backbone.output[3],channels=NUM_CLASSES,kernel_size_transpose=16,stride_transpose=8,name='side5')

    side_outputs = [upsample_side_1,upsample_side_2,upsample_side_3,upsample_side_5]
    concat = features.shared_concatenation(side_outputs,NUM_CLASSES)

    output = features.fused_classification(concat,NUM_CLASSES,name="output")

    model = tf.keras.Model(inputs = backbone.input, outputs = [output,upsample_side_5])

    # tf.keras.utils.plot_model(model,show_shapes = True,to_file = 'h.png')

# # Compile and Train Model

# In[9]:

if TENSORBOARD:
    get_ipython().run_line_magic('load_ext', 'tensorboard')
    get_ipython().run_line_magic('tensorboard', '--logdir /home/david/SemesterProject/Models/CASENet/logs')

# In[10]:

if TRAIN_MODEL:
    # learning rate schedule
    base_learning_rate = 0.0005
    end_learning_rate = 0.0001
    decay_step = np.ceil(img_count_train / BATCH_SIZE)*EPOCHS
    lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay(base_learning_rate,decay_steps = decay_step,end_learning_rate = end_learning_rate, power = 0.9)

    frequency = int(np.ceil(img_count_train / BATCH_SIZE)*MODEL_SAVE_EPOCH_FREQ)+1

    logdir = os.path.join(paths['TBLOGS'], datetime.now().strftime("%Y%m%d-%H%M%S"))
    callbacks = [tf.keras.callbacks.ModelCheckpoint(filepath = paths["CKPT"]+ "/ckpt-loss={val_loss:.2f}-epoch={epoch:.2f}-f1={val_f1:.4f}",
                                                    save_weights_only=False,save_best_only=False,monitor="val_f1",verbose=1,save_freq= 'epoch', period=5),
                tf.keras.callbacks.TensorBoard(log_dir=logdir,histogram_freq=1)]

    # compile model
    model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),
                  loss=loss,
                  metrics={'output': [metrics.BinaryAccuracyEdges(threshold_prediction=0),
                                      metrics.F1Edges(threshold_prediction=0, threshold_edge_width=0)]})

    history = model.fit(train_ds, epochs=EPOCHS, validation_data=test_real_ds, callbacks=callbacks)

# In[16]:

model_ckpt = os.listdir(paths['CKPT'])

f1_max = 0
for ckpt_name in model_ckpt:
    if float(ckpt_name[-4:]) > f1_max:
        f1_max = float(ckpt_name[-4:])
        model_path = paths['CKPT']+"/"+ckpt_name

        print(model_path)

custom_objects = {"BinaryAccuracyEdges": metrics.BinaryAccuracyEdges,
                  "F1Edges": metrics.F1Edges,
                  "<lambda>":loss}

model = tf.keras.models.load_model(model_path, custom_objects=custom_objects)

# # Plot Results

# In[17]:

if TRAIN_MODEL:
    plot_losses = ["loss", "output_loss"]
    plot_metrics = ["output_accuracy_edges", "f1", "recall", "precision"]

    path = os.path.join(paths["FIGURES"],"training.svg")

    visualize.plot_training_results(res=history.history, losses=plot_losses, metrics=plot_metrics, save=SAVE, path=path)

# In[18]:

### Maximum F1 Score:
if not TRAIN_MODEL:
    step_width = 0.05
    threshold_range = [0.05,0.95]
    threshold_array = np.arange(threshold_range[0],threshold_range[1]+step_width,step_width)
    threshold_array = np.array([0.025, 0.1, 0.2,0.3,0.4,0.45,0.5,0.55,0.6,0.7,0.8, 0.9, 0.975])

    path_metrics_evaluation_plot = os.path.join(paths["FIGURES"],"threshold_metrics_evaluation_test_ds.svg")
    threshold_f1_max = visualize.plot_threshold_metrics_evaluation_class(model=model,
                                                                         ds=test_ds,
                                                                         num_classes=NUM_CLASSES,
                                                                         threshold_array=threshold_array,
                                                                         threshold_edge_width=0, save=SAVE,
                                                                         path=path_metrics_evaluation_plot)

# In[19]:

if not TRAIN_MODEL:
    i = 0
    for img, label in test_ds.take(4):
        img, label = img, label

        threshold = 0.5

        predictions = model.predict(img)
        predictions = tools.predict_class_postprocessing(predictions[0], threshold=threshold)

        path = os.path.join(paths["FIGURES"],"img_test_threshold_{}_{}".format(threshold,i))
        visualize.plot_images(images=img, labels=label, predictions=predictions, save=SAVE, path=path, batch_size=3)

        threshold = threshold_f1_max
        path = os.path.join(paths["FIGURES"],"img_test_ods_{}".format(i))
        visualize.plot_images(images=img, labels=label, predictions=predictions, save=SAVE, path=path, batch_size=3)

        i += 1

# # Fine Tuning

# In[ ]:

if FINE_TUNING and TRAIN_MODEL:

    # Fine-tune from this layer onwards
    fine_tune_output = output_names[1-1]

    model.trainable = True

    # Freeze all the layers before the `fine_tune_at` layer:
    for submodel in model.layers:
        if submodel.name == "base_model":
            for layer in submodel.layers:
                layer.trainable = False
                if layer.name == fine_tune_output:
                    break

    total_epochs =  EPOCHS + FINE_TUNE_EPOCHS

    base_learning_rate = 0.00001
    end_learning_rate =  0.00001
    decay_step = np.floor(img_count_train / BATCH_SIZE)*FINE_TUNE_EPOCHS
    lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay(
        base_learning_rate,decay_steps = decay_step,end_learning_rate = end_learning_rate, power = 0.9)

    model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),
                  loss=loss,
                  metrics={'output': [metrics.BinaryAccuracyEdges(threshold_prediction=0),
                                      metrics.F1Edges(threshold_prediction=0, threshold_edge_width=0)]})

    history_fine = model.fit(train_ds, epochs=total_epochs,
                               initial_epoch=history.epoch[-1]+1,validation_data=train_ds.take(1),
                               callbacks=callbacks)

    plot_losses = ["loss", "output_loss"]
    plot_metrics = ["output_accuracy_edges", "f1", "recall", "precision"]

    path = os.path.join(paths["FIGURES"],"fine_tuning_training.svg")

    visualize.plot_training_results(res=history.history, res_fine = history_fine.history,
                                losses=plot_losses, metrics=plot_metrics, save=SAVE, path=path, epochs=EPOCHS)

    path_metrics_evaluation_plot = os.path.join(paths["FIGURES"],"threshold_metrics_evaluation__fine_tune_test_ds.svg")
    visualize.plot_threshold_metrics_evaluation(model=model, ds=test_ds, threshold_array=threshold_array,
                                        threshold_edge_width=0, save=SAVE, path=path_metrics_evaluation_plot,
                                        accuracy_y_lim_min = 0.9)

    for img, label in test_ds.take(1):
        img, label = img, label

    predictions = model.predict(img)
    predictions = tools.predict_class_postprocessing(predictions[0], threshold = 0.5)

    path = os.path.join(paths["FIGURES"],"fine_tuning_images_0,5")
    visualize.plot_images(images=img, labels=label, predictions=predictions, save=SAVE, path=path, batch_size=3)

# # Evaluate on Test DS of Real Images

# In[ ]:

DATA_REAL = 'RealRed'
TRAIN_REAL = 'Train'
TEST_REAL = 'Test'
TEST_HARD_REAL = 'Test Hard'
IMG_ONLY_REAL = 'Img Only'
BS_REAL = 8

paths_real, files_real = data_processing.path_definitions(HALF, MODEL, DATA_REAL, TRAIN_REAL, TEST_REAL, TEST_HARD_REAL, IMG_ONLY_REAL, make_dirs=False)

test_real_ds, img_count_test_real = data_processing.load_dataset(paths_real,"TEST", IMG_SIZE_HEIGHT, IMG_SIZE_WIDTH, HALF, MAX_IMG_TEST)
test_real_ds = data_processing.dataset_processing(test_real_ds, cache=False, shuffle=False, batch_size=BS_REAL, prefetch=False, img_count = img_count_test_real)

# ## Metrics Evaluation

# In[ ]:

if not TRAIN_MODEL:
    step_width = 0.025
    threshold_range = [0.025, 0.975]
    threshold_array = np.arange(threshold_range[0],threshold_range[1]+step_width,step_width)

    path_metrics_evaluation_plot = os.path.join(paths["FIGURES"],"threshold_metrics_evaluation_test_real_edge_threshold_{:.1f}.svg".format(0))
    threshold_f1_max = visualize.plot_threshold_metrics_evaluation_class(model=model, ds=test_real_ds,
                                                                   num_classes = NUM_CLASSES,
                                                                   threshold_array=threshold_array,
                                                                   threshold_edge_width=0, save=SAVE,
                                                                   path=path_metrics_evaluation_plot)

# ## Visual Results

# In[ ]:

if not TRAIN_MODEL:
    for img, label in test_real_ds.take(1):
        img, label = img, label

    threshold = 0.5

    predictions = model.predict(img)
    predictions = tools.predict_class_postprocessing(predictions[0], threshold=threshold)

    path = os.path.join(paths["FIGURES"],"images_test_real_threshold_{:.2f}".format(threshold))
    visualize.plot_images(images=img, labels=label, predictions=predictions, save=SAVE, path=path, batch_size=8)

    threshold = threshold_f1_max

    predictions = model.predict(img)
    predictions = tools.predict_class_postprocessing(predictions[0], threshold=threshold)

    path = os.path.join(paths["FIGURES"],"images_test_real_threshold_ods")
    visualize.plot_images(images=img, labels=label, predictions=predictions, save=SAVE, path=path, batch_size=8)

# # Save Model

# In[20]:

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),
                  loss=loss,
                  metrics={'output': [metrics.BinaryAccuracyEdges(threshold_prediction=0),
                                      metrics.F1Edges(threshold_prediction=0, threshold_edge_width=0)]})

if SAVE:
    model.save(paths["MODEL"])

    custom_objects = {"BinaryAccuracyEdges": metrics.BinaryAccuracyEdges,
                      "F1Edges": metrics.F1Edges,
                      "<lambda>":loss}

    model = tf.keras.models.load_model(paths["MODEL"], custom_objects=custom_objects)

# # Plot Other, Additional Data.

# # Addtional Elements to Consider in other Projects
#
# * Data augmentation for small datasets

# In[ ]:


from typing import Optional, Dict, Any
from django.contrib.auth.models import AnonymousUser

from users.models import JustfixUser

class GraphQLStaticRequest:
    """
    This represents a GraphQL request made on behalf of front-end
    code that is trying to generate static content--such as a PDF
    or email text--and therefore may not have access to an
    actual Django HttpRequest. For example, it may be running in
    a worker process or from a Django management command.

    Because we've already written all our GraphQL mutations to
    expect a Django HttpRequest as the GraphQL context, however,
    our best way to accomodate this use case (without doing a *lot*
    of refactoring) is to create a tiny subset of the HttpRequest
    interface that only our static content-related GraphQL endpoints
    will need to access.
    """

    def __init__(
        self,
        user: Optional[JustfixUser] = None,
        session: Optional[Dict[str, Any]] = None,
    ):
        if user is None:
            user = AnonymousUser()

        # This corresponds to HttpRequest.user.
        self.user = user

        # This corresponds to HttpRequest.session.
        self.session: Dict[str, Any] = session or {}


import os
import sys
import logging
import json

config_logger = logging.getLogger("main")

class Configuration():

  @property
  def DEBUG(self):
    if "WINGDB_ACTIVE" in os.environ:
      return False
    else:
      return True

  @property
  def TESTING(self):
    return False

  @property
  def DATABASE_URI(self):
    if "WINGDB_ACTIVE" in os.environ:
      return False
    else:
      return True

  @classmethod
  def configfile(self,config_filename="ldap.json"):
    try:
      config_logger.debug("retrieving %s configuration"% config_filename)
      with open(self.config_path('%s'%config_filename), "r") as f:
        x = f.read()
      if config_filename.endswith("json"):
        config=json.loads(x)
      else:
        auth_logger.error("extension unknown")
      return config
    except:
      config_logger.error("failed to retrieve %s configuration"%config_filename)

  @staticmethod
  def config_path(config_name):
    try:
      if getattr(sys, 'frozen', False):
        application_path = os.path.dirname(sys.executable)
      elif __file__:
        application_path = os.path.dirname(__file__)

      confpath = application_path + '/..' +'/config/' + config_name
      return confpath
    except:
      config_logger.error("failed to get config path")


"""
Customizes the Inception V3 model for classification.
"""

import tensorflow as tf

from network_utils import add_avg_pool, add_conv, add_fully_connected
import v3.model as model

# For the original inception-v3, input should be coming from mixed_7
# This auxillary loss should be weighted by 0.3 (as stated in the `Going Deeper with Convolutions` paper)
def add_layers_for_second_classification_head(graph, input, cfg):
  """
  Add an extra classification head to the graph, right after the second block of
  inception modules.
  """

  with graph.name_scope("second_head"):
    pool_2 = add_avg_pool(
      graph=graph,
      input=input,
      ksize=[1, 5, 5, 1],
      strides=[1, 3, 3, 1],
      padding = "VALID",
      name="pool_2"
    )

    conv = add_conv(
      graph = graph,
      input = pool_2,
      shape =  [1, 1, 768, 128],
      strides = [1, 1, 1, 1],
      padding = "SAME",
      use_batch_statistics=cfg.USE_BATCH_STATISTICS
    )

    fc = add_fully_connected(graph, conv, 1024)

  return fc

def add_layers_for_third_classification_head(graph, input, cfg):
  """
  Add a third classification head to the graph, right after the first block of
  inception modules.
  """

  with graph.name_scope("third_head"):

    pool_2 = add_avg_pool(
      graph=graph,
      input=input,
      ksize=[1, 5, 5, 1],
      strides=[1, 3, 3, 1],
      padding = "VALID",
      name="pool_2"
    )

    conv = add_conv(
      graph = graph,
      input = pool_2,
      shape =  [1, 1, 288, 128],
      strides = [1, 1, 1, 1],
      padding = "SAME",
      use_batch_statistics=cfg.USE_BATCH_STATISTICS
    )

    fc = add_fully_connected(graph, conv, 1024)

  return fc

def build(graph, inputs, cfg):
  """
  Build the inception model, and add a final layer of pooling.

  Args:
    graph: the graph to add the operations to.
    inputs: the input tensor, shape : [batch_size, height, width, dims]
    cfg: EasyDict with configuration params
  """

  base_features = model.build(graph, inputs, cfg)

  # Pool the features from the last inception layer
  pool_3 = add_avg_pool(
    graph=graph,
    input=base_features,
    ksize=[1, 8, 8, 1],
    strides=[1, 1, 1, 1],
    padding = "VALID",
    name="pool_3"
  )

  # reshape to the final feature dimension.
  features = tf.reshape(pool_3, [-1, 2048], name='features')

  return features


import math
import random

from minmaxAgent import MinMaxAgent
from game import convert_index_to_coordinates, get_possible_moves

class MinMaxRandomAgent(MinMaxAgent):
    def __init__(self,  my_token, in_row_to_win, depth=4, default_token=0, rand_threshold=0.5, if_print=True):
        super().__init__(my_token, in_row_to_win, depth, default_token)
        self.rand_threshold = rand_threshold
        self.maps = []
        self.if_print = if_print

    def make_decision(self, map):
        self.size = int(math.sqrt(len(map)))

        rand_value = random.random()
        if self.if_print:
            print(rand_value)
        if rand_value < self.rand_threshold:
            if self.if_print:
                print("rand")
            moves = get_possible_moves(map)
            index = random.randint(0, len(moves) - 1)
            move = moves[index]
            if self.if_print:
                print(move)
            self.save_map(map, move)
            return convert_index_to_coordinates(move, self.size)
        else:
            if self.if_print:
                print("minmax")
            best_move, val = self.minmax(map, depth=self.depth)
            if self.if_print:
                print(best_move)
            self.save_map(map, best_move)
            return convert_index_to_coordinates(best_move, self.size)

    def save_map(self, map, move):
        map[move] = 1
        self.maps.append(map)


import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import os

directory = os.fsencode('../stations/')
l = []
for s in os.listdir(directory):
	s = s.decode('ascii')
	if s.startswith('augusta'):
		l.append(s)
l.sort()
files = []
for i in range(len(l)):
	files.append(pd.read_csv('../stations/'+l[i], delimiter = ";"))

merged_file = pd.concat(files, axis=0, ignore_index = True)
file_clean = merged_file.replace(to_replace = '--', value='0')
file_clean['Data rilevazione'] = file_clean[file_clean.columns[2:4]].apply(
    lambda x: ','.join(x.astype(str)),
    axis=1)
df = file_clean.drop(['Ora rilevazione', 'Grandezza', 'Stazione'], axis=1)
df['Valore'] = df['Valore'].apply(lambda x: x.replace(',','.')).astype(float)

def dry_days(df):
	l = []
	c = 0
	for i in range(len(df)):
		if df['Valore'][i] == 0.0:
			c+=1
		else:
			l.append(c)
			c = 0
			continue
	l.append(c)
	return round(max(l)/144)

def wet_hours(df):
	l = []
	c = 0
	for i in range(len(df)):
		if df['Valore'][i] != 0.0:
			c+=1
			continue
		else:
			if c != 0:
				l.append(c)
				c = 0
			continue
	l.append(c)
	return round(max(l)/6)

dry_days = dry_days(df)
wet_hours = wet_hours(df)
years = [0, 52560, 105121, 157682, 210387, 262948, 315509, 368070, 420775, 473336, 525897, 578458, 631163, 683725]
df_years = []
for i in range(len(years)-1):
	df_years.append(df.iloc[years[i]:years[i+1]+1])
for i in range(len(df_years)):
	year = df_years[i]['Data rilevazione'].loc[df_years[i]['Data rilevazione'].index[5]][6:10]
	df_years[i]['Valore'].plot()
	plt.text(0.25, 0.96,'Max:'+ str(round(df['Valore'].max(),2)), fontsize=10,bbox = dict(facecolor = 'green', alpha = 0.5), transform=plt.gcf().transFigure)
	plt.text(0.02, 0.96,'Max dry days:'+ str(dry_days), fontsize=10,bbox = dict(facecolor = 'orange', alpha = 0.5), transform=plt.gcf().transFigure)
	plt.text(0.02, 0.9,'Max wet hours:'+ str(wet_hours), fontsize=10,bbox = dict(facecolor = 'orange', alpha = 0.5), transform=plt.gcf().transFigure)
	plt.xlabel('time line - 10 min intervals')
	plt.ylabel('rain - mm')
	plt.title(str(file_clean['Stazione'].loc[file_clean['Stazione'].index[5]])+' ' +year)
	plt.ylim(top=22)
	plt.savefig('results/'+str(file_clean['Stazione'].loc[file_clean['Stazione'].index[5]])+year+'.png')


import tarfile

def create_gzipped_tar_archive(tar_path, file_paths):
    with tarfile.open(tar_path, 'w:gz') as tar_file:
        for file_path in file_paths:
            tar_file.add(file_path, arcname=file_path)

def main():
    tar_path = 'example.tgz'
    file_paths = ['./example_folder/file1.txt',
                  './example_folder/file2.txt',
                  './example_folder/file3.txt']

    create_gzipped_tar_archive(tar_path, file_paths)
    print(f"{tar_path} created with the files: {', '.join(file_paths)}")

if __name__ == '__main__':
    main()


from cmlreaders import exc
from cmlreaders.base_reader import BaseCMLReader

class BaseRAMReportDataReader(BaseCMLReader):
    """Base class for all RAM report data readers."""
    protocols = ["r1"]
    default_representation = "pyobject"

    def __init__(self, data_type, subject, experiment, session, localization,
                 file_path=None, rootdir="/", **kwargs):
        super().__init__(data_type, subject=subject,
                         experiment=experiment,
                         session=session,
                         localization=localization,
                         file_path=file_path,
                         rootdir=rootdir)

        self.data_type = data_type

        try:
            from ramutils.reports.summary import (
                ClassifierSummary,
                FRStimSessionSummary,
                MathSummary,
            )
            from ramutils.utils import is_stim_experiment
            self.is_stim_experiment = is_stim_experiment
        except ImportError:
            raise exc.UnmetOptionalDependencyError(
                "Install ramutils to use this reader"
            )

        self.pyclass_mapping = {
            'classifier_summary': ClassifierSummary,
            'fr_stim_summary': FRStimSessionSummary,
            'math_summary': MathSummary,
        }

    def as_pyobject(self):
        """Return data as a python object specific to this data type."""
        if self.data_type in self.pyclass_mapping:
            return self.pyclass_mapping[self.data_type].from_hdf(
                self.file_path)

    def as_dataframe(self):
        raise exc.UnsupportedRepresentation("Unable to represent this data as "
                                            "a dataframe")

class RAMReportClassifierSummaryReader(BaseRAMReportDataReader):
    """Reader class for classifier summary data produced in the RAM reporting
    pipeline.

    Notes
    -----
    By default, a python class is returned. For report data read with this
    class a python object is the only supported return type. The returned class
    will be `ramutils.reports.summary.ClassifierSummary`

    """
    data_types = ["classifier_summary"]

class RAMReportSummaryDataReader(BaseRAMReportDataReader):
    """
        Reader class for session and math summary data produced in the
        reporting pipeline

    Notes
    -----
    By default, a python class is returned based on the type of data. It could
    be one of

    - `ramutils.reports.summary.MathSummary`
    - `ramutils.reports.summary.FRStimSessionSummary`

    """
    data_types = ["session_summary", "math_summary"]

    def __init__(self, data_type, subject, experiment, session, localization,
                 file_path=None, rootdir="/", **kwargs):
        super().__init__(data_type, subject=subject,
                         experiment=experiment,
                         session=session,
                         localization=localization,
                         file_path=file_path,
                         rootdir=rootdir)
        self.data_type = data_type
        self.subject = subject
        self.experiment = experiment
        self.session = session

    def as_pyobject(self):
        if self.data_type == "math_summary":
            return super().as_pyobject()

        stim_experiment = self.is_stim_experiment(self.experiment)

        # TODO: Loading record-only data is a bit more complicated since it is
        # not tied to a particular session
        if not stim_experiment:
            raise exc.UnsupportedExperimentError(
                "Only stim report data is currently supported."
                "The readers in ramutils can still be used"
            )

        summary_obj = self.pyclass_mapping['fr_stim_summary']

        return summary_obj.from_hdf(self.file_path)

    def as_dataframe(self):
        pyobj = self.as_pyobject()
        return pyobj.to_dataframe()


# https://www.codewars.com/kata/which-string-is-worth-more/train/python

def highest_value(a,b):
    atotal, btotal = 0, 0

    for achar in set(list(a)):
        atotal += ord(achar)

    for bchar in set(list(b)):
        btotal += ord(bchar)

    return a if atotal >= btotal else b


import grpc
import pytest

from couchers import errors
from couchers.db import session_scope
from couchers.models import Cluster, User
from couchers.servicers.admin import Admin
from proto import admin_pb2, admin_pb2_grpc
from tests.test_fixtures import db, generate_user, get_user_id_and_token, real_session, testconfig  # noqa

@pytest.fixture(autouse=True)
def _(testconfig):
    pass

NORMAL_USER_NAME = "normal_user"
SUPER_USER_NAME = "super_user"
NORMAL_USER_EMAIL = "normal@user.com"
COMMUNITY_NAME = "test community"
COMMUNITY_SLUG = "test-community"
COMMUNITY_DESCRIPTION = "community for testing"
VALID_GEOJSON_MULTIPOLYGON = """
    {
      "type": "MultiPolygon",
      "coordinates":
       [
        [
          [
            [
              -73.98114904754641,
              40.7470284264813
            ],
            [
              -73.98314135177611,
              40.73416844413217
            ],
            [
              -74.00538969848634,
              40.734314779027144
            ],
            [
              -74.00479214294432,
              40.75027851544338
            ],
            [
              -73.98114904754641,
              40.7470284264813
            ]
          ]
        ]
      ]
    }
"""
POINT_GEOJSON = """
{ "type": "Point", "coordinates": [100.0, 0.0] }
"""

def _admin_session(token: str):
    return real_session(token, admin_pb2_grpc.add_AdminServicer_to_server, Admin(), admin_pb2_grpc.AdminStub)

def _get_super_token():
    with session_scope() as session:
        _, super_token = get_user_id_and_token(session, SUPER_USER_NAME)
        return super_token

def _get_normal_user(session):
    return session.query(User).filter(User.username == NORMAL_USER_NAME).one_or_none()

def _get_super_user(session):
    return session.query(User).filter(User.username == SUPER_USER_NAME).one_or_none()

def _generate_normal_user(session):
    generate_user(username=NORMAL_USER_NAME, email=NORMAL_USER_EMAIL)

def _generate_super_user(session):
    generate_user(username=SUPER_USER_NAME, is_superuser=True)

def test_AccessByNormalUser(db):
    with session_scope() as session:
        _generate_normal_user(session)
        normal_user_id, normal_token = get_user_id_and_token(session, NORMAL_USER_NAME)
        with _admin_session(normal_token) as api:

            # all requests to the admin servicer should break when done by a non-super_user
            with pytest.raises(grpc.RpcError) as e:
                api.GetUserEmailById(
                    admin_pb2.GetUserEmailByIdReq(
                        user_id=normal_user_id,
                    )
                )
            assert e.value.code() == grpc.StatusCode.PERMISSION_DENIED

def test_GetEmailByUserId(db):
    with session_scope() as session:
        _generate_normal_user(session)
        _generate_super_user(session)
        normal_user = _get_normal_user(session)
        with _admin_session(_get_super_token()) as api:
            res = api.GetUserEmailById(admin_pb2.GetUserEmailByIdReq(user_id=normal_user.id))
        assert res.email == NORMAL_USER_EMAIL
        assert res.user_id == normal_user.id

def test_GetEmailByUserName(db):
    with session_scope() as session:
        _generate_normal_user(session)
        _generate_super_user(session)
        normal_user = _get_normal_user(session)
        with _admin_session(_get_super_token()) as api:
            res = api.GetUserEmailByUsername(admin_pb2.GetUserEmailByUsernameReq(username=normal_user.username))
            assert res.email == NORMAL_USER_EMAIL
            assert res.user_id == normal_user.id

def test_GetBanUser(db):
    with session_scope() as session:
        _generate_normal_user(session)
        _generate_super_user(session)
        with _admin_session(_get_super_token()) as api:
            normal_user = _get_normal_user(session)
            api.BanUser(admin_pb2.BanUserReq(user_id=normal_user.id))
            session.refresh(normal_user)
            assert normal_user.is_banned

def test_GetDeleteUser(db):
    with session_scope() as session:
        _generate_normal_user(session)
        _generate_super_user(session)
        with _admin_session(_get_super_token()) as api:
            normal_user = _get_normal_user(session)
            api.DeleteUser(admin_pb2.DeleteUserReq(user_id=normal_user.id))
            session.refresh(normal_user)
            assert normal_user.is_deleted

def test_CreateCommunityInvalidGeoJson(db):
    with session_scope() as session:
        _generate_normal_user(session)
        _generate_super_user(session)
        with _admin_session(_get_super_token()) as api:
            with pytest.raises(grpc.RpcError) as e:
                api.CreateCommunity(
                    admin_pb2.CreateCommunityReq(
                        name=COMMUNITY_NAME,
                        slug=COMMUNITY_SLUG,
                        description=COMMUNITY_DESCRIPTION,
                        admin_ids=[],
                        geojson=POINT_GEOJSON,
                    )
                )
            assert e.value.code() == grpc.StatusCode.INVALID_ARGUMENT
            assert e.value.details() == errors.NO_MULTIPOLYGON

def test_CreateCommunity(db):
    with session_scope() as session:
        _generate_normal_user(session)
        _generate_super_user(session)
        with _admin_session(_get_super_token()) as api:
            api.CreateCommunity(
                admin_pb2.CreateCommunityReq(
                    name=COMMUNITY_NAME,
                    slug=COMMUNITY_SLUG,
                    description=COMMUNITY_DESCRIPTION,
                    admin_ids=[],
                    geojson=VALID_GEOJSON_MULTIPOLYGON,
                )
            )
            community = session.query(Cluster).filter(Cluster.name == COMMUNITY_NAME).one()
            assert community.description == COMMUNITY_DESCRIPTION
            assert community.slug == COMMUNITY_SLUG


from datetime import date
from decimal import Decimal

from django.test import TestCase

from charcoallog.investments.forms import InvestmentDetailsForm
from charcoallog.investments.models import NewInvestmentDetails

class InvestmentDetailsFormTest(TestCase):
    def test_form_has_fields(self):
        """ Form must have 3 fields. The third field is in test_basicdata_form"""
        form = InvestmentDetailsForm()
        self.assertSequenceEqual(
            ['date', 'money', 'kind', 'tx_op',
             'brokerage', 'which_target', 'segment',
             'tx_or_price', 'quant'],
            list(form.fields)
        )

class InvestmentDetailSave(TestCase):
    def setUp(self):
        data = dict(
            user_name='teste',
            date='2018-09-19',
            money='10.00',
            kind='tesouro',
            tx_op=0.00,
            brokerage='A',
            which_target='selic',
            segment='2023',
            tx_or_price=0.00,
            quant=0.00,
        )
        self.form = InvestmentDetailsForm(data)

    def test_is_valid(self):
        self.assertTrue(self.form.is_valid())

    def test_save(self):
        """
        .save() param must exists. That's why the test.
        """
        self.form.save('teste')

        qs = NewInvestmentDetails.objects.all()
        expected = [
            (qs[0].which_target, 'selic'),
            (qs[0].segment, '2023'),
            (qs[0].tx_or_price, Decimal('0.00')),
            (qs[0].quant, 0.00),
            (qs[0].user_name, 'teste'),
            (qs[0].date, date(2018, 9, 19)),
            (qs[0].money, Decimal('10.00')),
            (qs[0].kind, 'tesouro'),
            (qs[0].tx_op, Decimal('0.00')),
            (qs[0].brokerage, 'A'),
        ]

        for obj, v in expected:
            with self.subTest():
                self.assertEqual(obj, v)


from pico2d import *
import random
import time
import game_world
import box
import scroll_state

class IdleState:
    @staticmethod
    def enter(boy):
        boy.time = time.time()
        boy.frame = 0
    @staticmethod
    def exit(boy):
        pass
    @staticmethod
    def update(boy):
        boy.frame = (boy.frame + 3 * game_world.ACTION_PER_TIME * game_world.frame_time) % 3
    @staticmethod
    def draw(boy):
        if boy.dir == 1:
            boy.src_y = 96
        elif boy.dir == 2:
            boy.src_y = 192
        elif boy.dir == 3:
            boy.src_y = 0
        elif boy.dir == 4:
            boy.src_y = 288
        boy.image.clip_draw(96, 288, 96, 96, boy.x,boy.y)
#        Boy.image.clip_draw(boy.fram e * 100, y, 100, 100, *boy.pos())
    def get_bb(self):
        return (self.x - 40, self.y - 40, self.x + 40, self.y + 40)

class RunState:
    MARGIN = 25
    @staticmethod
    def enter(boy):
        boy.time = time.time()
        boy.frame = 0
    @staticmethod
    def exit(boy):
        pass
    @staticmethod
    def update(boy):
        #elapsed = time.time() - boy.time
       # mag = 2 if elapsed > 2.0 else 1
        # print(mag, elapsed)
        boy.frame = (boy.frame + 3 * game_world.ACTION_PER_TIME * game_world.frame_time) % 3

    @staticmethod
    def draw(boy):
        boy.src_y = 0
        if boy.dir == 1:
            boy.src_y = 192
        elif boy.dir == 2:
            boy.src_y = 96
        elif boy.dir == 3:
            boy.src_y = 0
        elif boy.dir == 4:
            boy.src_y = 288
        boy.image.clip_draw(int(boy.frame) * 96, boy.src_y, 96, 96, boy.x,boy.y)

okay_right = False
okay_left = False
okay_up = False
okay_down = False

sheet_idle = load_image('../res/sheet_idle.png')
sheet_dig = load_image('../res/sheet_dig.png')
class Boy:
    image = None

    def __init__(self):
        global okay_right, okay_left, okay_up, okay_down
        print("Creating..")
        self.x = 400
        self.y = 300  # 손대지말기
        self.hand_image = load_image("../res/hand.png")
        self.attacking = False
        self.src_y = 0
        self.attack = False
        self.moving = False
        self.hand_frame = 0
        self.wall_touch = False
        self.speed = random.uniform(5.0, 8.0)
        self.frame = random.randint(0, 7)
        self.state = None
        self.set_state(IdleState)
        self.dir = 1        #좌우
        self.dir_up_down = 0    #상하

        self.image = sheet_idle

    def get_bb(self):
        return (self.x - 25, self.y - 30, self.x + 25, self.y + 30)

    def pos(self):
       # return self.x - self.bg.x, self.y - self.bg.y
        pass
    def draw(self):
        if self.attacking:

            if self.dir == 1:
                sheet_dig.clip_draw(int(self.hand_frame) * 96, self.src_y, 96, 96, self.x , self.y)
            elif self.dir == 2:
                sheet_dig.clip_draw(int(self.hand_frame) * 96, self.src_y, 96, 96, self.x , self.y)
            elif self.dir == 3:
                sheet_dig.clip_draw(int(self.hand_frame) * 96, self.src_y, 96, 96, self.x , self.y)
            elif self.dir == 4:
                sheet_dig.clip_draw(int(self.hand_frame) * 96, self.src_y, 96, 96, self.x , self.y)
        else: self.state.draw(self)
    def update(self):
        self.state.update(self)
        if self.attacking:
            self.hand_frame = (self.hand_frame + 3 * game_world.ACTION_PER_TIME * game_world.frame_time) % 4
            if self.hand_frame > 3:
                self.hand_frame = 0
                self.attacking = False
        self.collider()
    def handle_event(self):
        pass

    def set_dir(self,_dir):
        self.dir = _dir
    def collider(self):
        for i in scroll_state.boxs:
            if i.active == False: continue
            if i.get_bb(self):
                self.wall_touch = True

                return

        scroll_state.right_key_lock = False
        scroll_state.left_key_lock = False
        scroll_state.up_key_lock = False
        scroll_state.down_key_lock = False
    def dig(self):
        if self.dir == 1:
            print("왼쪽")
            for i in scroll_state.boxs:
                if i.active== False :continue
                if i.x + 50 > self.x - 50 and i.y -50 < self.y and i.y + 50 > self.y:
                    i.active = False
                    break;
        elif self.dir == 2:
            print("오른쪽")
            for i in scroll_state.boxs:
                if i.active == False: continue
                if  self.x + 50  > i.x - 50and self.x < i.x-50 and i.y - 50 < self.y and i.y+ 50 > self.y:
                    i.active = False
                    break;
        elif self.dir == 3:
            print("ㅁㅁ")
            for i in scroll_state.boxs:
                if i.active == False: continue
                if i.y - 50 < self.y + 50and self.y < i.y-50 and i.x - 50 < self.x and i.x + 50 > self.x:
                    i.active = False
                    break;
        elif self.dir == 4:
            for i in scroll_state.boxs:
                if i.active == False: continue
                if i.y + 50 > self.y - 50 and i.x - 50 < self.x and i.x + 50 > self.x:
                    i.active = False
                    break;
    def set_state(self, state):
        if self.state == state: return

        if self.state and self.state.exit:
            self.state.exit(self)

        self.state = state

        if self.state.enter:
            self.state.enter(self)

    # def fire_ball(self, big):
    #     mag = 1.5 if self.dir == 1 else -1.5
    #     ballSpeed = mag * self.speed + self.dx

    #     ySpeed = 2 * self.speed * (1 + random.random())
    #     if big: ySpeed *= 0.75
    #     ball = Ball(big, self.x, self.y, ballSpeed, ySpeed)
    #     game_world.add_object(ball, game_world.layer_obstacle)


# n=int(input())
# words=list(map(str,input().split()))
# words = ["fruit", "freetime", "time", "me", "apple"]
# words = ["time", "me", "bell"]
# words = ["me", "time"]
words = ["p", "grah", "qwosp"]
ans = ""
temp = []
temp.append(words[0])
temptr = 0

for i in range(1, len(words)):
    flag = True
    curr = words[i]
    seen = temp[temptr]
    if (curr in seen):
        if (curr[-1] == seen[-1]):
            flag = False
    if (seen in curr):
        if (seen[-1] == curr[-1]):
            flag = False
            temp.pop()
            temp.append(words[i])
            temptr += 1
    if (flag):
        temp.append(words[i])
        temptr += 1

ans = "#".join(temp)
ans = ans+"#"
print(ans)


#!/usr/bin/env python3

speeds = [3.5, 2.5, 1.5, 1, 0.75, 0.5]
chances = [0.5, 0.6, 0.7, 0.8, 0.85, 0.95]
dmgs = list(range(1, 7))

def dps(dmg, chance, speed):
    return int(dmgs[dmg] * chances[chance] * 1 / speeds[speed] * 100)

def best(dmg, chance, speed):
    a = dps(dmg + 1, chance, speed) if dmg < 5 else 0
    b = dps(dmg, chance + 1, speed) if chance < 5 else 0
    c = dps(dmg, chance, speed + 1) if speed < 5 else 0
    m = max(a, b, c)
    return ["", "d"][a == m] + ["", "c"][b == m] + ["", "s"][c == m]

for dmg in range(6):
    print("dmg", dmgs[dmg])
    for chance in range(6):
        print(
            chances[chance],
            "\t",
            "\t".join(
                best(dmg, chance, speed) + "|" + str(dps(dmg, chance, speed))
                for speed in range(6)
            ),
        )
    print()


from kitsune.postcrash.tests import SignatureFactory
from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse

class ApiTests(TestCase):
    def test_no_signature(self):
        response = self.client.get(reverse("postcrash.api"))
        self.assertEqual(400, response.status_code)
        self.assertEqual(b"", response.content)
        self.assertEqual("text/plain", response["content-type"])

    def test_unknown_signature(self):
        url = urlparams(reverse("postcrash.api"), s="foo")
        response = self.client.get(url)
        self.assertEqual(404, response.status_code)
        self.assertEqual(b"", response.content)
        self.assertEqual("text/plain", response["content-type"])

    def test_known_signature(self):
        sig = SignatureFactory()
        url = urlparams(reverse("postcrash.api"), s=sig.signature)
        response = self.client.get(url)
        self.assertEqual(200, response.status_code)
        self.assertEqual(
            "https://example.com/kb/%s" % sig.document.slug, response.content.decode()
        )
        self.assertEqual("text/plain", response["content-type"])


import math

delintervaller = 100000
# Areal
def areal():
    intervall = b - a
    deltax = intervall/delintervaller
    i = 0
    x = a
    s = 0
    while x <= intervall:
        if s == 0:
            s = 1
            i = i + ((1/2)*(f(x)))
        else:
            i = i + f(x)
        x = x + deltax
    nsx = x-deltax
    i = i - f(nsx)
    i = i + ((1/2)*f(intervall))
    return(i*(deltax))

def areal2():
    intervall = b - a
    deltax = intervall/delintervaller
    i = 0
    x = a
    while x < b:
        i = i + (f(x)*deltax)
        x = x + deltax
    return i

def f(x):
    return (1/(x*x))
a = 1
b = math.inf
print(areal2())


t = int(input())
for tc in range(1, t + 1):
    n = int(input())
    cnt = [0] * 201
    for i in range(n):
        s, e = map(int, input().split())
        if s > e:
            s, e = e, s
        s = (s + 1) // 2
        e = (e + 1) // 2
        for j in range(s, e + 1):
            cnt[j] += 1
    print(f'#{tc} {max(cnt)}')

4408_자기 방으로 돌아가기.py


num=media=soma=cont=maior=menor=0

while True:
    num=int(input('Insira a sua idade: '))
    if num==0: break

    cont+=1
    soma+=num
    media=soma/(cont)

    if cont==1:
        maior=menor=num
    else:
        if num>maior:
            maior=num
        if num<menor:
            menor=num

if cont!=0:
    print(f'\n{cont} pessoas inseriram suas idades.')
if media!=0:
    print(f'\nA média de idade é {media:.2f}.')

if menor!=0:
    print(f'\nA maior idade inserida foi {menor}.')
if maior!=0:
    print(f'\nA menor idade inserida foi {maior}.')


import subprocess as p
from multiprocessing.dummy import Pool as ThreadPool

def check_ip(ip):
    ip = ip.strip()
    w=p.Popen('ping -c 2 '+ip, shell=True, stdout=p.PIPE, stderr=p.PIPE)
    out, err = w.communicate()
    other_info = out.decode('utf-8')
    if 'ttl' in other_info or 'TTL' in other_info:
        pass
    else:
        print(ip,'is down')

with open('aliyun_ips_private.txt', 'r') as f:
    ips = f.readlines()
    try:
        pool = ThreadPool(30)
        pool.map(check_ip, ips)
        pool.close()
        pool.join()
    except Exception as e:
        print(e)


#!/usr/bin/env python
import pika

import sys, time, datetime
from pathlib import Path
# Se o cliente for executado no windows ou Visual Studio Code, descomentar a linha abaixo
#sys.path.insert(0, str(Path().resolve()))
# Se o cliente for executado no linux, descomentar a linha abaixo
sys.path.insert(0, str(Path().resolve().parent))
#print Path().resolve()
from data import Data
import util

TAB_1 = '\t - '

class Client():
    _dados = Data()
    startExperimentTS = ''
    channel = ''
    queue = 'tcc_amqp'

    def establishConnection(self, address='localhost', port=5672):
        dataTest = 'Hello World!'
        print('endereco: ' + address)
        print('porta: ' + str(port))
        print('dados: ' + dataTest)

        credentials = pika.PlainCredentials('pi','raspberry')
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=address, credentials=credentials))
        self.channel = connection.channel()
        self.channel.queue_declare(self.queue)
        response = self.channel.basic_publish(exchange='', routing_key=self.queue, body=dataTest)
        print(response)

    def startExperiment(self, reps=-1, timePerRep=1):
        """
		Inicia o Experimento
		>>Reps: quantidade de repetições que o experimento terá.
				Cada repetição é igual a 1 pacote enviado.
				Caso seja <= 0 serão enviados todos os dados disponíveis
		>>timePerRep:
				intervalo de tempo entre repetição, em segundos.
				Padrão = 1seg
		"""
        print("\nIniciando o experimento às {0}".format(
            util.getFormattedDatetimeWithMillisec()))

        if (reps <= 0):
            reps = self._dados.length()
        print("Quantidade de pacotes que serão enviados: {}".format(reps))
        duracao = timePerRep * reps
        print("Tempo estimado de duração do experimento: {} ({})\n".format(
            util.getFormattedDateTimeFromSeconds(duracao),
            str(datetime.timedelta(seconds=duracao))))

        for i in range(0, reps):
            print("iniciando repetição {} às {}".format(
                i + 1, str(util.getFormattedDatetimeWithMillisec())))
            self.sendPackage(i)
            time.sleep(timePerRep)
        print('Fechando a conexão...')
        self.channel.connection.close()
        print('Finalizado!')

    def sendPackage(self, index):
        print(TAB_1 + "Enviando pacote ...")
        response = self.channel.basic_publish(
            exchange='',
            routing_key=self.queue,
            body=self._dados.getByIndex(index).encode())
        print(TAB_1 + 'enviado: ' + str(response))

def main():
    client = Client()
    address = input(
        'Digite o endereco do servidor: (ou deixe em branco caso seja "localhost")\n'
    )
    if (address == ''):
        client.establishConnection()
    else:
        client.establishConnection(address=address)

    reps = input(
        '\nDigite a quantidade de pacotes que você deseja enviar: (ou deixe em branco para enviar a quantidade máxima possível )\n'
    )
    try:
        reps = int(reps)
    except ValueError:
        reps = -1

    client.startExperiment(reps)

if __name__ == '__main__':
    main()

# print(" [x] Sent 'Hello World!'")


from datetime import datetime
from pynput.keyboard import Key, Controller
import time, os
keyboard = Controller()

browser = "google-chrome"     # replace it with your browser
link = "jcx-sgnp-dra"        # set your link here
meet_time = ("12:14:30")   # set your time here

def presstabkey(num, tym, keys):

	time.sleep(tym)
	while num > 0 :
		keyboard.press(keys)
		keyboard.release(keys)
		num = num-1
	keyboard.press(Key.enter)
	keyboard.release(Key.enter)

while True:
	now = datetime.now()
	if now.strftime("%H:%M:%S")  == meet_time:
	    os.system("gnome-terminal -e '"+browser+" http://meet.google.com/"+link+"'")
	    presstabkey(8, 20, Key.tab)
	    break


import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
from PyQt5 import uic

import pandas as pd
import openpyxl
import datetime as pydatetime

form_class = uic.loadUiType("ui/main_page_test.ui")[0]

class WindowClass(QMainWindow, form_class) :
    def __init__(self) :
        super().__init__()
        self.initUI()
        self.show()

    def initUI(self):
        self.ts = self.get_now_timestamp()
        self.df = pd.DataFrame([['EXP_START', self.ts, -1, -1]],
                               index=[1], columns=['status', 'ts', 'ans', 'confidence'])

        self.setupUi(self)

        self.expInfoDict = {"name":"", "birth":"", "expCnt":"", "1st_ts":str(self.ts)}

        self.submitBtn.clicked.connect(self.submitBtn_clicked)

    def submitBtn_clicked(self):
        self.expInfoDict['name'] = self.nameLEdit.text()
        self.expInfoDict['birth'] = self.birthLEdit.text()
        self.expInfoDict['expCnt'] = self.expCntLEdit.text()
        self.expInfoDict['2nd_ts'] = str(self.get_now_timestamp())

        print('expInfo', self.expInfoDict)

        nowTime = pydatetime.datetime.today().strftime("%Y%m%d%H%M%S")
        print(nowTime)

        exit(1)
        # fileName = self.expInfoDict['name']+self.expInfoDict['birth']+
        # self.df.to_csv('output/'+self.expInfoDict['name'])

    def get_now(self):
        # 현재 시스템 시간을 datetime형으로 반환
        return pydatetime.datetime.now()

    def get_now_timestamp(self):
        # 현재 시스템 시간을 POSIX timestamp float형으로 반환
        return self.get_now().timestamp()

if __name__ == "__main__" :
    app = QApplication(sys.argv)
    myWindow = WindowClass()
    myWindow.show()
    app.exec_()


import numpy as np
import pandas as pd
import pytest
from sklearn.base import clone
from sklearn.pipeline import Pipeline
from sklearn.utils.estimator_checks import check_estimator

from feature_engine.timeseries.forecasting import (
    ExpandingWindowFeatures,
    LagFeatures,
    WindowFeatures,
)
from tests.estimator_checks.estimator_checks import check_feature_engine_estimator

_estimators = [
    LagFeatures(missing_values="ignore"),
    WindowFeatures(missing_values="ignore"),
    ExpandingWindowFeatures(missing_values="ignore"),
]

@pytest.mark.parametrize("estimator", _estimators)
def test_check_estimator_from_sklearn(estimator):
    return check_estimator(estimator)

@pytest.mark.parametrize("estimator", _estimators)
def test_check_estimator_from_feature_engine(estimator):
    return check_feature_engine_estimator(estimator)

@pytest.mark.parametrize("estimator", _estimators)
def test_error_when_not_unique_values_in_index(df_time, estimator):
    X = df_time.copy()

    # introduce dupes in index
    tmp = X.head(2).copy()
    tmp.iloc[0] = [1, 1, 1, "blue"]
    Xd = pd.concat([X, tmp], axis=0)

    transformer = clone(estimator)

    with pytest.raises(NotImplementedError):
        transformer.fit(Xd)

    transformer.fit(X)
    with pytest.raises(NotImplementedError):
        transformer.transform(Xd)

@pytest.mark.parametrize("estimator", _estimators)
def test_error_when_nan_in_index(df_time, estimator):
    X = df_time.copy()

    # Introduce NaN in index.
    tmp = X.head(1).copy()
    tmp.index = [np.nan]
    Xd = pd.concat([X, tmp], axis=0)

    transformer = clone(estimator)

    with pytest.raises(NotImplementedError):
        transformer.fit(Xd)

    transformer.fit(X)
    with pytest.raises(NotImplementedError):
        transformer.transform(Xd)

@pytest.mark.parametrize("transformer", _estimators)
def test_transformers_in_pipeline_with_set_output_pandas(df_time, transformer):
    X = df_time.copy()

    pipe = Pipeline([("trs", transformer)]).set_output(transform="pandas")

    Xtt = transformer.fit_transform(X)
    Xtp = pipe.fit_transform(X)

    pd.testing.assert_frame_equal(Xtt, Xtp)


import math
import numpy as np
import matplotlib.pyplot as plt
File = open("Galaxy1.txt","r")
next(File)
radius=[]
V=[]
mV=[]
m=[]
DMmassV=[]
CmassV=[]

#m[radius.index(i)]+ 4*math.pi*(100*10**6)*(1.87**2)*(i-1.87*np.arctan(i/1.87))

for i in File.readlines():
    radius.append(float(i.split()[0]))
    V.append(float(i.split()[1]))
    m.append(float(i.split()[4]))

for i in radius:
    DMmassV.append(math.sqrt((4.3*10**-6)*4*math.pi*(100*10**6)*(1.87**2)*(i-1.87*np.arctan(i/1.87))*1/i))
for i in radius:
    CmassV.append(math.sqrt((4.3*10**-6)*(m[radius.index(i)]+4*math.pi*(100*10**6)*(1.87**2)*(i-1.87*np.arctan(i/1.87)))*1/i))
for i in radius:
    mV.append(math.sqrt((4.3*10**-6)*m[radius.index(i)]*1/i))

mV=np.array(mV)
radius = np.array(radius)
y = np.array(DMmassV)
CmassV = np.array(CmassV)
plt.plot(radius,CmassV)#combined DM and Visable mass
plt.plot(radius,mV)#prediction based on mass from data
plt.plot(radius,y)#DM
plt.plot(radius,V)#actual data
plt.xlabel("Radius (kpc)")
plt.ylabel("Velocity (kms^-1)")
plt.axis([0,max(radius),0,max(V)+2])
plt.show()


# coding:utf-8
'''
全局变量
    在python脚本的最上层代码块的变量
    全局变量可以在寒素内被读取使用（不能被修改）
局部变量
    在函数体内定义的变量
    局部变量无法在自身函数以外使用
'''
name = 'zlw'
def test():
    print(name)
test()
def test1():
    name = '曾丽文'
    print('函数体内',name)
test1()
print('函数体外',name)

'''
global
    将全局变量可以在函数体内进行修改
    工作中：不建议使用global对全局变量修改
仅支持：字符串，数字，空类型，布尔类型
列表，字典不需要global进行声明，就可以在函数内修改
'''
def test2():
    global name
    name = 10

test2()
print(name)

test_dict = {'a':1,'b':2}
def test3():
    test_dict['c'] = 3
    test_dict.pop('a')

test3()
print(test_dict)

08函数的定义与使用/04局部变量与全局变量.py

04局部变量与全局变量.py


from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout

app = QApplication([])
main_win = QWidget()

main_win.setWindowTitle('TRASH')
main_win.resize(400, 250)

label = QLabel("Натисни щоб дізнатись переможця")
result = QLabel("?")
btn = QPushButton('Згенерувати')

line = QVBoxLayout()
line.addWidget(label)
line.addWidget(result)
line.addWidget(btn)

main_win.setLayout(line)
main_win.show()
app.exec_()


from django.shortcuts import render, redirect
from .models import Show
from django.contrib import messages

def shows(request):
    context = {
        "shows":Show.objects.all()
    }
    return render(request, "index.html", context)

def index(request):
    return redirect("/shows")

def new_show(request):
    return render(request, "new_show.html")

def add_new_show(request):
    errors = Show.objects.basic_validator(request.POST)
    if len(errors) > 0:
        for key, value in errors.items():
            messages.error(request, value)
        return redirect(f"/shows/new")
    else:
        new_show = Show.objects.create(title = request.POST['title'],
            description = request.POST['description'],
            network = request.POST['network'],
            release_date = request.POST['release_date']
            )
        return redirect(f"/shows/{new_show.id}")

def show(request, show_id):
    context = {
        "show":Show.objects.get(id = show_id)
    }
    return render(request, "show.html", context)

def edit_show(request, show_id):
    context = {
        "show":Show.objects.get(id = show_id)
    }
    return render(request, "edit_show.html", context)

def update_show(request, show_id):
    errors = Show.objects.basic_validator(request.POST)
    if len(errors) > 0:
        for key, value in errors.items():
            messages.error(request, value)
        return redirect(f"/shows/{show_id}/edit")
    else:
        new_show = Show.objects.get(id = show_id)
        new_show.title = request.POST['title']
        new_show.description = request.POST['description']
        new_show.network = request.POST['network']
        new_show.release_date = request.POST['release_date']
        new_show.save()
        return redirect(f"/shows/{new_show.id}")

def delete_show(request, show_id):
    show = Show.objects.get(id = show_id)
    show.delete()
    return redirect("/shows")


__author__ = 'admin'

import unittest

import os,sys
lib_path = os.path.abspath('../src')
sys.path.append(lib_path)

from ScopeBuilder import *
from Parser import *
from ContextManager import *
from Context import *
from DefaultContext import *
from DeclarationContext import *
from ExpressionContext import *
from FlowControlContext import *

class TestScope(unittest.TestCase):
    def setUp(self):
        self.manager = ContextManager()
        self.context = Context(self.manager)
        self.defaultContext = DefaultContext(self.manager)
        self.declarationContext = DeclarationContext(self.manager)
        self.expressionContext = ExpressionContext(self.manager)
        self.flowControlContext = FlowControlContext(self.manager)
        self.contexts = [self.declarationContext, self.expressionContext, self.flowControlContext, self.defaultContext]
        self.manager.addContext('Default', self.defaultContext)
        self.manager.addContext('Declaration', self.declarationContext)
        self.manager.addContext('Expression', self.expressionContext)
        self.manager.addContext('FlowControl', self.flowControlContext)
        self.manager.setCurrentContexts(self.contexts)

    def test_buildScope(self):
        scopeBuilder = ScopeBuilder()
        declToken = self.declarationContext.createDeclarationOrDefinitionToken('(decl)')
        intToken = self.context.createToken('int')
        xToken = self.context.createToken('x')
        declToken.data.append(intToken)
        declToken.data.append(xToken)

        scopeBuilder.buildScope(declToken)
        self.assertEqual([declToken], scopeBuilder.scope.list)
        self.assertEqual(['x'], scopeBuilder.scope.displayList)

    def test_buildScope_nested_brace(self):
        scopeBuilder = ScopeBuilder()
        declToken = self.declarationContext.createDeclarationOrDefinitionToken('(decl)')
        intToken = self.context.createToken('int')
        xToken = self.context.createToken('x')
        declToken.data.append(intToken)
        declToken.data.append(xToken)
        braceToken = self.context.createToken('{')

        scopeBuilder.buildScope(declToken)
        self.assertEqual(['x'], scopeBuilder.scope.displayList)
        scopeBuilder.buildScope(braceToken)
        self.assertEqual(['x', []], scopeBuilder.scope.displayList)
        scopeBuilder.buildScope(declToken)
        self.assertEqual(['x', ['x']], scopeBuilder.scope.displayList)

    def test_buildScope_findLocal(self):
        scopeBuilder = ScopeBuilder()
        declToken1 = self.declarationContext.createDeclarationOrDefinitionToken('(decl)')
        declToken2 = self.declarationContext.createDeclarationOrDefinitionToken('(decl)')
        intToken = self.context.createToken('int')
        xToken = self.context.createToken('x')
        declToken1.data.append(intToken)
        declToken1.data.append(xToken)
        declToken2.data.append(intToken)
        declToken2.data.append(xToken)
        braceToken = self.context.createToken('{')

        scopeBuilder.buildScope(declToken1)
        localToken = scopeBuilder.findLocal('x')
        self.assertEqual(declToken1, localToken)

        scopeBuilder.buildScope(braceToken)
        localToken = scopeBuilder.findLocal('x')
        self.assertEqual(None, localToken)

        scopeBuilder.buildScope(declToken2)
        localToken = scopeBuilder.findLocal('x')
        self.assertEqual(declToken2, localToken)
        self.assertNotEqual(declToken1, localToken)

    def test_buildScope_(self):
        scopeBuilder = ScopeBuilder()
        declToken1 = self.declarationContext.createDeclarationOrDefinitionToken('(decl)')
        intToken1 = self.context.createToken('int')
        xToken = self.context.createToken('x')
        declToken2 = self.declarationContext.createDeclarationOrDefinitionToken('(decl)')
        intToken2 = self.context.createToken('int')
        yToken = self.context.createToken('y')
        declToken1.data.append(intToken1)
        declToken1.data.append(xToken)
        declToken2.data.append(intToken2)
        declToken2.data.append(yToken)
        braceToken = self.context.createToken('{')

        scopeBuilder.buildScope(declToken1)  # scope = [x]
        scopeBuilder.buildScope(braceToken)  # scope = [x, []]
        localToken = scopeBuilder.findLocal('x')
        self.assertEqual(None, localToken)
        globalToken = scopeBuilder.findGlobal('x')
        self.assertEqual(declToken1, globalToken)
        globalToken = scopeBuilder.findGlobal('y')
        self.assertEqual(None, globalToken)

        scopeBuilder.buildScope(declToken2)  # scope = [x, [y]]
        localToken = scopeBuilder.findLocal('x')
        self.assertEqual(None, localToken)
        localToken = scopeBuilder.findLocal('y')
        self.assertEqual(declToken2, localToken)
        globalToken = scopeBuilder.findGlobal('x')
        self.assertEqual(declToken1, globalToken)
        globalToken = scopeBuilder.findGlobal('y')
        self.assertEqual(declToken2, globalToken)
        globalToken = scopeBuilder.findGlobal('z')
        self.assertEqual(None, globalToken)

"""
    def test_buildScope_will_only_care_declaration_but_not_expression(self):
        lexer = LexerStateMachine('int x ;\
                                   x = 2 + 3 ;', self.context)
        scopeBuilder = ScopeBuilder()
        parser = Parser(lexer, self.manager)
        self.manager.setParser(parser)

        token = parser.parseStatements(0)

        self.assertEqual(['x'], scopeBuilder.scopeHistory[0])
        self.assertEqual(['x'], scopeBuilder.scopeHistory[1])

    def test_buildScope_to_deal_with_curly_brace(self):
        lexer = LexerStateMachine('int x ; { int y ; }', self.context)
        scopeBuilder = ScopeBuilder()
        parser = Parser(lexer, self.manager)
        self.manager.setParser(parser)

        token = parser.parseStatements(0)

        self.assertEqual(['x'], scopeBuilder.scopeHistory[0])
        self.assertEqual(['x', []], scopeBuilder.scopeHistory[1])
        self.assertEqual(['x', ['y']], scopeBuilder.scopeHistory[2])
        self.assertEqual(['x'], scopeBuilder.scopeHistory[3])

    def test_buildScope_to_deal_with_curly_braces(self):
        lexer = LexerStateMachine('{ int x ;\
                                   { int y ; }\
                                   }', self.context)
        scopeBuilder = ScopeBuilder()
        parser = Parser(lexer, self.manager)
        self.manager.setParser(parser)

        token = parser.parseStatements(0)

        self.assertEqual([[]], scopeBuilder.scopeHistory[0])
        self.assertEqual([['x']], scopeBuilder.scopeHistory[1])
        self.assertEqual([['x', []]], scopeBuilder.scopeHistory[2])
        self.assertEqual([['x', ['y']]], scopeBuilder.scopeHistory[3])
        self.assertEqual([['x']], scopeBuilder.scopeHistory[4])
        self.assertEqual([], scopeBuilder.scopeHistory[5])
        pass

    def test_buildScope_can_deal_with_3_nested_curly_braces(self):
        lexer = LexerStateMachine('{ int a ; int b ; { int x ; { int y ; } int z ; } }', self.context)
        scopeBuilder = ScopeBuilder()
        parser = Parser(lexer, self.manager)
        self.manager.setParser(parser)

        token = parser.parseStatements(0)

        self.assertEqual([[]], scopeBuilder.scopeHistory[0])
        self.assertEqual([['a']], scopeBuilder.scopeHistory[1])
        self.assertEqual([['a', 'b']], scopeBuilder.scopeHistory[2])
        self.assertEqual([['a', 'b', []]], scopeBuilder.scopeHistory[3])
        self.assertEqual([['a', 'b', ['x']]], scopeBuilder.scopeHistory[4])
        self.assertEqual([['a', 'b', ['x', []]]], scopeBuilder.scopeHistory[5])
        self.assertEqual([['a', 'b', ['x', ['y']]]], scopeBuilder.scopeHistory[6])
        self.assertEqual([['a', 'b', ['x']]], scopeBuilder.scopeHistory[7])
        self.assertEqual([['a', 'b', ['x', 'z']]], scopeBuilder.scopeHistory[8])
        self.assertEqual([['a', 'b']], scopeBuilder.scopeHistory[9])
        self.assertEqual([], scopeBuilder.scopeHistory[10])

    def test_findLocal(self):
        lexer = LexerStateMachine('int x ; x = 2 + 3 ; { x = 5 + 6 ; int y ; }', self.context)
        scopeBuilder = ScopeBuilder()
        parser = Parser(lexer, self.manager)
        self.manager.setParser(parser)

        token = parser.parseStatements(0)

        self.assertEqual(['x'], scopeBuilder.scopeHistory[0])
        self.assertEqual(['x'], scopeBuilder.scopeHistory[1])
        self.assertEqual([['x', []]], scopeBuilder.scopeHistory[2])
        self.assertEqual([['x', ['y']]], scopeBuilder.scopeHistory[3])
        self.assertEqual([['x']], scopeBuilder.scopeHistory[4])
        self.assertEqual([], scopeBuilder.scopeHistory[5])
"""

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


"""
Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.

Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both
considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child
order, where not necessarily be parent-child order.

Example 1:
Input:
        1
       / \
      2   3
Output: 2
Explanation: The longest consecutive path is [1, 2] or [2, 1].
Example 2:
Input:
        2
       / \
      1   3
Output: 3
Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
Note: All the values of tree nodes are in the range of [-1e7, 1e7].
"""

from TreeNode import TreeNode
class Solution(object):
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int, int
            length of sequence which is increasing, length of sequence which is decreasing
        """
        def dfs(node, parent):
            if not node:
                return 0, 0
            li, ld = dfs(node.left, node)
            ri, rd = dfs(node.right, node)
            l[0] = max(l[0], li + rd + 1, ld + ri + 1)
            if node.val == parent.val + 1:
                return max(li, ri) + 1, 0
            if node.val == parent.val - 1:
                return 0, max(ld, rd) + 1
            return 0, 0

        l = [0]
        r = dfs(root, root)
        print(r)
        return l[0]

root = TreeNode(1)
root.left = TreeNode(2)
res = Solution().longestConsecutive(root)
print(res)


# Zadatak broj 69
broj = "22222"
a = int(broj[0])
b = int(broj[1])
c = int(broj[2])
d = int(broj[3])
e = int(broj[4])

if a * c + 2 == b + d * e:
    print("Vazi")
else:
    print("Ne vazi")

# Zadatak broj 71
a = "34521"
suma = 0
for char in a:
    suma += int(char)

print(suma / len(a))

def absolute_of_even_sum(niz):
    """Zadatak 2.1"""
    suma = 0
    for broj in niz:
        if broj < 0 and broj % 2 == 0:
            suma += abs(broj)

    return suma

print(absolute_of_even_sum([-2, 7, -5, 3, 1, -4]))

def presjek(a, b):
    """Zadatak 2.3"""
    c = []
    for i in a:
        if i in b:
            c.append(i)
    return c

print(presjek([1, 2, 'a'], ['a', 2]))

def update_list(a, x):
    """Zadatak 2.6"""
    for i in range(len(a)):
        if a[i] % 2 == 0:
            a[i] += x

    return a

print(update_list([2, 3, 4, 5, 6], 2))


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
import requests
import os
import base64

#导入thrift的python模块
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
#导入编译生成的hbase 模块
from myThrift.hbase import THBaseService
from myThrift.hbase.ttypes import *

#response =requests.get('http://duanziwang.com/')
#data = response.text
#result = re.findall('(.*?)',data)

def get_page(url):
    try:
        headers = {'User-Agent':'Mozilla/5.0(Windows NT 10.0;Win64; x64) APPleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36'}
        response = requests.get(url, timeout=10)
        data = response.text
        result = re.findall('(.*?)',data)
        #result = re.findall('(.*?)',data)
        #result = re.findall('(.*?)',data)
        return  result
    except:
        return ""
    #/html/body/section/div/div/main
    #//*[@id="1844"]/div[2]
    #//*[@id="1847"]/div[1]/h1/a
    #//*[@id="1845"]/div[1]/h1/a
    #//*[@id="1847"]/div[2]/p/text()
    #//*[@id="1843"]/footer/div/a[2]
def out_write(result):
    with open('areduanzi4.txt','a',encoding='utf-8')as fw:
        for i in result:
            fw.write('\n'+i)
            fw.flush()

def put(url,result):
    #创建Socket连接，到s201:9090
    transport = TSocket.TSocket('192.168.43.155', 9090)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = THBaseService.Client(protocol)
    #打开传输端口
    transport.open()
    #对url进行base64编码，形成bytes,作为rowkey
    urlBase64Bytes = url.encode("utf-8")

    #put操作
    table = b'ns01:t4'
    rowkey = urlBase64Bytes

    for i in result:
        #v1 = TColumnValue(rb'f1', b'duanzi',i)
        print(i)
        print("-"*30)
        bytes = i.encode('utf-8')
        tcls = TColumnValue(b'f1', b'content', bytes)
        vals = [tcls]
        put = TPut(rowkey, vals)
        client.put(table, put)
    print("okkkk!!")
    transport.close()

def get(url,d,m):
    #创建Socket连接，到s201:9090
    transport = TSocket.TSocket('192.168.43.155', 9090)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = THBaseService.Client(protocol)
    #打开传输端口
    transport.open()
    #对url进行base64编码，形成bytes,作为rowkey
    urlBase64Bytes = url.encode("utf-8")
    #get
    table = b'ns01:t4'
    rowkey=urlBase64Bytes
    col_id = TColumn(b"f1",b'content')
    cols = [col_id]
    get = TGet(rowkey,cols)
    res = client.get(table,get)
    print(bytes.decode(res.columnValues[0].qualifier))
    print(bytes.decode(res.columnValues[0].family))
    print(res.columnValues[0].timestamp)
    print(bytes.decode(res.columnValues[0].value))
    transport.close()
    print("Get data okokok")

def scan():
    #创建Socket连接，到s201:9090
    transport = TSocket.TSocket('192.168.43.155', 9090)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = THBaseService.Client(protocol)
    #打开传输端口
    transport.open()

    # scan 全表扫描操作
    table = b'ns01:t4'

    # startRow = b'34,13520401111,20180114152647,0,13269364444,406'
    # stopRow = b'90,15032295555,20180922165903,0,15778421111,298'
    # dur = TColumn(b"f1", b"callDuration")
    # time = TColumn(b"f1", b"callTime")
    # caller = TColumn(b"f1", b"caller")
    # callee = TColumn(b"f1", b"callee")
    # cols = [dur, time,caller,callee]
    #caller = TColumn(b"f1", b"name")

    callee = TColumn(b"f1", b'content')
    cols = [callee]

    scan = TScan(columns=cols,startRow="1".encode(),stopRow="10".encode(),maxVersions=10)
    r = client.getScannerResults(table,scan,10);
    print(len(r))
    for x in r:
        print("============")
        print(bytes.decode(x.columnValues[0].qualifier))
        #print(bytes.decode(x.columnValues[0].family))
      #  print(x.columnValues[0].timestamp)
        print(bytes.decode(x.columnValues[0].value))

        print(x.columnValues[0].value)

    transport.close()
    print("Scan data okokok")

def out_print(data):
    for i in data:
        print(i)

if __name__ == '__main__':
    url = "http://duanziwang.com/"
    #u =get_page(url) #爬取网页
    #out_write(u)#写到文档
   # put(url,u)

#    get(url)
   # out_print(u)#打印到屏幕
    scan()


import os.path
from urllib.request import urlretrieve
import robolib.datamanager.datadir as datadir

def get_model(model, delete=False):
    filename = datadir.get_opencv_dir(model["name"])
    if delete and os.path.isfile(filename):
        print("Delete-Mode is on. Deleting file")
        os.remove(filename)
    if os.path.isfile(filename):
        print("{} already present, to re-download it remove the file.".format(filename))
    else:
        print("{} not found, downloading it from: {} ".format(filename, model["url"]))
        urlretrieve(model["url"], filename)
    return filename

HAARCASCADE_FRONTALFACE_DEFAULT = \
    {"url": 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default'
            '.xml',
     "name": 'Frontalface.xml'}
HAARCASCADE_EYE = \
    {"url": 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_eye.xml',
     "name": 'Eye.xml'}

HAARCASCADE_FRONTALFACE_ALT = \
    {"url": "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt.xml",
     "name": "Frontalface_alt.xml"}

HAARCASCADE_FRONTALFACE_ALT2 = \
    {"url": "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt2.xml",
     "name": "Frontalface_alt2.xml"}

HAARCASCADE_FRONTALFACE_ALT_TREE = \
    {"url": "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades"
            "/haarcascade_frontalface_alt_tree.xml",
     "name": "Frontalface_alt_tree.xml"}


def option_pane(title, message, options, default=''):
    from javax.swing import JOptionPane
    return JOptionPane.showInputDialog(
        None,
        message,
        title,
        JOptionPane.QUESTION_MESSAGE,
        None,  # return on cancel
        options,
        default)  # must be in options, otherwise 1st is shown

def multiline_pane(title='', default=''):
    from javax.swing import JOptionPane, JScrollPane, JTextArea
    ta = JTextArea(20, 20)
    ta.setText(default)
    result = JOptionPane.showConfirmDialog(None,
                                           JScrollPane(ta),
                                           title,
                                           JOptionPane.OK_CANCEL_OPTION,
                                           JOptionPane.PLAIN_MESSAGE,
                                           # JOptionPane.QUESTION_MESSAGE
                                           )
    if result == JOptionPane.OK_OPTION:
        return ta.getText()
    else:
        return default