import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QButtonGroup
from PyQt5.QtGui import QIcon, QPainter, QBrush, QPen
from PyQt5.QtCore import pyqtSlot, Qt
from collections.abc import Sequence
from itertools import chain, count
import numpy as np
import tree

testData = '''(  (IP-MAT
    (NP-SBJ (PRO-D Honum))
    (VBDI blöskraði)
    (PP
      (P þegar)
      (CP-ADV
        (C 0)
        (IP-SUB
          (NP-SBJ (NP (D-D þessi) (N-D niðurstaða)))
          (RDDI varð)
          (ADJP (ADJ-N ljós)))))))'''

testVal = tree.Tree([testData], 0)

class App(QWidget):

    def __init__(self, text):
        super().__init__()
        self.positions = []
        self.rightmostX = 0
        self.paintPos = []
        self.currentID = 1
        self.currentPosition = [0]
        self.buttongroup = QButtonGroup()
        self.title = 'Tree'
        self.left = 10
        self.top = 10
        self.width = 700
        self.height = 700
        self.bWidth = 80
        self.bHeight = 40
        self.margin = 20
        self.selected = []

        self.depth = self.findDepth(text)
        self.initUI(text)

    def increseID(self):
        self.currentID += 1

    #draws a arrow from parent to child
    def paintEvent(self, event):
        for i in self.paintPos:
            qp = QPainter()
            pxPos = int(i["pxPos"])
            pyPos = int(i["pyPos"])
            cxPos = int(i["cxPos"])
            cyPos = int(i["cyPos"])

            qp.begin(self)

            qp.setPen(Qt.red)

            qp.setBrush(Qt.white)
            qp.drawLine(pxPos, pyPos, cxPos, cyPos)
        qp.end()

    def initUI(self, text):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.buttongroup.buttonClicked[int].connect(self.on_button_clicked)
        if not self.buttongroup.buttons():

            buttons = self.createButtons(text)
            for b in buttons:
                button = QPushButton(b["name"], self)
                button.setGeometry(int(b["xpos"]),int(b["ypos"]),self.bWidth,self.bHeight)
                self.buttongroup.addButton(button,b["id"])

        #button1.clicked.connect(self.on_click)
        #button2.clicked.connect(self.on_click)
        self.paintEvent("test")
        #TEMP CHANGE LATER
        self.show()

    def on_button_clicked(self,ID):
        print(ID)

    def createButtons(self,text):
        buttons = []

        yPos = 10
        #below is temp, change later
        sent = text[0][1]
        depth = self.findDepth(sent)
        maxHeight = self.height // depth

        parentX = self.width/2
        parentY = self.bHeight + 40

        button = {
                    "id": self.currentID,
                    "name" : sent[0],
                    "xpos" : self.width/2,
                    "ypos" : self.bHeight + 40,
                    "position": self.currentPosition[:]
                }
        buttons.append(button)
        self.positions.append(self.currentPosition[:])

        buttons2 = self.createLayout(sent,self.width/2, parentX + (self.bWidth/2), parentY + (self.bHeight/2))
        buttons = buttons + buttons2

        for i in buttons:
            t = "print(sent"
            for j in i["position"]:
                temp = '[' + str(j) + ']'
                t += temp
            t += ')'
            exec(t)

        return buttons

    def findDepth(self, text):
        depth = lambda L: isinstance(L, list) and max(map(depth, L))+1
        return depth(text)

    def DefaultXPos(self, sentence, xPos, buttons):
        #find how many notes are in this depth excluding the head

        #start by checking if the rightmost xposition is clos

        length = len(sentence)-1
        xPositions = []
        #create list of xPositions

        if length%2 == 0:

            #find new xpos in respect to the children of previous note

            left = []
            right = []

            #left list
            for i in range(int(length/2)):
                if not left:
                    left.append(xPos-(self.bWidth + 20))
                else:
                    left.append(left[-1]-(self.bWidth + 20))

            #right list
            for i in range(int(length/2)):
                if not right:
                    right.append(xPos+(self.bWidth + 20))
                else:
                    right.append(right[-1]+(self.bWidth + 20))

            left.reverse()
            xPositions = left + right
        else:
            mid = []
            mid.append(int(xPos))
            left = []
            right = []

            #left list
            for i in range(int((length-1)/2)):
                if not left:
                    left.append(xPos-(self.bWidth + 20))
                else:
                    left.append(left[-1]-(self.bWidth + 20))

            #right list
            for i in range(int((length-1)/2)):
                if not right:
                    right.append(xPos+(self.bWidth + 20))
                else:
                    right.append(right[-1]+(self.bWidth + 20))
            left.reverse()
            xPositions = left + mid + right
        return xPositions

    def createLayout(self, sentence, xPos, parentX, parentY, depth=2, buttons=[], currentPos = [0]):

        xPositions = self.DefaultXPos(sentence, xPos, buttons)

        for i in range(1,len(sentence)):
            currentPos[-1] = i
            if isinstance(sentence[i], list):
                if len(sentence[i]) == 2:
                    if isinstance(sentence[i][0], str) and isinstance(sentence[i][1], str):
                        if i == len(sentence) - 1:
                            self.rightmostX = xPositions[i-1]
                        #HEADER
                        self.increseID()

                        #paint the arrow from parent to child node
                        if self.rightmostX >= xPositions[i-1]:
                            if i != len(sentence)-1:
                                xPositions[i-1] = self.rightmostX + self.bWidth + 20

                                for i in range(i,len(xPositions)):
                                    xPositions[i] = xPositions[i-1] + (self.bWidth + 20)

                        paint = {
                            "pxPos" : parentX,
                            "pyPos" : parentY,
                            "cxPos" : xPositions[i-1] + (self.bWidth/2),
                            "cyPos" : (self.bHeight + 40)*depth + (self.bHeight/2)
                        }
                        self.paintPos.append(paint)

                        self.appendPosition(currentPos[:])

                        header = {
                            "id": self.currentID,
                            "name" : sentence[i][0],
                            "xpos" : xPositions[i-1],
                            "ypos" : (self.bHeight + 40)*depth,
                            "position": currentPos[:] + [0]
                        }

                        buttons.append(header)
                        #VALUE
                        self.increseID()

                        #paint the arrow from parent to child node
                        paint2 = {
                            "pxPos" : xPositions[i-1] + (self.bWidth/2),
                            "pyPos" : (self.bHeight + 40)*depth + (self.bHeight/2),
                            "cxPos" : xPositions[i-1] + (self.bWidth/2),
                            "cyPos" : (self.bHeight + 40)*(depth+1) + (self.bHeight/2)
                        }

                        self.paintPos.append(paint2)
                        self.appendPosition(currentPos[:])
                        value = {
                            "id": self.currentID,
                            "name" : sentence[i][1],
                            "xpos" : xPositions[i-1],
                            "ypos" : (self.bHeight + 40)*(depth+1),
                            "position": currentPos[:] + [1]
                        }
                        buttons.append(value)

                    else:

                        self.increseID()

                        #paint the arrow from parent to child node
                        paint = {
                            "pxPos" : parentX,
                            "pyPos" : parentY,
                            "cxPos" : xPositions[i-1] + (self.bWidth/2),
                            "cyPos" : (self.bHeight + 40)*depth + (self.bHeight/2)
                        }
                        self.paintPos.append(paint)

                        self.appendPosition(currentPos[:])

                        header = {
                            "id": self.currentID,
                            "name" : sentence[i][0],
                            "xpos" : xPositions[i-1],
                            "ypos" : (self.bHeight + 40)*depth,
                            "position": currentPos[:] + [0]
                        }

                        buttons.append(header)
                        if isinstance(sentence[i][1][0], str) and isinstance(sentence[i][1][1], str):

                            #HEADER
                            self.increseID()

                            #paint the arrow from parent to child node
                            paint2 = {
                                "pxPos" : xPositions[i-1] + (self.bWidth/2),
                                "pyPos" : (self.bHeight + 40)*depth + (self.bHeight/2),
                                "cxPos" : xPositions[i-1] + (self.bWidth/2),
                                "cyPos" : (self.bHeight + 40)*(depth+1) + (self.bHeight/2)
                            }

                            self.paintPos.append(paint2)
                            self.appendPosition(currentPos[:])

                            header2 = {
                                "id": self.currentID,
                                "name" : sentence[i][1][0],
                                "xpos" : xPositions[i-1],
                                "ypos" : (self.bHeight + 40)*(depth+1),
                                "position": currentPos[:] + [1] + [0]
                            }
                            buttons.append(header2)
                            self.increseID()

                            paint3 = {
                                "pxPos" : xPositions[i-1] + (self.bWidth/2),
                                "pyPos" : (self.bHeight + 40)*(depth+1) + (self.bHeight/2),
                                "cxPos" : xPositions[i-1] + (self.bWidth/2),
                                "cyPos" : (self.bHeight + 40)*(depth+2) + (self.bHeight/2)
                            }

                            self.paintPos.append(paint3)

                            value = {
                                "id": self.currentID,
                                "name" : sentence[i][1][1],
                                "xpos" : xPositions[i-1],
                                "ypos" : (self.bHeight + 40)*(depth+2),
                                "position": currentPos[:] + [1] + [1]
                            }
                            buttons.append(value)
                        else:

                            paint2 = {
                                "pxPos" : xPositions[i-1] + (self.bWidth/2),
                                "pyPos" : (self.bHeight + 40)*depth + (self.bHeight/2),
                                "cxPos" : xPositions[i-1] + + (self.bWidth/2),
                                "cyPos" : (self.bHeight + 40)*(depth+1) + (self.bHeight/2)
                            }

                            self.paintPos.append(paint2)
                            self.increseID()
                            header2 = {
                                "id": self.currentID,
                                "name" : sentence[i][1][0],
                                "xpos" : xPositions[i-1],
                                "ypos" : (self.bHeight + 40)*(depth+1),
                                "position": currentPos[:] + [1] + [0]
                            }

                            tempPos = currentPos[:] + [1] + [0]
                            buttons.append(header2)

                            #define new parent X and parentY
                            npX = xPositions[i-1] + (self.bWidth/2)
                            npY = (self.bHeight + 40)*(depth+1) + (self.bHeight/2)
                            self.createLayout(sentence[i][1], xPositions[i-1], npX, npY, depth+2, buttons, tempPos[:])
                else:

                    tempxPos = xPositions[i-1]
                    if isinstance(sentence[i][1], list):
                        if len(sentence[i]) > 2:

                            tempxPos = xPositions[i-1] + self.bWidth + 20
                        else:
                            print("<=2")

                    self.increseID()
                    self.appendPosition(currentPos[:])

                    paint2 = {
                        "pxPos" : parentX,
                        "pyPos" : parentY,
                        "cxPos" : tempxPos + (self.bWidth/2),
                        "cyPos" : (self.bHeight + 40)*depth + (self.bHeight/2)
                    }
                    self.paintPos.append(paint2)
                    currentPos.append(0)
                    header = {
                        "id" : self.currentID,
                        "name" : sentence[i][0],
                        "xpos" : tempxPos,
                        "ypos" : (self.bHeight + 40)*depth,
                        "position": currentPos[:]
                    }
                    buttons.append(header)

                    #define new parent X and parentY
                    npX = tempxPos + (self.bWidth/2)
                    npY = (self.bHeight + 40)*depth + (self.bHeight/2)

                    self.createLayout(sentence[i], tempxPos, npX, npY, depth+1, buttons, currentPos[:])

            else:
                tempxPos = xPositions[i-1]

                currentPos.append(1)

                self.appendPosition(currentPos)

                value = {
                        "id" : self.currentID,
                        "name" : sentence[i],
                        "xpos" : tempxPos,
                        "ypos" : (self.bHeight + 40)*depth,
                        "position": currentPos[:]
                    }
                buttons.append(value)

        return buttons
            #else:

    def appendPosition(self,pos):
        self.positions = self.positions + [pos]

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App(testVal.tree)
    sys.exit(app.exec_())


import wx
import wx.aui

ID_About = wx.NewId()

class AuiFrame(wx.Frame):
    def __init__(self,parent,id=-1,title="",pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE |
                                            wx.SUNKEN_BORDER |
                                            wx.CLIP_CHILDREN):
        wx.Frame.__init__(self,parent,id,title,pos,size,style)
        self.createMenu()
        self.createSplitLayout()

    def createMenu(self):
        # create menu
        mb = wx.MenuBar()

        file_menu = wx.Menu()
        file_menu.Append(wx.ID_EXIT, "Exit")

        help_menu = wx.Menu()
        help_menu.Append(ID_About, "About...")
        mb.Append(file_menu, "File")
        mb.Append(help_menu, "Help")
        self.SetMenuBar(mb)

    def createSplitLayout(self):
        split1 = wx.SplitterWindow(self,-1,style=wx.SP_LIVE_UPDATE)
        self.left_panel = self.createLeftPane(split1)

        split2 = wx.SplitterWindow(split1,-1,style=wx.SP_LIVE_UPDATE)
        self.first_panel = wx.Window(split2,style = wx.BORDER_SUNKEN)
        self.second_panel = wx.Window(split2,style = wx.BORDER_SUNKEN)

        split1.SetMinimumPaneSize(50)
        split1.SplitVertically(self.left_panel, split2,200)

        split2.SetMinimumPaneSize(20)
        split2.SetSashGravity(0.5)
        split2.SplitVertically(self.first_panel, self.second_panel)

    def createLeftPane(self,parent):
        sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',
                      'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
                      'twelve', 'thirteen', 'fourteen']
        self.clone_list = wx.ListBox(parent, 60, (100, 50), (90, 120), sampleList, wx.LB_SINGLE)
        return self.clone_list

if __name__ == '__main__':
    import sys,os
    app = wx.App(False)
    frame = AuiFrame(None, wx.ID_ANY, "Aui", size=(750, 590))
    frame.Show(True)

    app.MainLoop()


import pika, json

AMQP_URL = 'amqps://akpuvzcs:D474MrduFSaxw19PzP4z_8uhWbGqwGXv@baboon.rmq.cloudamqp.com/akpuvzcs'
params = pika.URLParameters(AMQP_URL)
connection = pika.BlockingConnection(params)
channel = connection.channel()

def publish(method, body):
    properties = pika.BasicProperties(method)
    channel.basic_publish(
        exchange='',
        routing_key='main',
        body=json.dumps(body),
        properties = properties
    )


#######################################################################
# library
#######################################################################
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

#######################################################################
# Polynomial basis functions
#######################################################################

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
x= np.array([2,3,4])
poly = PolynomialFeatures(3,include_bias=False)
# convert one-dimensional array into a three-dimensional array
poly.fit_transform(x[:, None])

from sklearn.pipeline import make_pipeline
# Make a 7th-degree polynomial model
poly_model = make_pipeline(PolynomialFeatures(7),LinearRegression())
# create training data
rng = np.random.RandomState(1)
x = 10 * rng.rand(50)
y = np.sin(x) + 0.1 * rng.randn(50)
# Fit the model
poly_model.fit(x[:,np.newaxis], y)
# create test data
xfit = np.linspace(0, 10, 1000)
yfit = poly_model.predict(xfit[:,np.newaxis])

plt.scatter(x,y)
plt.plot(xfit,yfit)
plt.show()

#######################################################################
# Gaussian basis functions
#######################################################################

#######################################################################
# PolynomialRegression
#######################################################################
# Use a pipeline to string operations together
def PolynomialRegression(degree=2, **kwargs):
    return make_pipeline(PolynomialFeatures(degree),
                         LinearRegression(**kwargs))

# generate data
def make_data(N, err=1.0, rseed=1):
    # randomly sample the data
    rng = np.random.RandomState(rseed)
    X = rng.rand(N, 1) ** 2
    y = 10 - 1. / (X.ravel() + 0.1)
    if err > 0:
        y += err * rng.randn(N)
    return X, y

# Call the function
X, y = make_data(40)

# visualize our data
plt.scatter(X.ravel(), y, color='black')
axis = plt.axis()

# generate X_test
X_test = np.linspace(-0.1, 1.1, 500)[:, None]
# Fit Polynomial Regression
for degree in [1, 3, 5]:
    y_test = PolynomialRegression(degree).fit(X,y).predict(X_test)
    plt.plot(X_test.ravel(),y_test,label='degree{0}'.format(degree))
plt.xlim(-0.1, 1.0)
plt.ylim(-2, 12)
plt.legend(loc='best');
plt.show()

# Compute training score and validation score across the range
from sklearn.model_selection import validation_curve
degree = np.arange(0,21)
train_score, val_score = validation_curve(PolynomialRegression(),X,y,'polynomialfeatures__degree',degree,cv=7)
plt.plot(degree, np.median(train_score, 1), color='blue', label='training score')
plt.plot(degree, np.median(val_score, 1), color='red', label='validation score')
plt.legend(loc='best')
plt.ylim(0, 1)
plt.xlabel('degree')
plt.ylabel('score');
plt.show()

# Compute and display the fit of degree d over the original data
plt.scatter(X.ravel(), y)
lim = plt.axis()
y_test = PolynomialRegression(3).fit(X, y).predict(X_test)
plt.plot(X_test.ravel(), y_test);
plt.axis(lim);
plt.show()

#######################################################################
# Learning Curves
#######################################################################

# Compute training score and validation score across the range
from sklearn.model_selection import validation_curve
degree = np.arange(0,21)
train_score, val_score = validation_curve(PolynomialRegression(),X,y,'polynomialfeatures__degree',degree,cv=7)
plt.plot(degree, np.median(train_score, 1), color='blue', label='training score')
plt.plot(degree, np.median(val_score, 1), color='red', label='validation score')
plt.legend(loc='best')
plt.ylim(0, 1)
plt.xlabel('degree')
plt.ylabel('score');
plt.show()

# generate a new dataset with a factor of five more points
X2, y2 = make_data(200)
plt.scatter(X2.ravel(), y2);
plt.show()

# Compute training score and validation score across the range
from sklearn.model_selection import validation_curve
degree = np.arange(21)
train_score2, val_score2 = validation_curve(PolynomialRegression(), X2, y2,'polynomialfeatures__degree', degree, cv=7)
plt.plot(degree, np.median(train_score2, 1), color='blue', label='training score')
plt.plot(degree, np.median(val_score2, 1), color='red', label='validation score')
plt.plot(degree, np.median(train_score, 1), color='blue', alpha=0.3, linestyle='dashed')
plt.plot(degree, np.median(val_score, 1), color='red', alpha=0.3, linestyle='dashed')
plt.legend(loc='lower center')
plt.ylim(0, 1)
plt.xlabel('degree')
plt.ylabel('score');
plt.show()

#######################################################################
# Validation in Practice: Grid Search
#######################################################################
# Using grid to find the optimal polynomial model
from sklearn.model_selection import GridSearchCV
# set parameters
param_grid = {'polynomialfeatures__degree': np.arange(21),
              'linearregression__fit_intercept': [True, False],
              'linearregression__normalize': [True, False]}
grid = GridSearchCV(PolynomialRegression(), param_grid, cv=7)
# Fit the model at each grid point, keeping track of the scores along the way
grid.fit(X, y);
# Ask the best parameters
grid.best_params_
# Use the best model and show the fit over the data
model = grid.best_estimator_

plt.scatter(X.ravel(), y)
lim = plt.axis()
y_test = model.fit(X, y).predict(X_test)
plt.plot(X_test.ravel(), y_test);
plt.axis(lim);
plt.show()

#######################################################################
# Basis Function Regression
#######################################################################
# transform data according to basis functions

#----------------------------------------------------------------------
# Polynomial basis functions
#----------------------------------------------------------------------
from sklearn.preprocessing import PolynomialFeatures
x = np.array([2, 3, 4])
poly = PolynomialFeatures(3, include_bias=False)
poly.fit_transform(x[:, None])

xfit = np.linspace(0, 10, 1000)

from sklearn.pipeline import make_pipeline
poly_model = make_pipeline(PolynomialFeatures(7),
                           LinearRegression())

rng = np.random.RandomState(1)
x = 10 * rng.rand(50)
y = np.sin(x) + 0.1 * rng.randn(50)

poly_model.fit(x[:, np.newaxis], y)
yfit = poly_model.predict(xfit[:, np.newaxis])

plt.scatter(x, y)
plt.plot(xfit, yfit);
plt.show()

#----------------------------------------------------------------------
# Gaussian basis functions
#----------------------------------------------------------------------
from sklearn.base import BaseEstimator, TransformerMixin

class GaussianFeatures(BaseEstimator, TransformerMixin):
    """Uniformly spaced Gaussian features for one-dimensional input"""

    def __init__(self, N, width_factor=2.0):
        self.N = N
        self.width_factor = width_factor

    @staticmethod
    def _gauss_basis(x, y, width, axis=None):
        arg = (x - y) / width
        return np.exp(-0.5 * np.sum(arg ** 2, axis))

    def fit(self, X, y=None):
        # create N centers spread along the data range
        self.centers_ = np.linspace(X.min(), X.max(), self.N)
        self.width_ = self.width_factor * (self.centers_[1] - self.centers_[0])
        return self

    def transform(self, X):
        return self._gauss_basis(X[:, :, np.newaxis], self.centers_,
                                 self.width_, axis=1)

gauss_model = make_pipeline(GaussianFeatures(20),
                            LinearRegression())
gauss_model.fit(x[:, np.newaxis], y)
yfit = gauss_model.predict(xfit[:, np.newaxis])

plt.scatter(x, y)
plt.plot(xfit, yfit)
plt.xlim(0, 10);
plt.show()

#----------------------------------------------------------------------
# Regularization
#----------------------------------------------------------------------
model = make_pipeline(GaussianFeatures(30),
                      LinearRegression())
model.fit(x[:, np.newaxis], y)

plt.scatter(x, y)
plt.plot(xfit, model.predict(xfit[:, np.newaxis]))

plt.xlim(0, 10)
plt.ylim(-1.5, 1.5);
plt.show()

def basis_plot(model, title=None):
    fig, ax = plt.subplots(2, sharex=True)
    model.fit(x[:, np.newaxis], y)
    ax[0].scatter(x, y)
    ax[0].plot(xfit, model.predict(xfit[:, np.newaxis]))
    ax[0].set(xlabel='x', ylabel='y', ylim=(-1.5, 1.5))

    if title:
        ax[0].set_title(title)

    ax[1].plot(model.steps[0][1].centers_,
               model.steps[1][1].coef_)
    ax[1].set(xlabel='basis location',
              ylabel='coefficient',
              xlim=(0, 10))

model = make_pipeline(GaussianFeatures(30), LinearRegression())
basis_plot(model)
plt.show()

#----------------------------------------------------------------------
# Ridge regression ($L_2$ Regularization)
#----------------------------------------------------------------------

from sklearn.linear_model import Ridge
model = make_pipeline(GaussianFeatures(30), Ridge(alpha=0.1))
basis_plot(model, title='Ridge Regression')
plt.show()

#----------------------------------------------------------------------
# Lasso regression ($L_1$ regularization)
#----------------------------------------------------------------------
from sklearn.linear_model import Lasso
model = make_pipeline(GaussianFeatures(30), Lasso(alpha=0.001))
basis_plot(model, title='Lasso Regression')
plt.show()

#######################################################################
# Predicting Bicycle Traffic
#######################################################################
# !curl -o FremontBridge.csv https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD
import pandas as pd
counts = pd.read_csv('FremontBridge.csv', index_col='Date', parse_dates=True)
weather = pd.read_csv('data/BicycleWeather.csv', index_col='DATE', parse_dates=True)

daily = counts.resample('d').sum()
daily['Total'] = daily.sum(axis=1)
daily = daily[['Total']] # remove other columns

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for i in range(7):
    daily[days[i]] = (daily.index.dayofweek == i).astype(float)

from pandas.tseries.holiday import USFederalHolidayCalendar
cal = USFederalHolidayCalendar()
holidays = cal.holidays('2012', '2016')
daily = daily.join(pd.Series(1, index=holidays, name='holiday'))
daily['holiday'].fillna(0, inplace=True)

def hours_of_daylight(date, axis=23.44, latitude=47.61):
    """Compute the hours of daylight for the given date"""
    days = (date - pd.datetime(2000, 12, 21)).days
    m = (1. - np.tan(np.radians(latitude))
         * np.tan(np.radians(axis) * np.cos(days * 2 * np.pi / 365.25)))
    return 24. * np.degrees(np.arccos(1 - np.clip(m, 0, 2))) / 180.

daily['daylight_hrs'] = list(map(hours_of_daylight, daily.index))
daily[['daylight_hrs']].plot()
plt.ylim(8, 17)

# temperatures are in 1/10 deg C; convert to C
weather['TMIN'] /= 10
weather['TMAX'] /= 10
weather['Temp (C)'] = 0.5 * (weather['TMIN'] + weather['TMAX'])

# precip is in 1/10 mm; convert to inches
weather['PRCP'] /= 254
weather['dry day'] = (weather['PRCP'] == 0).astype(int)

daily = daily.join(weather[['PRCP', 'Temp (C)', 'dry day']])

daily['annual'] = (daily.index - daily.index[0]).days / 365.

# Drop any rows with null values
daily.dropna(axis=0, how='any', inplace=True)

column_names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'holiday',
                'daylight_hrs', 'PRCP', 'dry day', 'Temp (C)', 'annual']
X = daily[column_names]
y = daily['Total']

model = LinearRegression(fit_intercept=False)
model.fit(X, y)
daily['predicted'] = model.predict(X)

daily[['Total', 'predicted']].plot(alpha=0.5);

params = pd.Series(model.coef_, index=X.columns)
params

from sklearn.utils import resample
np.random.seed(1)
err = np.std([model.fit(*resample(X, y)).coef_
              for i in range(1000)], 0)

print(pd.DataFrame({'effect': params.round(0),
                    'error': err.round(0)}))


import requests
import re
import datetime
import time
from src.hw1.catch import const_holder
from src.util.db.DBExecutor import DbUtils

###############
# 主函数

###############

if __name__ == '__main__':
    print(const_holder.host_url)
    # fetch list of project
    page_pinfo = 0
    # and git_project_id in (157)
    while True:
        select_sql = '''
            SELECT * FROM bi_test.project_primary_info
            where 1 = 1
            order by git_project_id
            limit %d, 10
        ''' % (page_pinfo * 10)
        res_dicts = const_holder.dbut.fetch_dicts(select_sql)
        if res_dicts is None:
            break
        else:
            for pj_dict in res_dicts:
                project_id = pj_dict['git_project_id']
                #     conn to git
                commit_list_page = 1
                while True:
                    r1 = requests.get(
                        const_holder.url_commits_info % project_id
                        # '%s/api/v4/projects/%d/repository/commits?per_page=2000' % (mo_url, i['id'])
                        , headers=const_holder.http_header
                        , params={
                            'per_page': 100,
                            'page': commit_list_page
                        }
                    )
                    dataCommit = r1.json()
                    if len(dataCommit) <= 0:
                        break
                    for commit_info in dataCommit:
                        insert_commit_sql = '''
                            INSERT INTO `bi_test`.`project_commits`
                             (`project_id`, `short_id`, `commit_id`, `created_at`,
                             `parent_ids`, `title`, `message`, `author_name`, `author_email`,
                             `authored_date`, `committer_name`, `committer_email`, `committed_date`)
                             VALUES
                             (
                             %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'
                             );
                        ''' % (
                            project_id,
                            const_holder.str_refine(commit_info['short_id']),
                            const_holder.str_refine(commit_info['id']),
                            const_holder.date_refine(commit_info['created_at']),
                            const_holder.str_refine(commit_info['parent_ids']),
                            const_holder.str_refine(commit_info['title']),
                            const_holder.str_refine(commit_info['message']),
                            const_holder.str_refine(commit_info['author_name']),
                            const_holder.str_refine(commit_info['author_email']),
                            const_holder.date_refine(commit_info['authored_date']),
                            const_holder.str_refine(commit_info['committer_name']),
                            const_holder.str_refine(commit_info['committer_email']),
                            const_holder.date_refine(commit_info['committed_date'])
                        )
                        print(insert_commit_sql)
                        const_holder.dbut.do_execute(insert_commit_sql)
                    print("commit_list_page : %d" % commit_list_page)
                    commit_list_page += 1
                print("##########project_id: %d over ########" % project_id)
        page_pinfo += 1

        print("all right %d" % page_pinfo)


"""BestinTCP Platform"""

DOMAIN='bestintcp'

import voluptuous as vol
from homeassistant import const

import homeassistant.helpers.config_validation as cv

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema({
            vol.Required(const.CONF_HOST): cv.string,
            vol.Required(const.CONF_PORT): cv.positive_int,
            vol.Required('rooms'): cv.string,
            vol.Optional('enable_lights', default=True): cv.boolean,
            vol.Optional('enable_switches', default=True): cv.boolean,
            vol.Optional('enable_thermostats', default=True): cv.boolean,
            vol.Optional('enable_fans', default=True): cv.boolean,
            vol.Optional('enable_gas', default=True): cv.boolean,
            vol.Optional('enable_elevator', default=True): cv.boolean,
        })
    },
    extra=vol.ALLOW_EXTRA,
)

import logging
_LOGGER = logging.getLogger(__name__)

def setup(haas, config):
    """BestinTCP core config"""
    conf = config[DOMAIN]

    btcp = BestinTCP(conf['host'], int(conf['port']))

    # Enumerate the rooms
    rooms = []
    for name in conf['rooms'].split():
        rooms.append(BestinRoom(name, btcp))

    haas.data[DOMAIN] = {
        'rooms': rooms,
        'btcp': btcp,
    }

    if conf['enable_lights']:
        haas.helpers.discovery.load_platform('light', DOMAIN, rooms, config)
    if conf['enable_switches']:
        haas.helpers.discovery.load_platform('switch', DOMAIN, rooms, config)
    if conf['enable_thermostats']:
        haas.helpers.discovery.load_platform('climate', DOMAIN, rooms, config)

    # haas.helpers.discovery.load_platform('fan', DOMAIN, {}, config)
    # haas.helpers.discovery.load_platform('gas', DOMAIN, {}, config)
    # haas.helpers.discovery.load_platform('elevator', DOMAIN, {}, config)

    return True

###############################################################################
###############################################################################
###############################################################################
###############################################################################
#
# THESE STUFF BELOW LIVES IN THE FILE bestintcp.py
#
# Use 'make' to slurp it in.
#
# The reason for these hijinks is because I'm not packaging it separately from
# the Home Assistant goo, and the custom_components dir isn't part of the
# import path. Sorry.
###############################################################################
###############################################################################
###############################################################################
###############################################################################
# BEGIN bestinctp.py ##########################################################
#!/usr/bin/python3

import sys
import time
import socket
import xmltodict
import logging

_LOGGER = logging.getLogger(__name__)

# socket.recv buffer size ... thankfully the connection is closed on exit, and
# I don't have to do something dumb like parse XML to find the end. This is
# more than big enough for all the RPCs I've sent... but you never know
READ_SIZE=4096

class BestinTCP():
    '''Quick class to encapsulate some of the XML over TCP protocol for the
    Bestin home automation system.

    It's only as complete as I needed it to be for Home Assistant integration.'''
    def __init__(self, host, port):
        self.host = host
        self.port = port

    def request(self, request):
        _LOGGER.debug('Request --> %s' % request)
        # handle strings as inputs
        try:
            request = request.encode()
        except:
            pass

        mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        mysocket.connect((self.host, self.port))

        mysocket.sendall(request)
        # XXX this will break for big responses
        response = mysocket.recv(READ_SIZE)
        if len(response) == READ_SIZE:
            _LOGGER.critical("Possibly incomplete read!")
        mysocket.close()

        # Korean characters in the response ... gotta decode to keep the peace
        try:
            response = response.decode('EUC-KR')
        except:
            pass

        _LOGGER.debug('Response <-- %s' % response)
        return response

    def XMLRequest(self, reqname, action, dev_num='null', unit_num='null', ctrl_action='null'):
        '''Send an XML request

        This is a subset of the true API ... but it's good enough for now'''

        request = ('<?xml version="1.0" encoding="utf-8"?>'
                   f'<imap ver = "1.0" address ="{self.host}" sender = "mobile">'
                   f'	<service type = "request" name = "{reqname}">'
                   '		<target name = "internet" id = "1" msg_no = "11"/>'
                   f'		<action>"{action}"</action>'
                   f'		<params dev_num = "{dev_num}" unit_num = "{unit_num}" ctrl_action = "{ctrl_action}"/>'
                   '	</service>'
                   '</imap>')
        return self.request(request)

    def ParseXMLResponse(self, response):
        '''Parse an XML response, return an array of resuts on success, or False on failure'''
        # Danger Will Robinson: early returns abound
        if not response:
            return False

        try:
            responsedict = xmltodict.parse(response)
            result = responsedict['imap']['service']['@result']
            if result != 'ok':
                _LOGGER.error("Failed RPC result: %s" % responsedict)
                return False
            else:
                return responsedict['imap']['service']['status_info']
        except:
            _LOGGER.critical("exeption in result parsing")

        return False

class BestinRoom():
    def __init__(self, name, tcp):
        self.name = name
        self.tcp = tcp

        self.lights = {}
        self.fetchLightsStatus()
        self.outlets = {}
        self.fetchOutletsStatus()
        self.heat_status = None
        self.heat_target_temp = None
        self.temperature = None
        self.fetchTemperStatus()

    def __repr__(self):
        return (f'BestinRoom(name="{self.name}", '
                f'lights={self.lights}, '
                f'outlets={self.outlets}, '
                f'temperature={self.temperature})')

    def _parseBestinSwitchResponse(self, response, outputdict={}):
        '''parse the response, results in return _AND_ passed argument
        outputdict

        The protocol uses the same response format for 'status' and 'control'
        actions, so we leech off the output like it's a status call and update
        all of the switches at once.
        '''
        status_info = self.tcp.ParseXMLResponse(response)
        if status_info == False:
            return {}

        for x in status_info:
            outputdict[x['@unit_num']] = x['@unit_status']

        return outputdict

    def _parseBestinTemperResponse(self, response):
        output = (None, None, None)
        status_info = self.tcp.ParseXMLResponse(response)
        if status_info == False:
            return output

        output = status_info['@unit_status'].split('/')
        return output

    def _livinglightswizzle(self):
        reqname = 'remote_access_light'
        devnum = self.name
        if self.name == 'living':
            reqname = 'remote_access_livinglight'
            devnum = 1
        return (reqname, devnum)

    def isLightOn(self, name):
        return self.lights[name] == 'on'

    def fetchLightsStatus(self):
        reqname, dev_num = self._livinglightswizzle()

        response = self.tcp.XMLRequest(reqname, 'status', dev_num=dev_num)
        self._parseBestinSwitchResponse(response, self.lights)

    def setLightStatus(self, unit_num, ctrl_action):
        assert(ctrl_action in ('on', 'off'))
        assert(unit_num in self.lights)

        reqname, dev_num = self._livinglightswizzle()
        response = self.tcp.XMLRequest(reqname, 'control', dev_num=dev_num, unit_num=unit_num, ctrl_action=ctrl_action)
        self._parseBestinSwitchResponse(response, self.lights)

    def fetchOutletsStatus(self):
        response = self.tcp.XMLRequest('remote_access_electric', 'status', dev_num=self.name)
        self._parseBestinSwitchResponse(response, self.outlets)

    def setOutletStatus(self, unit_num, ctrl_action):
        assert(ctrl_action in ('on', 'off'))
        assert(unit_num in self.outlets)

        response = self.tcp.XMLRequest('remote_access_electric', 'control', dev_num=self.name, unit_num=unit_num, ctrl_action=ctrl_action)
        self._parseBestinSwitchResponse(response, self.outlets)

    def isOutletOn(self, name):
        # TODO: state is usually unset/on or unset/off. What's unset? eco mode?
        if name not in self.outlets.keys():
            _LOGGER.error("outlet %s not in room %s" % (name, self))
            return False
        state = self.outlets[name].split('/')
        return state[1] == 'on'

    def fetchTemperStatus(self):
        response = self.tcp.XMLRequest('remote_access_temper', 'status', dev_num='1', unit_num=f"room{self.name}", ctrl_action='')
        temps = self._parseBestinTemperResponse(response)
        self.heat_status = temps[0]
        self.heat_target_temp = temps[1]
        self.temperature = temps[2]

    def setTemperStatus(self, onoff, temperature=None):
        assert(onoff in ('on', 'off'))
        if not temperature:
            temperature = self.heat_target_temp
        response = self.tcp.XMLRequest('remote_access_temper', 'control', dev_num='1', unit_num=f"room{self.name}", ctrl_action=f"{onoff}/{temperature}")
        temps = self._parseBestinTemperResponse(response)
        self.heat_status = temps[0]
        self.heat_target_temp = temps[1]
        self.temperature = temps[2]

    def isTemperOn(self):
        return self.heat_status == "on"

if __name__ == '__main__':
    import ipdb
    _LOGGER.setLevel(logging.DEBUG)
    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    _LOGGER.addHandler(handler)

    h = BestinTCP('192.168.50.200', 10000)

    rooms = [
        BestinRoom('living', h),
        BestinRoom(1, h),
        #BestinRoom(2, h),
        #BestinRoom(3, h),
        #BestinRoom(4, h),
        #BestinRoom(5, h)
    ]

    for room in rooms:
        print(room)

    ipdb.set_trace()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'g3n35i5'

import shopdb.exceptions as exc
from tests.base_api import BaseAPITestCase
from flask import json

class GetRefundsAPITestCase(BaseAPITestCase):

    def test_get_refunds_as_admin(self):
        """Test for geting a single refund"""
        # Do 5 refunds
        self.insert_default_refunds()
        res = self.get(url='/refunds/2', role='admin')
        self.assertEqual(res.status_code, 200)
        refund = json.loads(res.data)
        self.assertEqual(refund['id'], 2)
        self.assertEqual(refund['user_id'], 2)
        self.assertEqual(refund['total_price'], 200)
        self.assertFalse(refund['revoked'])

        required = ['id', 'timestamp', 'user_id', 'total_price', 'comment',
                    'revoked', 'revokehistory']
        assert all(x in refund for x in required)

    def test_get_non_existing_refund(self):
        """Getting a non existing refund should raise an exception"""
        self.insert_default_refunds()
        res = self.get(url='/refunds/6', role='admin')
        self.assertEqual(res.status_code, 401)
        self.assertException(res, exc.EntryNotFound)


'''
A GUI Application that lets you draw with your mouse on a canvas and predict
the digits using a Pre-Trained CNN model.
For training the model refer to the IPython notebook

'''
#libraries
import tkinter as tk
import tkinter.filedialog as filedialog
from PIL import ImageGrab ,ImageTk, Image
import numpy as np
import cv2
import win32gui
from keras.models import load_model

# loading the model
model = load_model(r'C:\Users\panka\Study\Machine Learning\Digit Recognition GUI\model.h5')

def predict_digit(filename):

    # opening the image and converting it fit for input in model
    image = cv2.imread(filename)
    grey = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2GRAY)
    ret, th = cv2.threshold(grey.copy(), 75, 255, cv2.THRESH_BINARY_INV)
    contours, _ = cv2.findContours(th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        # Create rectangle
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), thickness=2)
        digit = th[y:y + h, x:x + w]

        # Resizing that digit to (18, 18)
        resized_digit = cv2.resize(digit, (18, 18))

        # Padding the digit with 5 pixels of black color (zeros) in each side to
        #finally produce the image of (28, 28)
        padded_digit = np.pad(resized_digit, ((5, 5), (5, 5)), "constant", constant_values=0)

        # sending the padded digit to model and prediciting
        prediction = model.predict(padded_digit.reshape(1, 28, 28, 1))
        #writing prediciton on image
        data = "Pred = " + str(np.argmax(prediction))
        #print(data)
        font = cv2.FONT_HERSHEY_SIMPLEX
        fontScale = 0.5
        color = (0, 0, 0)
        thickness = 1
        cv2.putText(image, data, (x, y - 5), font, fontScale, color, thickness)
    #resizing & saving the final image
    image = cv2.resize(image,(800,600))
    cv2.imwrite('predict.png', image)

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.lastx = self.lasty = None
        self.x = self.y = 0
        #self.geometry("820x690")
        self.resizable(0,0)
        #self.resizable(width = True, height = True)
        self.title("Handwriiten Digit Recognition GUI")

        # Creating elements
        self.canvas = tk.Canvas(self, width=800, height=600, bg="white", borderwidth=5)
        self.classify_btn = tk.Button(self, text="Recognise", command=self.classify_handwriting,
                                      bg='deep sky blue')
        self.classify_btn.config(font=('helvetica', 14, 'bold'))
        self.button_clear = tk.Button(self, text="Clear", command=self.clear_all,
                                      bg='deep sky blue')
        self.button_clear.config(font=('helvetica', 14, 'bold'))
        self.openfile = tk.Button(self, text="Open A File", command=self.open_file,
                                      bg='deep sky blue')
        self.openfile.config(font=('helvetica', 14, 'bold'))

        # Grid structure
        self.canvas.grid(row=0, column=0, pady=2, sticky=tk.W, columnspan=3)
        self.classify_btn.grid(row=1, column=0, pady=2, padx=2,columnspan=2)
        self.button_clear.grid(row=1, column=2, pady=2, padx =2,columnspan =2)
        self.openfile.grid(row=1, column=4, pady=2, padx =2)
        self.canvas.bind("<Button-1>", self.activate_event)

        img = Image.open("First.jpg")
        # PhotoImage class is used to add image to widgets, icons etc
        img = ImageTk.PhotoImage(img)

        # create a label
        panel = tk.Label(self, image = img)

        # set the image as img
        panel.image = img
        panel.grid(row=0, column=3,columnspan = 3)

    def clear_all(self):
        #clear button
        self.canvas.delete("all")
        #reset the output screen
        img = Image.open("First.jpg")

        # PhotoImage class is used to add image to widgets, icons etc
        img = ImageTk.PhotoImage(img)

        # create a label
        panel = tk.Label(self, image = img)

        # set the image as img
        panel.image = img
        panel.grid(row=0, column=3,columnspan = 3)
    def open_file(self):
        file_path = filedialog.askopenfilename()
        predict_digit(file_path)
        img = Image.open('predict.png')
        # PhotoImage class is used to add image to widgets, icons etc
        img = ImageTk.PhotoImage(img)
        panel = tk.Label(self, image = img)
        #   set the image as img
        panel.image = img
        panel.grid(row=0, column=3,columnspan = 3)

    def classify_handwriting(self):
        HWND = self.canvas.winfo_id()         # get the handle of the canvas
        rect = win32gui.GetWindowRect(HWND)   # get the coordinate of the canvas
        ImageGrab.grab(rect).save('test.png') # taking ss of canvas

        predict_digit("test.png")
        # opens the output image
        img = Image.open('predict.png')
        # PhotoImage class is used to add image to widgets, icons etc
        img = ImageTk.PhotoImage(img)

        panel = tk.Label(self, image = img)
        #   set the image as img
        panel.image = img
        panel.grid(row=0, column=3,columnspan = 3)

    def activate_event(self, event):
        self.canvas.bind('<B1-Motion>', self.draw_lines)
        self.lastx, self.lasty = event.x, event.y

    def draw_lines(self, event):
        self.x = event.x
        self.y = event.y
        self.canvas.create_line((self.lastx, self.lasty, self.x, self.y), width=8, fill='black',
                                capstyle=tk.ROUND, smooth=tk.TRUE, splinesteps=12)
        self.lastx, self.lasty = self.x, self.y

app = App()
tk.mainloop()


import os
import pkginfo
import zipfile
import pkg_resources
import glob

from typing import Dict, Optional

class Wheel(object):
    def __init__(self, path):
        self._path = path

    def path(self):
        return self._path

    def name(self):
        return self.metadata().name

    def metadata(self):
        return pkginfo.get_metadata(self.path())

    def dependencies(self, extras_requested=None):
        if not extras_requested:
            # Provide an extra to safely evaluate the markers
            # without matching any extra
            extras_requested = [""]

        dependency_set = set()

        for req in self.metadata().requires_dist:
            r = pkg_resources.Requirement(req)

            if r.marker is None or any(
                r.marker.evaluate({"extra": extra}) for extra in extras_requested
            ):
                dependency_set.add(r.name)

        return dependency_set

    def unzip(self, directory):
        with zipfile.ZipFile(self.path(), "r") as whl:
            whl.extractall(directory)

def get_dist_info(extracted_whl_directory) -> str:
    dist_info_dirs = glob.glob(os.path.join(extracted_whl_directory, "*.dist-info"))
    if not dist_info_dirs:
        raise ValueError(
            f"No *.dist-info directory found. {extracted_whl_directory} is not a valid Wheel."
        )
    elif len(dist_info_dirs) > 1:
        raise ValueError(
            f"Found more than 1 *.dist-info directory. {extracted_whl_directory} is not a valid Wheel."
        )
    else:
        dist_info = dist_info_dirs[0]
    return dist_info

def get_dot_data_directory(extracted_whl_directory) -> Optional[str]:
    # See: https://www.python.org/dev/peps/pep-0491/#the-data-directory
    dot_data_dirs = glob.glob(os.path.join(extracted_whl_directory, "*.data"))
    if not dot_data_dirs:
        return None
    elif len(dot_data_dirs) > 1:
        raise ValueError(
            f"Found more than 1 *.data directory. {extracted_whl_directory} is not a valid Wheel."
        )
    else:
        dot_data_dir = dot_data_dirs[0]
    return dot_data_dir

def parse_WHEEL_file(whl_file_path: str) -> Dict[str, str]:
    contents = {}
    with open(whl_file_path, "r") as f:
        for line in f:
            cleaned = line.strip()
            if not cleaned:
                continue
            try:
                key, value = cleaned.split(":", maxsplit=1)
                contents[key] = value.strip()
            except ValueError:
                raise RuntimeError(f"Encounted invalid line in WHEEL file: '{cleaned}'")
    return contents


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#参考程序：http://www.cnblogs.com/sparkling-ly/p/5466644.html
from selenium import webdriver
import os
import time
from PIL import Image
import getsave_fn

#本方法用于chrome和edge浏览器获取网页的长截图
def chrome_capture(url,savepath='baseimages',whichbrowser='Chrome'):
    """chrome截屏
    url- 要截屏的url
    pix_w- 窗口宽
    pix_h- 窗口高
    filename-生成截图的文件名
    """
    global real_scroll_h
    global image_pix_h
    pix_h=800#定义页面每次滚动的高度
    image_pix_h = pix_h#分图片的高度等于每次滚动的高度
    if whichbrowser=='Chrome':
        pix_w=1947-26
        driver = webdriver.Chrome()
        driver.set_window_size(pix_w, pix_h + 85 + 47)  # 原来是89，猜测为浏览器头的高度，实测是85,47是被自动化软件控制的通知条的高度
    elif whichbrowser=='Edge':
        pix_w = 1947 - 32
        driver = webdriver.Edge()
        driver.set_window_size(pix_w, pix_h + 84)  # Edge浏览器的头高度为76,但实际截图时发现84可得到完美的图片
        print('pix_w:', pix_w)
    elif whichbrowser=='Firefox':
        pix_w = 1947 - 32
        driver = webdriver.Firefox()
        driver.set_window_size(pix_w, pix_h+109)#Firefox的浏览器头高为109，实际截图时发现**可得到完美的图片
        print('pix_w:', pix_w)
    else:#IE11
        pix_w = 1947-32
        driver = webdriver.Ie()
        driver.set_window_size(pix_w, pix_h+55+7)  # IE浏览器的头高度为55,但实际截图时发现84可得到完美的图片(793),使用QQ截图时，自动捕获的浏览器窗口和此处设置的x、y值完全相同，但是实际测量窗口高度是少了7个像素，不知为何有7个像素的高度不可见。
        print('pix_w:',pix_w)

    driver.get('http://'+url)
    time.sleep(2)
    img_list = []
    i = 0
    last_t=0
    while i < 20:
        #滚动到指定位置并等待1s
        print('滚动前whichbrowser的值：',whichbrowser)
        if whichbrowser=='Chrome' or whichbrowser=='Firefox' or whichbrowser=='IE':
            js_chrome="document.documentElement.scrollTop="+str(i * pix_h)#在chrome上工作良好
            driver.execute_script(js_chrome)
            time.sleep(2)
            # 通过js获取当前页面的总长度和滚动条目前所在的位置
            js_chrome_scroll = "return document.body.scrollHeight.toString()+','+document.documentElement.scrollTop"  # chrome
            js1_result = driver.execute_script(js_chrome_scroll)
        elif whichbrowser=='Edge':
            js_edge="document.body.scrollTop="+str(i * pix_h)
            driver.execute_script(js_edge)
            time.sleep(2)
            # 通过js获取当前页面的总长度和滚动条目前所在的位置
            js_edge_scroll = "return document.body.scrollHeight.toString()+','+document.body.scrollTop.toString()"#Edge
            js1_result = driver.execute_script(js_edge_scroll)

        print('js1_result:'+js1_result)
        real_scroll_h, real_top = js1_result.split(',')[0], js1_result.split(',')[1]
        # real_scroll_h, real_top 是当前滚动条长度和当前滚动条的top，作为是否继续执行的依据，由于存在滚动条向下拉动后会加载新内容的情况，所以需要以下的判断
        #real_scroll_h可以看做是页面的总长度，real_top是目前滚动条(看做一个点)所在的位置。
        # 如果这次设置的top成功，则继续滚屏
        if real_top == str(i * pix_h):
            i += 1
            print('存储图片名：''.\\cache-' + str(i) + '.png')
            driver.save_screenshot('.\\cache-'+ str(i) + '.png')#获取当前页面的截图
            img_list.append('.\\cache-'+ str(i) + '.png')#把当前页面的截图文件名存入数组
            last_t = real_top
            print('当前滚动条位置'+real_top)
        else:
            # 如果本次设置失败，看这次的top和上一次记录的top值是否相等，相等则说明没有新加载内容，且已到页面底，跳出循环
            if real_top != last_t:
                last_t = real_top
            else:
                driver.save_screenshot('.\\cache-' + str(i + 1) + '.png')
                img_list.append('.\\cache-' + str(i + 1) + '.png')
                break
    driver.close()
    # 生成图片的文件名
    save_fn = getsave_fn.save_fn(url, savepath, whichbrowser)
    print('save_fn in chromecapture:' + save_fn)
    image_merge(img_list,save_fn,whichbrowser)

def image_merge(images,save_fn,whichbrowser):
    """垂直合并多张图片
    images - 要合并的图片路径列表
    ouput_dir - 输出路径
    output_name - 输出文件名
    """

    max_width = 0
    # 计算合成后图片的宽度（以最宽的为准）和高度
    for img_path in images:
        if os.path.exists(img_path):
            img = Image.open(img_path)
            width, height = img.size
            if width > max_width:
                max_width = width
                print('max_width:',max_width)
    total_height=int(real_scroll_h)
    print('total_height:',total_height)

    # 产生一张空白图
    new_img = Image.new('RGB', (max_width, total_height), 255)

    # 合并
    x = y = 0
    for img_path in images:
        if os.path.exists(img_path):
            img = Image.open(img_path)
            width, height = img.size
            new_img.paste(img, (x, y))
            if y <= total_height-2*image_pix_h:
                y += height
            else:
                y = total_height-image_pix_h  # 最后一次滚动高度不足一屏时，图片有部分重合，以底部为准

    if whichbrowser=='Chrome':
        bounds=(0,0,new_img.size[0]-18,new_img.size[1])
        last_img=new_img.crop(bounds)
        last_img.save(save_fn)
    else:
        bounds = (0, 0, new_img.size[0] - 12, new_img.size[1])
        last_img = new_img.crop(bounds)
        last_img.save(save_fn)

    print('图片合成已完成')
    #需要在此处加入裁切图片的步骤，裁掉右侧宽为7个像素的滚动条
    for img_path in images:
        os.remove(img_path)
        print('缓存分页图片已删除',img_path)
    return save_fn

if __name__=='__main__':
    chrome_capture('www.meizu.com/pro7', savepath='newimages',whichbrowser='Edge')


import random as r
import sys
import matplotlib.pyplot as plt

r.seed()
arr = []
compares = 0
sys.setrecursionlimit(1500)

def lcs_length(x, y):
    global compares
    m = len(x)
    n = len(y)
    b = [[0 for el1 in x] for row1 in x]
    c = [[0 for el2 in y] for row2 in y]
    for i in range(1, m):
        for j in range(1, n):
            if x[i] == y[j]:
                c[i][j] = c[i-1][j-1] + 1
                b[i][j] = "upleft"
                compares += 1
            elif c[i-1][j] >= c[i][j-1]:
                c[i][j] = c[i-1][j]
                b[i][j] = "up"
                compares += 1
            else:
                c[i][j] = c[i][j-1]
                b[i][j] = "left"
                compares += 1
    return c, b

def lcs_print(b, x, i, j):
    global compares
    if i == 0 or j == 0:
        return
    if b[i][j] == "upleft":
        lcs_print(b, x, i-1, j-1)
        arr.append(x[i])
        compares += 1
    elif b[i][j] == "up":
        lcs_print(b, x, i - 1, j)
        compares += 1
    else:
        lcs_print(b, x, i, j - 1)
        compares += 1

res = []
result = []
for value in range(1, 200, 10):
    for test in range(100):
        ar1 = [r.randint(0, 19) for num1 in range(value)]
        ar2 = [r.randint(0, 19) for num2 in range(value)]
        compares = 0
        arr = []
        lcs_print(lcs_length(ar1, ar2)[1], ar1, len(ar1) - 1, len(ar1) - 1)
        res.append(compares)
    print("Test:" + str(value) + " completed.")
for i in range(0, 20):
    result.append(sum(res[i * 100: i * 100 + 100]) / 100)
ar1 = [r.randint(0, 9) for num1 in range(20)]
ar2 = [r.randint(0, 9) for num2 in range(20)]
print(ar1)
print(ar2)
lcs_print(lcs_length(ar1, ar2)[1], ar1, len(ar1)-1, len(ar1)-1)
print(str(arr))
plt.grid(True)
plt.ylabel("Avg")
plt.xlabel("Amount of objects")
plt.axis([0, 1001, 0, max(result)])
plt.plot(list(range(1, 201, 10)), result, 'r.-')
plt.show()


from sklearn.model_selection import train_test_split

#将数据分为建立模型和测试用，
#分割基于随机的数字产生器，提供一个数字给 random_state
#以保证每次运行脚本得到同样的分组
train_X,val_X,train_y,val_y = train_test_split(X,y,random_state=0)
#define model
melbourne_model = DecisionTreeRegressor()
#fit model
melbourne_model.fit(train_X,train_y)

#从 validation data 获得预测值
val_predictions = melbourne_model.predict(val_X)
print(val_predictions)
print(mean_absolute_error(val_y,val_predictions))


import os
import jinja2

from datasette.utils import (
    to_css_class,
    validate_sql_select,
    is_url,
    path_with_added_args,
    path_with_removed_args,
)
from datasette.utils.asgi import AsgiFileDownload
from datasette.plugins import pm

from .base import DatasetteError, DataView

class DatabaseView(DataView):
    name = "database"

    async def data(self, request, database, hash, default_labels=False, _size=None):
        metadata = (self.ds.metadata("databases") or {}).get(database, {})
        self.ds.update_with_inherited_metadata(metadata)

        if request.args.get("sql"):
            if not self.ds.config("allow_sql"):
                raise DatasetteError("sql= is not allowed", status=400)
            sql = request.args.get("sql")
            validate_sql_select(sql)
            return await QueryView(self.ds).data(
                request, database, hash, sql, _size=_size, metadata=metadata
            )

        db = self.ds.databases[database]

        table_counts = await db.table_counts(5)
        views = await db.view_names()
        hidden_table_names = set(await db.hidden_table_names())
        all_foreign_keys = await db.get_all_foreign_keys()

        tables = []
        for table in table_counts:
            table_columns = await db.table_columns(table)
            tables.append(
                {
                    "name": table,
                    "columns": table_columns,
                    "primary_keys": await db.primary_keys(table),
                    "count": table_counts[table],
                    "hidden": table in hidden_table_names,
                    "fts_table": await db.fts_table(table),
                    "foreign_keys": all_foreign_keys[table],
                }
            )

        tables.sort(key=lambda t: (t["hidden"], t["name"]))
        return (
            {
                "database": database,
                "size": db.size,
                "tables": tables,
                "hidden_count": len([t for t in tables if t["hidden"]]),
                "views": views,
                "queries": self.ds.get_canned_queries(database),
            },
            {
                "show_hidden": request.args.get("_show_hidden"),
                "editable": True,
                "metadata": metadata,
                "allow_download": self.ds.config("allow_download")
                and not db.is_mutable
                and database != ":memory:",
            },
            ("database-{}.html".format(to_css_class(database)), "database.html"),
        )

class DatabaseDownload(DataView):
    name = "database_download"

    async def view_get(self, request, database, hash, correct_hash_present, **kwargs):
        if database not in self.ds.databases:
            raise DatasetteError("Invalid database", status=404)
        db = self.ds.databases[database]
        if db.is_memory:
            raise DatasetteError("Cannot download :memory: database", status=404)
        if not self.ds.config("allow_download") or db.is_mutable:
            raise DatasetteError("Database download is forbidden", status=403)
        if not db.path:
            raise DatasetteError("Cannot download database", status=404)
        filepath = db.path
        return AsgiFileDownload(
            filepath,
            filename=os.path.basename(filepath),
            content_type="application/octet-stream",
        )

class QueryView(DataView):
    async def data(
        self,
        request,
        database,
        hash,
        sql,
        editable=True,
        canned_query=None,
        metadata=None,
        _size=None,
    ):
        params = {key: request.args.get(key) for key in request.args}
        if "sql" in params:
            params.pop("sql")
        if "_shape" in params:
            params.pop("_shape")
        # Extract any :named parameters
        named_parameters = self.re_named_parameter.findall(sql)
        named_parameter_values = {
            named_parameter: params.get(named_parameter) or ""
            for named_parameter in named_parameters
        }

        # Set to blank string if missing from params
        for named_parameter in named_parameters:
            if named_parameter not in params:
                params[named_parameter] = ""

        extra_args = {}
        if params.get("_timelimit"):
            extra_args["custom_time_limit"] = int(params["_timelimit"])
        if _size:
            extra_args["page_size"] = _size
        results = await self.ds.execute(
            database, sql, params, truncate=True, **extra_args
        )
        columns = [r[0] for r in results.description]

        templates = ["query-{}.html".format(to_css_class(database)), "query.html"]
        if canned_query:
            templates.insert(
                0,
                "query-{}-{}.html".format(
                    to_css_class(database), to_css_class(canned_query)
                ),
            )

        async def extra_template():
            display_rows = []
            for row in results.rows:
                display_row = []
                for column, value in zip(results.columns, row):
                    display_value = value
                    # Let the plugins have a go
                    # pylint: disable=no-member
                    plugin_value = pm.hook.render_cell(
                        value=value,
                        column=column,
                        table=None,
                        database=database,
                        datasette=self.ds,
                    )
                    if plugin_value is not None:
                        display_value = plugin_value
                    else:
                        if value in ("", None):
                            display_value = jinja2.Markup(" ")
                        elif is_url(str(display_value).strip()):
                            display_value = jinja2.Markup(
                                '{url}'.format(
                                    url=jinja2.escape(value.strip())
                                )
                            )
                    display_row.append(display_value)
                display_rows.append(display_row)
            return {
                "display_rows": display_rows,
                "custom_sql": True,
                "named_parameter_values": named_parameter_values,
                "editable": editable,
                "canned_query": canned_query,
                "metadata": metadata,
                "config": self.ds.config_dict(),
                "request": request,
                "path_with_added_args": path_with_added_args,
                "path_with_removed_args": path_with_removed_args,
                "hide_sql": "_hide_sql" in params,
            }

        return (
            {
                "database": database,
                "query_name": canned_query,
                "rows": results.rows,
                "truncated": results.truncated,
                "columns": columns,
                "query": {"sql": sql, "params": params},
            },
            extra_template,
            templates,
        )


import asyncio
import requests
from bs4 import BeautifulSoup as bs

@asyncio.coroutine
def camera_toggle(onoff):
    resp = requests.get(f"http://192.168.1.211:8080/0/detection/{onoff}").text
    soup = bs(resp, "html.parser")
    soup = soup.find("body").text.strip()
    status = soup[soup.index("Detection")+10:]
    if status == "resumed":
        return "On"
    elif status == "paused":
        return "Off"


#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import os
import re
import xlwt
import xlrd
from xlutils.copy import copy
url = r"https://www.bilibili.com/video/av17879644"
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding':  'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    'Cookie': 'finger=edc6ecda; LIVE_BUVID=AUTO4315255158474705; fts=1525515866; sid=agn7r1c4; buvid3=EA52FCB4-3F10-4E3B-936E-4224DF05DEE520821infoc; rpdid=kxmwxswpsqdosixpkqmxw',
    'Host': 'www.bilibili.com',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36',
}
r = requests.get(url,headers = headers)
html = r.content.decode('utf8')
allpage = re.findall(r'"page":(.*?),',html)
allpart = re.findall(r'"part":(.*?),',html)
filename = []
i = 0
while i < 86:
    filename.append(allpage[i] +' '+allpart[i][1:-1])
    i = i + 1
path1 = r"C:\Users\Administrator.USER-20180422WL\Desktop\test.xls"
wb = xlrd.open_workbook(path1)
w = copy(wb)
x = 0
for y in filename:
    w.get_sheet(0).write(x,0,y+'.flv')
    x = x + 1
w.save(path1)

提取哔哩哔哩专辑视频名称.py

提取哔哩哔哩专辑视频名称.py


import csv
import json
import datetime
import glob
import os
import urllib.request
from patients import PatientsReader

JST = datetime.timezone(datetime.timedelta(hours=+9), 'JST')

class CovidDataManager:
    def __init__(self):
        self.data = {
            'contacts':{},
            'querents':{},
            'patients':{},
            'patients_summary':{},
            'discharges':{},
            'discharges_summary':{},
            'inspections':{},
            'inspections_summary':{},
            'better_patients_summary':{},
            'last_update':datetime.datetime.now(JST).isoformat(),
            'main_summary':{}
        }

    def fetch_data(self):
        pr = PatientsReader()
        self.data['patients'] = pr.make_patients_dict()
        self.data['patients_summary'] = pr.make_patients_summary_dict()

    def export_csv(self):
        for key in self.data:
            if key == 'last_update' or key == 'main_summary':
                continue

            datas = self.data[key]
            if datas == {}:
                continue

            maindatas = datas['data']
            header = list(maindatas[0].keys())
            csv_rows = [ header ]
            for d in maindatas:
                csv_rows.append( list(d.values()) )

            with open('data/' + key + '.csv', 'w', encoding='utf-8', newline='') as f:
                writer = csv.writer(f)
                writer.writerows(csv_rows)

    def export_json(self, filepath='data/data.json'):
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(self.data, f, indent=4, ensure_ascii=False)

    def export_json_from_name(self, key):
        with open('data/' + key + '.json', 'w', encoding='utf-8') as f:
            json.dump(self.data[key], f, indent=4, ensure_ascii=False)

    def import_csv(self):
        csvfiles = glob.glob('./import/*.csv')
        for csvfile in csvfiles:
            filename = os.path.splitext(os.path.basename(csvfile))[0]
            last_modified_time = datetime.datetime.fromtimestamp(os.path.getmtime(csvfile), JST).isoformat()
            datas = []
            with open(csvfile, encoding='utf-8') as f:
                rows = [row for row in csv.reader(f)]
                header = rows[0]
                maindatas = rows[1:]
                for d in maindatas:
                    data = {}
                    for i in range(len(header)):
                        if filename == "current_patients":
                            if i <= 1:
                                if header[i] == '患者数':
                                    data['subtotal'] = int(d[i])
                                if header[i] == '日付':
                                    data['date'] = d[i]
                        else:
                            if header[i] == '小計':
                                data['subtotal'] = int(d[i])
                            if header[i] == '日付':
                                data['date'] = d[i]
                    datas.append(data)

            self.data[filename] = {
                'data':datas,
                'last_update':last_modified_time
            }

    def import_csv_from_odp(self):
        responce = urllib.request.urlopen('https://www.harp.lg.jp/opendata/api/package_show?id=752c577e-0cbe-46e0-bebd-eb47b71b38bf')
        print(responce.getcode())
        if responce.getcode() == 200:
            loaded_json = json.loads(responce.read().decode('utf-8'))
            if loaded_json['success'] == True:
                resources = loaded_json['result']['resources']
                for resource in resources:
                    url = resource['download_url']
                    request_file = urllib.request.urlopen(url)
                    if request_file.getcode() == 200:
                        f = request_file.read().decode('utf-8')
                        filename = resource['filename'].rstrip('.csv')
                        last_modified_time = resource['updated']
                        datas = []
                        rows = [row for row in csv.reader(f.splitlines())]
                        header = rows[0]
                        maindatas = rows[1:]
                        for d in maindatas:
                            data = {}
                            for i in range(len(header)):
                                if filename == "current_patients":
                                    if i <= 1:
                                        if header[i] == '患者数':
                                            data['subtotal'] = int(d[i])
                                        if header[i] == '日付':
                                            data['date'] = d[i]
                                else:
                                    if header[i] == '小計':
                                        data['subtotal'] = int(d[i])
                                    if header[i] == '日付':
                                        data['date'] = d[i]
                            datas.append(data)

                        self.data[filename] = {
                            'data':datas,
                            'last_update':last_modified_time
                        }

    def import_csv_from_sdp_contacts(self):
        request_file = urllib.request.urlopen('https://ckan.pf-sapporo.jp/dataset/f6338cc2-dd6b-43b6-98a3-cd80b05b6a36/resource/e9e6f062-cafd-4aea-992f-039e2e26f4ac/download/contacts.csv')
        if request_file.getcode() == 200:
            f = request_file.read().decode('utf-8')
            filename = 'contacts'
            datas = []
            rows = [row for row in csv.reader(f.splitlines())]
            header = rows[0]
            maindatas = rows[1:]
            for d in maindatas:
                data = {}
                for i in range(len(header)):
                    if header[i] == '小計':
                        data['subtotal'] = int(d[i])
                    if header[i] == '日付':
                        data['date'] = d[i]
                datas.append(data)

            self.data[filename] = {
                'data': datas,
                'last_update': datetime.datetime.now(JST).isoformat()
            }

    def import_csv_from_sdp_querents(self):
        request_file = urllib.request.urlopen('https://ckan.pf-sapporo.jp/dataset/f6338cc2-dd6b-43b6-98a3-cd80b05b6a36/resource/a89ba566-93d1-416a-a269-e0ba48a06636/download/querents.csv')
        if request_file.getcode() == 200:
            f = request_file.read().decode('utf-8')
            filename = 'querents'
            datas = []
            rows = [row for row in csv.reader(f.splitlines())]
            header = rows[0]
            maindatas = rows[1:]
            for d in maindatas:
                data = {}
                for i in range(len(header)):
                    if header[i] == '小計':
                        data['subtotal'] = int(d[i])
                    if header[i] == '日付':
                        data['date'] = d[i]
                datas.append(data)

            self.data[filename] = {
                'data': datas,
                'last_update': datetime.datetime.now(JST).isoformat()
            }

if __name__ == "__main__":
    dm = CovidDataManager()
    dm.fetch_data()
    dm.import_csv()
    dm.import_csv_from_sdp_contacts()
    dm.import_csv_from_sdp_querents()
    for key in dm.data:
        dm.export_json_from_name(key)


# -*- coding: utf-8 -*-
import json
from os import system, remove

with open('questions.json') as data_file:
	questions = json.load(data_file)

with open('answers.json') as data_file:
	answers = json.load(data_file)

questions = questions['questions']
answers = answers['answers']

for question in questions:
	#Generar el tsv con los datos
	for answer in answers:
		if answer['questionId'] == question['id']:
			respuestas = answer['answers']
			yrange = max(answer['answers'])

	respuestastsv = ''
	cont = 0
	for res in question['answers']:
		respuestastsv += str(respuestas[res['id']-1]) + ' ' + res['text'].encode('utf-8')
		cont+=1

	file = open('respuestas.tsv', 'w+')
	file.write(respuestastsv) # python will convert \n to os.linesep
	file.close()

	gnuplot = "\
	# ______________________________________________________________________\n\
	#Setting output\n\
	set term png\n\
	set output \"./Plots/plot"+str(question['id'])+".png\"\n\
	# For the next graph, we want a histogram.\n\
	set style data boxes\n\
	# set xrange [0:"+str(question['numAnswers'])+"]\n\
	# set yrange [0:"+str(yrange)+"]\n\
	# set xtics rotate by -45\n\
	\n\
	# We want a small gap between solid (filled-in) bars.\n\
	set boxwidth 0.8 relative\n\
	set style fill solid 1.0\n\
	\n\
	# Plot the histogram (one curve).\n\
	plot 'respuestas.tsv' using 1:xtic(2) with boxes title '"+question['text'].strip('\n').encode('utf-8')+"'\n\
	"
	file = open('tmp.gp', 'w+')
	file.write(gnuplot) # python will convert \n to os.linesep
	file.close()
#
#
#
#
	system('gnuplot tmp.gp')
	remove('respuestas.tsv')
	remove('tmp.gp')


from collections import deque

def dummy():
    time = 0
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
    direction = 1

    head_x, head_y = 1, 1       # 머리의 위치 1행 1열
    body = deque()
    body.append((head_x, head_y))
    board[head_x][head_y] = 1

    snake = True        # 머리가 몸에 부딪히면 False
    while True:
        # 먼저 해당 시각에 입력된 커맨드대로 방향전환이 있는지 체크
        if command:
            if command[0][0] == time:
                if command[0][1] == 'L':
                    direction = (direction + 3) % 4
                else:
                    direction = (direction + 1) % 4
                command.popleft()

        # 바라보고 있는 방향으로 몸을 늘려 머리를 위치시킴
        head_x += dx[direction]
        head_y += dy[direction]
        if head_x < 1 or head_x > n or head_y < 1 or head_y > n:
            return time + 1
        if board[head_x][head_y] == 0:  # 사과가 없으면 꼬리 한 칸 제거, 있으면 pass
            tail_x, tail_y = body.popleft()
            board[tail_x][tail_y] = 0
        board[head_x][head_y] = 1
        body.append((head_x, head_y))

        # 머리가 몸에 부딪혔는지 check
        for i in range(0, len(body)-1):
            if body[i] == (head_x, head_y):
                snake = False
                return time

        time += 1

n = int(input())
board = [[0]*(n+1) for _ in range(n+1)]

k = int(input())
for _ in range(k):
    i, j = map(int, input().split())
    board[i][j] = 2

l = int(input())
command = deque()
for _ in range(l):
    x, c = input().split()
    command.append((int(x), c))

print(dummy())


import tensorflow as tf
import numpy as np
import json
import os
from PIL import Image

def load_graph(frozen_graph_filename):
    # We load the protobuf file from the disk and parse it to retrieve the
    # unserialized graph_def
    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    # Then, we can use again a convenient built-in function to import a graph_def into the
    # current default Graph
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(
            graph_def,
            input_map=None,
            return_elements=None,
            name="prefix",
            op_dict=None,
            producer_op_list=None
        )
    return graph

def go(typ, image,path=None):
    print(os.getcwd())
#    /app/Code/WebApi/graph/output_graph.pb

    graph=load_graph(os.path.join(os.getcwd(),'Code/WebApi/graph/output_graph.pb'))
    # We access the input and output nodes
    input = graph.get_tensor_by_name('prefix/DecodeJpeg:0')
    output = graph.get_tensor_by_name('prefix/final_result:0')
    image = Image.open(image)
    image_array = None
    if typ == 'jpg':
        image_array = np.array(image)
    else:
        image_array = np.array(image)[:, :, 0:3]  # Select RGB channels only.

    with tf.Session(graph=graph) as sess:
        result = sess.run(output, feed_dict={
            input: image_array
        })
        result = result[0]
        datatemp = {
                'message': 'Model trained',
                'result': [
                    {
                        'prediction': [
                            {
                                'label':        'Bar Chart',
                                "probability":  format(result[1]),
                            },
                            {
                                'label':        'Line Chart',
                                "probability":   format(result[2]),
                            },
                            {
                                'label':        'Pie chart',
                                'probability':   format(result[0]),
                            },
                            {
                                'label':        'Scatter plot',
                                'probability':  format(result[3]),
                            },
                        ],
                        'file':'image.jpg'
                    }
                ]
            }
        print(json.dumps(datatemp))
        if path is not None :
            os.remove(path)
    return json.dumps(datatemp)


from flask import redirect, render_template, session, request
from oidc_rp import app, client

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/authenticate')
def authenticate():
    redirect_url = client.authenticate(session)
    return redirect(redirect_url)

@app.route('/repost_fragment', methods=['POST'])
def repost_fragment(**kwargs):
    info = client.implicit_flow_callback(request.form['url_fragment'], session)
    return success_page(info)

@app.route('/code_flow_callback')
def code_flow_callback():
    if 'error' in request.form:
        return "{}: {}".format(request.form['error'], request.form['error_description']), 500
    info = client.code_flow_callback(request.query_string, session)
    return success_page(info)

@app.route('/implicit_flow_callback')
def implicit_flow_callback():
    return render_template('repost_fragment.html')

def success_page(info):
    return render_template(
        'success_page.html',
        client_id=info['client_id'],
        client_secret=info['client_secret'],
        auth_code=info['auth_code'],
        access_token=info['access_token'],
        id_token_claims=info['id_token_claims'],
        userinfo=info['userinfo']
    )


import dataclasses
import typing as typ
import win32com.client
from astropy import units as u
from kgpy.optics import system
from kgpy.optics.zemax import ZOSAPI
from .. import configuration
from . import DiffractionGrating

__all__ = ['EllipticalGrating1']

@dataclasses.dataclass
class InstanceVarBase:
    _a_op: configuration.SurfaceOperand = dataclasses.field(
        default_factory=lambda: configuration.SurfaceOperand(
            op_factory=lambda: ZOSAPI.Editors.MCE.MultiConfigOperandType.PRAM,
            param_2=3,
        ),
        init=None,
        repr=None,
    )
    _b_op: configuration.SurfaceOperand = dataclasses.field(
        default_factory=lambda: configuration.SurfaceOperand(
            op_factory=lambda: ZOSAPI.Editors.MCE.MultiConfigOperandType.PRAM,
            param_2=4,
        ),
        init=None,
        repr=None,
    )
    _c_op: configuration.SurfaceOperand = dataclasses.field(
        default_factory=lambda: configuration.SurfaceOperand(
            op_factory=lambda: ZOSAPI.Editors.MCE.MultiConfigOperandType.PRAM,
            param_2=5,
        ),
        init=None,
        repr=None,
    )
    _alpha_op: configuration.SurfaceOperand = dataclasses.field(
        default_factory=lambda: configuration.SurfaceOperand(
            op_factory=lambda: ZOSAPI.Editors.MCE.MultiConfigOperandType.PRAM,
            param_2=6,
        ),
        init=None,
        repr=None,
    )
    _beta_op: configuration.SurfaceOperand = dataclasses.field(
        default_factory=lambda: configuration.SurfaceOperand(
            op_factory=lambda: ZOSAPI.Editors.MCE.MultiConfigOperandType.PRAM,
            param_2=7,
        ),
        init=None,
        repr=None,
    )

    _a_unit = u.dimensionless_unscaled
    _b_unit = u.dimensionless_unscaled
    _alpha_unit = u.dimensionless_unscaled
    _beta_unit = u.dimensionless_unscaled

@dataclasses.dataclass
class EllipticalGrating1(system.surface.EllipticalGrating1, InstanceVarBase, DiffractionGrating, ):

    def _update(self) -> typ.NoReturn:
        super()._update()
        self.a = self.a
        self.b = self.b
        self.c = self.c
        self.alpha = self.alpha
        self.beta = self.beta

    @property
    def _lde_row_type(self) -> ZOSAPI.Editors.LDE.SurfaceType:
        return ZOSAPI.Editors.LDE.SurfaceType.EllipticalGrating1

    @property
    def _lde_row_data(self) -> ZOSAPI.Editors.LDE.ISurfaceEllipticalGrating1:
        return win32com.client.CastTo(self._lde_row.SurfaceData, ZOSAPI.Editors.LDE.ISurfaceEllipticalGrating1.__name__)

    @property
    def _lde_row(self) -> ZOSAPI.Editors.LDE.ILDERow[ZOSAPI.Editors.LDE.ISurfaceEllipticalGrating1]:
        return super()._lde_row

    def _a_setter(self, value: float):
        self._lde_row_data.A = value

    @property
    def a(self) -> u.Quantity:
        return self._a

    @a.setter
    def a(self, value: u.Quantity):
        self._a = value
        self._set(value, self._a_setter, self._a_op, self._a_unit)

    def _b_setter(self, value: float):
        self._lde_row_data.B = value

    @property
    def b(self) -> u.Quantity:
        return self._b

    @b.setter
    def b(self, value: u.Quantity):
        self._b = value
        self._set(value, self._b_setter, self._b_op, self._b_unit)

    def _c_setter(self, value: float):
        self._lde_row_data.C = value

    @property
    def c(self) -> u.Quantity:
        return self._c

    @c.setter
    def c(self, value: u.Quantity):
        self._c = value
        self._set_with_lens_units(value, self._c_setter, self._c_op)

    def _alpha_setter(self, value: float):
        self._lde_row_data.Alpha = value

    @property
    def alpha(self) -> u.Quantity:
        return self._alpha

    @alpha.setter
    def alpha(self, value: u.Quantity):
        self._alpha = value
        self._set(value, self._alpha_setter, self._alpha_op, self._alpha_unit)

    def _beta_setter(self, value: float):
        self._lde_row_data.Beta = value

    @property
    def beta(self) -> u.Quantity:
        return self._beta

    @beta.setter
    def beta(self, value: u.Quantity):
        self._beta = value
        self._set(value, self._beta_setter, self._beta_op, self._beta_unit)


import pyqrcode
import cv2
from PIL import Image

qr = pyqrcode.create('http://www.cmu.edu/', error='M', version=3)
qr.png('test.png')
qr.png('test2.png',scale=10)
qr.png('test3.png',scale=10,module_color=(125,31,31,220))
img = cv2.imread("test.png",0)
img2 = cv2.resize(img, (0,0), fx=10, fy=10, interpolation = cv2.INTER_NEAREST)

for i in range(40,111):
	for j in range(40,111):
		img2[i][j]=255

for i in range(260,341):
	for j in range(40,111):
		img2[i][j]=255

for i in range(40,111):
	for j in range(260,341):
		img2[i][j]=255

for i in range(240,281):
	for j in range(240,281):
		img2[i][j]=255

def is_30by20(img,i,j):
	for k in range(20):
		for m in range(30):
			if img[i+k,j+m] != 0:
				return False
	return True

def locating_30by20(img):
	for i in range(331):
		for j in range(331):
			if is_30by20(img,i,j):
				for k in range(20):
					for m in range(30):
						img2[i+k][j+m]=100
				return j,i

box = Image.open("icon.png")
cv2.imwrite("test2.png",img2)
pic2 = Image.open("test2.png")
pic3 = Image.open("test3.png")

boxes = box.resize((70, 70), Image.ANTIALIAS)
box_small = box.resize((50, 50), Image.ANTIALIAS)
two_by_three = box.resize((30, 20), Image.ANTIALIAS)

pic3.paste(boxes, (40, 40))
pic3.paste(boxes, (260, 40))
pic3.paste(boxes, (40, 260))
pic3.paste(box_small, (240, 240))

two_by_three_list = []
for k in range(4):
	two_by_three_list.append(locating_30by20(img2))
print(two_by_three_list)
for i in range(4):
	if two_by_three_list[i]==None: break
	pic3.paste(two_by_three, two_by_three_list[i])

pic3.save("boxed_code.png")
#cv2.imshow('boxed_code',img2)
#cv2.waitKey(0)