<file_sep>from . import db


class Demand(db.Model):
    _tablename_ = 'demand'
    id = db.Column(db.INTEGER, primary_key=True)
    address = db.Column(db.VARCHAR(20))
    channel = db.Column(db.INTEGER)
    model = db.Column(db.VARCHAR(20))
    datetime = db.Column(db.DATETIME)
    demand_min = db.Column(db.FLOAT(precision='20,2'))
    demand_quarter = db.Column(db.FLOAT(precision='20,2'))
    R_value = db.Column(db.FLOAT(precision='20,2'))
    S_value = db.Column(db.FLOAT(precision='20,2'))
    T_value = db.Column(db.FLOAT(precision='20,2'))
    Total_value = db.Column(db.FLOAT(precision='20,2'))

    def __init__(self, address, channel, model, datetime,
                 demand_min, demand_quarter, R_value, S_value,
                 T_value, Total_value):
        self.address = address
        self.channel = channel
        self.model = model
        self.datetime = datetime
        self.demand_min = demand_min
        self.demand_quarter = demand_quarter
        self.R_value = R_value
        self.S_value = S_value
        self.T_value = T_value
        self.Total_value = Total_value
<file_sep># DAE
測試上傳至GitHub
<file_sep>function randNum(){
	return ((Math.floor( Math.random()* (1+40-20) ) ) + 20)* 1200;
}

function randNum2(){
	return ((Math.floor( Math.random()* (1+40-20) ) ) + 20) * 500;
}

function randNum3(){
	return ((Math.floor( Math.random()* (1+40-20) ) ) + 20) * 300;
}

function randNum4(){
	return ((Math.floor( Math.random()* (1+40-20) ) ) + 20) * 100;
}

$(document).ready(function(){

	/* ---------- Event ---------- */
	var ldata1 = [], ldata2 = [], ldata3 = [], ldata4 = [], ldata5 = [];

	var d1 = [];
	for (var i = 1; i <= 96; i += 1)
		d1.push([i, parseInt(Math.random() * 5)]);
	
	var d2 = [];
	for (var i = 1; i <= 24; i += 1)
		d2.push([i, 10 + parseInt(Math.random() * 5)]);

	var d3 = [];
	for (var i = 1; i <= 1; i += 1)
		d3.push([i, 200 + parseInt(Math.random() * 80)]);

	ldata1.push(d1);
	ldata1.push(d2);
	ldata1.push(d3);

	var d1 = [];
	for (var i = 1; i <= 96; i += 1)
		d1.push([i, parseInt(Math.random() * 5)]);
	
	var d2 = [];
	for (var i = 1; i <= 24; i += 1)
		d2.push([i, 10 + parseInt(Math.random() * 5)]);

	var d3 = [];
	for (var i = 1; i <= 1; i += 1)
		d3.push([i, 200 + parseInt(Math.random() * 80)]);

	ldata2.push(d1);
	ldata2.push(d2);
	ldata2.push(d3);

	var d1 = [];
	for (var i = 1; i <= 96; i += 1)
		d1.push([i, parseInt(Math.random() * 5)]);
	
	var d2 = [];
	for (var i = 1; i <= 24; i += 1)
		d2.push([i, 10 + parseInt(Math.random() * 5)]);

	var d3 = [];
	for (var i = 1; i <= 1; i += 1)
		d3.push([i, 200 + parseInt(Math.random() * 80)]);

	ldata3.push(d1);
	ldata3.push(d2);
	ldata3.push(d3);

	var d1 = [];
	for (var i = 1; i <= 96; i += 1)
		d1.push([i, parseInt(Math.random() * 5)]);
	
	var d2 = [];
	for (var i = 1; i <= 24; i += 1)
		d2.push([i, 10 + parseInt(Math.random() * 5)]);

	var d3 = [];
	for (var i = 1; i <= 1; i += 1)
		d3.push([i, 200 + parseInt(Math.random() * 80)]);

	ldata4.push(d1);
	ldata4.push(d2);
	ldata4.push(d3);

	var d1 = [];
	for (var i = 1; i <= 96; i += 1)
		d1.push([i, parseInt(Math.random() * 5)]);
	
	var d2 = [];
	for (var i = 1; i <= 24; i += 1)
		d2.push([i, 10 + parseInt(Math.random() * 5)]);

	var d3 = [];
	for (var i = 1; i <= 1; i += 1)
		d3.push([i, 200 + parseInt(Math.random() * 80)]);

	ldata5.push(d1);
	ldata5.push(d2);
	ldata5.push(d3);


	$("#stack_btn").click(function(){
		var d = [];
		if($("#stackchart").length)
		{
			if(stack_check_box_1.checked){
				d = ldata1;
			}
	        if(stack_check_box_2.checked){
				d = ldata2;
			}
	        if(stack_check_box_3.checked){
				d = ldata3;
			}
	        if(stack_check_box_4.checked){
				d = ldata4;
			}
	        if(stack_check_box_5.checked){
				d = ldata5;
			}

			var stack = 0, bars = true, lines = false, steps = false;

			function plotWithOptions(d) {
				$.plot($("#stackchart"), [ d ], {
					series: {
						stack: stack,
						bars: { show: true, barWidth: 0.6 },
					},
					colors: ["#FA5833", "#2FABE9", "#FABB3D"]
				});
			}

			plotWithOptions(d[0]);

			$(".graphControls input").click(function (e) {
				e.preventDefault();
				bars = $(this).val().indexOf("15分鐘") != -1;
				lines = $(this).val().indexOf("1小時") != -1;
				steps = $(this).val().indexOf("1天") != -1;
				week = $(this).val().indexOf("1周") != -1;
				//console.log(bars, lines, steps);
				if(bars)
					plotWithOptions(d[0]);
				else if(lines)
					plotWithOptions(d[1]);
				else 
					plotWithOptions(d[2]);
			});
		}
	});


	var rd1 = [], rd2 = [], rd3 = [], rd4 = [], rd5 = [];
	for (var i = 1; i < 25; i += 1){
		rd1.push([i, 3 + Math.random()*5]);
		rd2.push([i, 3 + Math.random()*5]);
		rd3.push([i, 3 + Math.random()*5]);
		rd4.push([i, 3 + Math.random()*5]);
		rd5.push([i, 3 + Math.random()*5]);
	}
	
	$("#lines_btn").click(function(){
		
		if(check_box_1.checked){
			var d1 = rd1;
		}
        if(check_box_2.checked){
			var d2 = rd2;
		}
        if(check_box_3.checked){
			var d3 = rd3;
		}
        if(check_box_4.checked){
			var d4 = rd4;
		}
        if(check_box_5.checked){
			var d5 = rd5;
		}
        if($("#sincos").length)
		{
			var plot = $.plot($("#sincos"),
				   [ { data: d1, label: "電表一"}, { data: d2, label: "電表二" }, { data: d3, label: "電表三" }, { data: d4, label: "電表四" }, { data: d5, label: "電表五" } ], {
					   series: {
						   lines: { show: true,
									lineWidth: 2,
								 },
						   points: { show: true },
						   shadowSize: 2
					   },
					   grid: { hoverable: true, 
							   clickable: true, 
							   tickColor: "#dddddd",
							   borderWidth: 0 
							 },
					   //yaxis: { min: -1.2, max: 1.2 },
					   colors: ["#FA5833", "#2FABE9", "yellow", "green"]
					 });

			function showTooltip(x, y, contents) {
				$('<div id="tooltip">' + contents + '</div>').css( {
					position: 'absolute',
					display: 'none',
					top: y + 5,
					left: x + 5,
					border: '1px solid #fdd',
					padding: '2px',
					'background-color': '#dfeffc',
					opacity: 0.80
				}).appendTo("body").fadeIn(200);
			}

			var previousPoint = null;
			$("#sincos").bind("plothover", function (event, pos, item) {
				$("#x").text(pos.x.toFixed(2));
				$("#y").text(pos.y.toFixed(2));

					if (item) {
						if (previousPoint != item.dataIndex) {
							previousPoint = item.dataIndex;

							$("#tooltip").remove();
							var x = item.datapoint[0].toFixed(2),
								y = item.datapoint[1].toFixed(2);

							showTooltip(item.pageX, item.pageY,
										item.series.label + " of " + x + " = " + y);
						}
					}
					else {
						$("#tooltip").remove();
						previousPoint = null;
					}
			});
			
		}
	});

	/* ---------- Chart with points ---------- */
	
	
	/* ---------- Stack chart ---------- */
	
	
	/* ---------- Donut chart ---------- */
	if($("#osChart").length)
	{
		$.plot($("#osChart"), data,
		{
				series: {
						pie: {
								innerRadius: 0.6,
								show: true
						}
				},
				legend: {
					show: true
				},
				colors: ["#FA5833", "#2FABE9", "#FABB3D", "#78CD51"]
		});
	}

	/* ---------- Pie chart ---------- */
	var data = [
	{ label: "Internet Explorer",  data: 12},
	{ label: "Mobile",  data: 27},
	{ label: "Safari",  data: 85},
	{ label: "Opera",  data: 64},
	{ label: "Firefox",  data: 90},
	{ label: "Chrome",  data: 112}
	];
	
	if($("#piechart").length)
	{
		$.plot($("#piechart"), data,
		{
			series: {
					pie: {
							show: true
					}
			},
			grid: {
					hoverable: true,
					clickable: true
			},
			legend: {
				show: false
			},
			colors: ["#FA5833", "#2FABE9", "#FABB3D", "#78CD51"]
		});
		
		function pieHover(event, pos, obj)
		{
			if (!obj)
					return;
			percent = parseFloat(obj.series.percent).toFixed(2);
			$("#hover").html('<span style="font-weight: bold; color: '+obj.series.color+'">'+obj.series.label+' ('+percent+'%)</span>');
		}
		$("#piechart").bind("plothover", pieHover);
	}
	
	/* ---------- Donut chart ---------- */
	if($("#donutchart").length)
	{
		$.plot($("#donutchart"), data,
		{
				series: {
						pie: {
								innerRadius: 0.5,
								show: true
						}
				},
				legend: {
					show: false
				},
				colors: ["#FA5833", "#2FABE9", "#FABB3D", "#78CD51"]
		});
	}




	 // we use an inline data source in the example, usually data would
	// be fetched from a server
	var data = [], totalPoints = 300;
	function getRandomData() {
		if (data.length > 0)
			data = data.slice(1);

		// do a random walk
		while (data.length < totalPoints) {
			var prev = data.length > 0 ? data[data.length - 1] : 50;
			var y = prev + Math.random() * 10 - 5;
			if (y < 0)
				y = 0;
			if (y > 100)
				y = 100;
			data.push(y);
		}

		// zip the generated y values with the x values
		var res = [];
		for (var i = 0; i < data.length; ++i)
			res.push([i, data[i]])
		return res;
	}

	// setup control widget
	var updateInterval = 30;
	$("#updateInterval").val(updateInterval).change(function () {
		var v = $(this).val();
		if (v && !isNaN(+v)) {
			updateInterval = +v;
			if (updateInterval < 1)
				updateInterval = 1;
			if (updateInterval > 2000)
				updateInterval = 2000;
			$(this).val("" + updateInterval);
		}
	});

	
	if($("#realtimechart").length)
	{
		var options = {
			series: { shadowSize: 1 },
			lines: { fill: true, fillColor: { colors: [ { opacity: 1 }, { opacity: 0.1 } ] }},
			yaxis: { min: 0, max: 100 },
			xaxis: { show: false },
			colors: ["#F4A506"],
			grid: {	tickColor: "#dddddd",
					borderWidth: 0 
			},
		};
		var plot = $.plot($("#realtimechart"), [ getRandomData() ], options);
		function update() {
			plot.setData([ getRandomData() ]);
			// since the axes don't change, we don't need to call plot.setupGrid()
			plot.draw();
			
			setTimeout(update, updateInterval);
		}

		update();
	}
	
});<file_sep>$(function() { 
    $("#dialog_div").dialog({ 
        autoOpen: false,
        show: "blind", 
        hide: "explode",
        dialogClass: "dlg-no-close",
        width: 400,
        height:350,
        buttons: { 
            "Ok": function() { 
                $(this).dialog("close");
                $("#value").empty();
                $("#cost").empty();
                $( "#count_btn").unbind( "click" );
            }, 
            "Cancel": function() { 
                $(this).dialog("close"); 
                $("#value").empty();
                $("#cost").empty();
                $( "#count_btn").unbind( "click" );
            }
        }
    });

    $("#refresh").click(function() { 
        location.reload();
    });

    $(".info-box.red-bg").click(function() { 
        $("#dialog_div").dialog("open");
       
        $("#count_btn").click(function() { 
            $("#value").empty();
            $("#cost").empty();
            $.ajax({
                url:"assets/php/query_count.php",
                type: "GET",
                data: {
                        houlddeviceindex: 'SMB350-4-B CH1 R',
                        sDate: $('#datetimepicker1').val(),
                        eDate: $('#datetimepicker2').val()
                    },
                dataType: "json",
                success: function(response) {
                    var money = $("#money").val();
                    $("#value").append(response+" KWH");
                    $("#cost").append(response*money+" 元");
                }
            });
        });
    });

    $(".info-box.green-bg").click(function() { 
        $("#dialog_div").dialog("open"); 
        $("#count_btn").click(function() { 
            $("#value").empty();
            $("#cost").empty();
            $.ajax({
                url:"assets/php/query_count.php",
                type: "GET",
                data: {
                        houlddeviceindex: 'SMB350-4-B CH1 S',
                        sDate: $('#datetimepicker1').val(),
                        eDate: $('#datetimepicker2').val()
                    },
                dataType: "json",
                success: function(response) {
                    var money = $("#money").val();
                    $("#value").append(response+" KWH");
                    $("#cost").append(response*money+" 元");
                }
            });
        });
    });

    $(".info-box.blue-bg").click(function() { 
        $("#dialog_div").dialog("open"); 
        $("#count_btn").click(function() { 
            $("#value").empty();
            $("#cost").empty();
            $.ajax({
                url:"assets/php/query_count.php",
                type: "GET",
                data: {
                        houlddeviceindex: 'SMB350-4-B CH1 T',
                        sDate: $('#datetimepicker1').val(),
                        eDate: $('#datetimepicker2').val()
                    },
                dataType: "json",
                success: function(response) {
                    var money = $("#money").val();
                    $("#value").append(response+" KWH");
                    $("#cost").append(response*money+" 元");
                }
            });
        });
    });

    $(".info-box.magenta-bg").click(function() { 
        $("#dialog_div").dialog("open"); 
        $("#count_btn").click(function() {
            $("#value").empty();
            $("#cost").empty();
            $.ajax({
                url:"assets/php/query_count.php",
                type: "GET",
                data: {
                        houlddeviceindex: 'SMB350-4-B CH2 R',
                        sDate: $('#datetimepicker1').val(),
                        eDate: $('#datetimepicker2').val()
                    },
                dataType: "json",
                success: function(response) {
                    var money = $("#money").val();
                    $("#value").append(response+" KWH");
                    $("#cost").append(response*money+" 元");
                }
            });
        });
    });

    $(".info-box.yellow-bg").click(function() { 
        $("#dialog_div").dialog("open"); 
        $("#count_btn").click(function() {
            $("#value").empty();
            $("#cost").empty();
            $.ajax({
                url:"assets/php/query_count.php",
                type: "GET",
                data: {
                        houlddeviceindex: 'PM210',
                        sDate: $('#datetimepicker1').val(),
                        eDate: $('#datetimepicker2').val()
                    },
                dataType: "json",
                success: function(response) {
                    var money = $("#money").val();
                    $("#value").append(response+" KWH");
                    $("#cost").append(response*money+" 元");
                }
            });
        });
    });

    $.ajax({
        url:"assets/php/query.php",
        type: "GET",
        data: {
                houlddeviceindex: ['SMB350-4-B CH1 R','SMB350-4-B CH1 S','SMB350-4-B CH1 T','SMB350-4-B CH2 R', 'PM210']
            },
        dataType: "json",
        success: function(response) {
            remove();
            $("#updatetime").append(getDateTime());

            for(var i=1;i<6;i++){
                var index = i-1;
                if(response[index])
                    $("#dev"+i).append(response[index]);
                else
                    $("#dev"+i).append(0);
            }
            $("#connect").empty();
            $("#connect").append("通訊良好");
        }
    });

    function getDateTime(){
        var currentTime = new Date();
        var currentDate = new Date();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        var day = currentDate.getDate();
        var month = currentDate.getMonth();
        var year = currentDate.getFullYear();

        if (minutes < 10)
            minutes = "0" + minutes;
        if (month < 10)
            month = "0" + month;
        if (day < 10)
            day = "0" + day;

        var time = year + "-" + month + "-" + day + " " + hours + ":" + minutes;
        return time;
    }

    function remove(){
        $("#dev1").empty();
        $("#dev2").empty();
        $("#dev3").empty();
        $("#dev4").empty();

    }
});<file_sep>import logging

from logging.handlers import RotatingFileHandler


class BasicConfig(object):
    SECRET_KEY = '421d7fa062a76ca25669e91923a3c79f'
    #SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    SQLALCHEMY_RECORD_QUERIES = True

    @staticmethod
    def init_app(app):
        _handler = RotatingFileHandler('app.log',
                                       maxBytes=10000,
                                       backupCount=1)

        _handler.setLevel(logging.WARNING)
        app.logger.addHandler(_handler)


class DevelopmentConfig(BasicConfig):
    DEBUG = True

    SQLALCHEMY_DATABASE_URI = 'mysql://root:kDd414o6@localhost/dae'
    SQLALCHEMY_ECHO = True
   # SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
   #     'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')


class TestingConfig(BasicConfig):
    pass


class ProductionConfig(BasicConfig):
    pass


config = {
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig
}
<file_sep>"""initial migration

Revision ID: fce4c7d2f0f6
Revises: 
Create Date: 2017-06-07 13:19:58.722466

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'fce<KEY>'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('demand',
    sa.Column('id', sa.INTEGER(), nullable=False),
    sa.Column('address', sa.VARCHAR(length=20), nullable=True),
    sa.Column('channel', sa.INTEGER(), nullable=True),
    sa.Column('model', sa.VARCHAR(length=20), nullable=True),
    sa.Column('datetime', sa.DATETIME(), nullable=True),
    sa.Column('demand_min', sa.FLOAT(precision='20,2'), nullable=True),
    sa.Column('demand_quarter', sa.FLOAT(precision='20,2'), nullable=True),
    sa.Column('R_value', sa.FLOAT(precision='20,2'), nullable=True),
    sa.Column('S_value', sa.FLOAT(precision='20,2'), nullable=True),
    sa.Column('T_value', sa.FLOAT(precision='20,2'), nullable=True),
    sa.Column('Total_value', sa.FLOAT(precision='20,2'), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('demand')
    # ### end Alembic commands ###
<file_sep>/*每日最大需量*/

function daily_maxDemand(data) {
    var chart = AmCharts.makeChart("daily_maxDemand", {
        "type": "serial",
        "theme": "light",
        "dataProvider": data,
        "legend": {
            // "equalWidths": false,
            "useGraphSettings": true,
            "valueAlign": "left",
            "valueWidth": 120
        },
        "valueAxes": [{
            "gridColor": "#FFFFFF",
            "gridAlpha": 0.2,
            "dashLength": 0
        }],
        "gridAboveGraphs": true,
        "startDuration": 1,
        "graphs": [{
            "balloonText": "[[category]]: <b>[[value]]</b>kW",
            "fillAlphas": 0.8,
            "lineAlpha": 0.2,
            "type": "column",
            "title": "最高需量",
            "legendValueText": "[[value]] Watt",
            "valueField": "peak_demand"
        }],
        "chartCursor": {
            "categoryBalloonEnabled": false,
            "cursorAlpha": 0,
            "zoomable": false
        },
        "categoryField": "time",
        "categoryAxis": {
            "gridPosition": "start",
            "gridAlpha": 0,
            "tickPosition": "start",
            "tickLength": 20
        },

    });


}
//每日最大需輛區間
function daily_demand(data) {

    var chart = AmCharts.makeChart("daily_maxDemand_period", {
        "type": "serial",
        //圖例
        "mouseWheelZoomEnabled": false,
        "dataDateFormat": "YYYY-MM-DD JJ:NN:SS",
        "legend": {
            // "equalWidths": false,
            "useGraphSettings": true,
            "valueAlign": "left",
            "valueWidth": 120
        },
        //資料
        "dataProvider": data["demands"],
        "valueAxes": [
            //Demand值軸
            {
                "id": "demandAxis",
                "gridColor": "#FFFFFF",
                "gridAlpha": 0.5,
                "position": "left",
                "title": "kW",
                "minimum": 0
            },
        ],
        "gridAboveGraphs": true,
        "graphs": [{
            "id": "g1",
            "balloonText": "<span style='font-size:12px; font-family:Microsoft JhengHei;'> 時間:[[category]]<br><b>需量:[[value]]kW</b>[[additional]]</span>",
            "bullet": "round",
            "bulletsize": 0.5,
            "bulletBorderThickness": 1.5,
            "bulletBorderAlpha": 0.5,
            "bulletColor": "#FFFFFF",
            "useLineColorForBulletBorder": true,
            "balloon": {
                "drop": false
            },
            "hideBulletsCount": 24,
            "legendValueText": "[[value]] kW",
            "title": "每10秒功率",
            "labelPosition": "right",
            "valueField": "Value",
            "valueAxis": "demandAxis",
            "lineColor": " #1f77b4",
            "lineThickness": 2.5
        }, ],
        "chartScrollbar": {
            "graph": "g1",
            "autoGridCount": true,
            "scrollbarHeight": 40,
            "color": "#000000"
        },
        "chartCursor": {
            "categoryBalloonEnabled": false,
            "categoryBalloonDateFormat": "MMM DD,JJ:NN:SS",
            "cursorPosition": "mouse",
            "cursorColor": "#FFFFFF",
            "cursorAlpha": 0
        },
        "valueScrollbar": {
            "autoGridCount": true,
            "color": "#000000",
            "scrollbarHeight": 50
        },
        "categoryField": "time",
        "categoryAxis": {
            "minPeriod": "10ss",
            "parseDates": true
        },
    });


}
/*該月前三大需量*/
function Demand_high(data) {
    var chart = AmCharts.makeChart("Demand_high", {
        "type": "serial",
        "theme": "light",
        "dataProvider": data,
        "legend": {
            // "equalWidths": false,
            "useGraphSettings": true,
            "valueAlign": "left",
            "valueWidth": 120
        },
        "valueAxes": [{
            "gridColor": "#FFFFFF",
            "gridAlpha": 0.2,
            "dashLength": 0
        }],
        "gridAboveGraphs": true,
        "startDuration": 1,
        "graphs": [{
            "balloonText": "[[category]]: <b>[[value]]</b>kW",
            "fillAlphas": 0.8,
            "lineAlpha": 0.2,
            "type": "column",
            "title": "最高需量",
            "legendValueText": "[[value]] Watt",
            "valueField": "peak_demand"
        }],
        "chartCursor": {
            "categoryBalloonEnabled": false,
            "cursorAlpha": 0,
            "zoomable": false
        },
        "categoryField": "time",
        "categoryAxis": {
            "gridPosition": "start",
            "gridAlpha": 0,
            "tickPosition": "start",
            "tickLength": 20,
        },

    });
}
/*用電折線圖*/
function power(divs, data) {
    for (var i in divs) {
        if (data[i] !== undefined) {
            console.log(i + " " + divs[i] + "\n" + data[i]["demands"])
            var chart = AmCharts.makeChart(divs[i], {
                "type": "serial",
                //圖例
                "mouseWheelZoomEnabled": false,
                "dataDateFormat": "YYYY-MM-DD JJ:NN:SS",
                "legend": {
                    // "equalWidths": false,
                    "useGraphSettings": true,
                    "valueAlign": "left",
                    "valueWidth": 120
                },
                //資料
                "dataProvider": data[i]["demands"],
                "valueAxes": [
                    //Demand值軸
                    {
                        "id": "demandAxis",
                        "gridColor": "#FFFFFF",
                        "gridAlpha": 0.5,
                        "position": "left",
                        "title": "kW",
                        "minimum": 0
                    },
                ],
                "gridAboveGraphs": true,
                "graphs": [{
                    "id": "g1",
                    "balloonText": "<span style='font-size:12px; font-family:Microsoft JhengHei;'> 時間:[[category]]<br><b>需量:[[value]]kW</b>[[additional]]</span>",
                    "bullet": "round",
                    "bulletsize": 0.5,
                    "bulletBorderThickness": 1.5,
                    "bulletBorderAlpha": 0.5,
                    "bulletColor": "#FFFFFF",
                    "useLineColorForBulletBorder": true,
                    "balloon": {
                        "drop": false
                    },
                    "hideBulletsCount": 24,
                    "legendValueText": "[[value]] kW",
                    "title": "每10秒功率",
                    "labelPosition": "right",
                    "valueField": "Value",
                    "valueAxis": "demandAxis",
                    "lineColor": " #1f77b4",
                    "lineThickness": 2.5
                }, ],
                "chartScrollbar": {
                    "graph": "g1",
                    "autoGridCount": true,
                    "scrollbarHeight": 40,
                    "color": "#000000"
                },
                "chartCursor": {
                    "categoryBalloonEnabled": false,
                    "categoryBalloonDateFormat": "MMM DD,JJ:NN:SS",
                    "cursorPosition": "mouse",
                    "cursorColor": "#FFFFFF",
                    "cursorAlpha": 0
                },
                "valueScrollbar": {
                    "autoGridCount": true,
                    "color": "#000000",
                    "scrollbarHeight": 50
                },
                "categoryField": "time",
                "categoryAxis": {
                    "minPeriod": "10ss",
                    "parseDates": true
                },
            });
        }
    }
}<file_sep>function startTime(type) {
    var today = new Date(); //定義日期對象
    var yyyy = today.getFullYear(); //通過日期對象的getFullYear()方法返回年
    var MM = today.getMonth() + 1; //通過日期對象的getMonth()方法返回年
    var dd = today.getDate(); //通過日期對象的getDate()方法返回年
    var hh = today.getHours(); //通過日期對象的getHours方法返回小時
    var mm = today.getMinutes(); //通過日期對象的getMinutes方法返回分?
    var ss = today.getSeconds(); //通過日期對象的getSeconds方法返回秒

    // 如果分?或小時的值小於10，則在其值前加0，比如如果時間是下午3點20分9秒的話，則顯示15：20：09
    MM = checkTime(MM);
    dd = checkTime(dd);
    mm = checkTime(mm);
    ss = checkTime(ss);
    var day; //用於保存星期（getDay()方法得到星期編號）
    if (today.getDay() == 0) day = "星期日";
    if (today.getDay() == 1) day = "星期一";
    if (today.getDay() == 2) day = "星期二";
    if (today.getDay() == 3) day = "星期三";
    if (today.getDay() == 4) day = "星期四";
    if (today.getDay() == 5) day = "星期五";
    if (today.getDay() == 6) day = "星期六";

    switch (type) {
        case '1':
            document.getElementById('nowDateTimeSpan-demend').innerHTML = yyyy + "-" + MM + "-" + dd + " " + hh + ":" + mm + ":" + ss + "   " + day;
            setTimeout('startTime("1")', 1000); //每一秒中重新加載startTime()方法
            break;
        case '2':
            return yyyy + "-" + MM + "-" + dd + " " + hh + ":" + mm + ":" + ss;

    }
}

function checkTime(i) {
    if (i < 10)
        i = "0" + i;
    return i;
} // checkTime function
//set the button
var check = 0;
var index_year = 0;
var index_month = 0;
var index_day = 0;
$(document).ready(function () {
    $("a.list-group-item").click(function () {
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
    });
    //dialog show
    $("button.btn.btn-info.col-md-12").click(function () {
        $("#dialog_model").dialog({
            dialogClass: "dlg-no-close",
            width: 1000,
            height: 750,
            resizeStop: function () {
                $(this).height($(this).parent().height() - $(this).prev('.ui-dialog-titlebar').height() - $(this).prev('.ui-dialog-buttonpane').height() - 34);
                $(this).width($(this).prev('.ui-dialog-titlebar').width() + 2);
                // $("#Demand_high, #Demand_high_Interval, #Demand").height($(this).height() - $(".modal-header").height() - $(".dateframe").height() - $("#myTab").height() - 34);
            },
            open: function () {
                // $("#Demand_high, #Demand_high_Interval, #Demand").height($(this).height() - $(".modal-header").height() - $(".dateframe").height() - $("#myTab").height() - 34);
                $(document).ready(function () {
                    realtime_demand();
                    $('#demand_page').show();
                    $('#setting_page').hide();
                    //open　即插入需量值
                    // $("#real_demand > span").append("456");

                });
            },
        });
    });
    $("#Demand_Setting").click(function () {
        $("#page-wrapper").dialog({
            title: "需量反應設定",
            dialogClass: "dlg-no-close",
            width: 800,
            height: 700,
            resizeStop: function () {
                $(this).height($(this).parent().height() - $(this).prev('.ui-dialog-titlebar').height() - $(this).prev('.ui-dialog-buttonpane').height() - 34);
                $(this).width($(this).prev('.ui-dialog-titlebar').width() + 2);
                // $("#Demand_high, #Demand_high_Interval, #Demand").height($(this).height() - $(".modal-header").height() - $(".dateframe").height() - $("#myTab").height() - 34);
            },
            open: function () {
                // $("#Demand_high, #Demand_high_Interval, #Demand").height($(this).height() - $(".modal-header").height() - $(".dateframe").height() - $("#myTab").height() - 34);
                $(document).ready(function () {
                    realtime_demand();
                    $('#demandsetting_page').show();
                    $('#groupdown_setting').hide();
                    //open　即插入需量值
                    // $("#real_demand > span").append("456");

                });
            },
        });
    });
    $('#datetime').datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-MM-dd',
        maxDate: 0,
        minDate: "-23m",
        onClose: function (dateText, inst) {
            $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
        }
    });



    $('#demandControl').click(function (e) {
        $('#demand_page').hide();
        $('#setting_page').show();
    });
    $('#returnpage').click(function (e) {
        $('#setting_page').hide();
        $('#demand_page').show();

    });
    $('#groupdown').click(function (e) {
        $('#demandsetting_page').hide();
        $('#groupdown_setting').show();
    });
    $('#group_returnpage').click(function (e) {
        $('#groupdown_setting').hide();
        $('#demandsetting_page').show();
    });
});

// }
//Demans_Setting

$(function () {
    $("#demand-range").slider({
        range: true,
        min: 0,
        max: 100,
        step: 5,
        values: [45, 70],
        slide: function (event, ui) {
            $("#demand_bottom").val(ui.values[0]);
            $("#demand_top").val(ui.values[1]);
        }
    });
    $("#demand_bottom").val($("#demand-range").slider("values", 0));
    $("#demand_top").val($("#demand-range").slider("values", 1));
});

$(function () {
    $("#demand-max").slider({
        range: "min",
        min: 500,
        max: 1500,
        step: 10,
        value: 1000,

        slide: function (event, ui) {
            $("#max").val(ui.value);
        }
    });
    $("#max").val($("#demand-max").slider("value"));
});

$(function () {
    var spinner = $("#gap1").spinner();
});

$(function () {
    var spinner = $("#delay").spinner();
});

$(function () {
    var spinner = $("#gap2").spinner();
});<file_sep>//////////////////////////////////////純每15分鐘平均用電需量//未使用
function barchart2(data) {
    //console.log(data);
    var chart = AmCharts.makeChart("chartdiv2", {
        "theme": "light",
        "type": "serial",
        "startDuration": 2,
        "dataProvider": data,
        "graphs": [{
            "balloonText": "[[category]]: <b>[[value]]</b>kW",
            "fillColorsField": "color",
            "fillAlphas": 1,
            "lineAlpha": 0.1,
            "type": "column",
            "valueField": "Average_demand"
        }],
        "depth3D": 20,
        "angle": 30,
        "chartCursor": {
            "categoryBalloonEnabled": false,
            "cursorAlpha": 0,
            "zoomable": false
        },
        "categoryField": "Time",
        "categoryAxis": {
            "gridPosition": "start",
            "labelRotation": 90
        },
        "categorxAxis": {
            "gridPosition": "start",
            "labelRotation": 0
        },
        "export": {
            "enabled": true
        }

    });
}<file_sep>alembic==0.9.1
click==6.7
Flask==0.12.1
Flask-Migrate==2.0.3
Flask-Script==2.0.5
Flask-SQLAlchemy==2.2
itsdangerous==0.24
Jinja2==2.9.6
Mako==1.0.6
MarkupSafe==1.0
mysqlclient==1.3.10
python-editor==1.0.3
requests==2.13.0
SQLAlchemy==1.1.9
Werkzeug==0.12.1
<file_sep>$(document).ready(function () {
    // $.ajax({
    //         type: "GET", //傳值方式有分 post & get
    //         url: "/api/v1.0/", //第一筆用電折線圖
    //         dataType: 'json',
    //         data: {
    //             //傳送2017/06取得資料格式為該月第一筆最大需量的270筆(每10秒)如2017-06-10 12:15-12:45
    //         },
    //         success: function (meter_count) {
    //            meter(meter_count);
    //         },
    //         error: function () {
    //             alert("no data");
    //         }
    //     });
    $('#load').click(function () {
        //該月每日最大需量
        if ($("#datetime").val() == "") {
            alert("請選擇日期");
            return;
        }
        var spinner_daily_maxDemand = show_spinner($("#daily_maxDemand"));
        $.ajax({
            type: "GET", //傳值方式有分 post & get
            url: "/api/v1.0/peak_period_everyday_in_month", //第一筆用電折線圖
            dataType: 'json',
            data: {
                "address": "0",
                "channel": "0",
                "datetime": $("#datetime").val()
                //傳送2017/06取得資料格式為該月第一筆最大需量的270筆(每10秒)如2017-06-10 12:15-12:45
            },
            success: function (response) {
                daily_maxDemand(response);
                remove_spinner(spinner_daily_maxDemand);
            },
            error: function () {
                alert("no data");
            }
        });



        //每日最大需量區間

        var spinner_daily_maxDemand_period = show_spinner($("#daily_maxDemand_period"));
        $.ajax({
            type: "GET", //傳值方式有分 post & get
            url: "/api/v1.0/peak_period_in_day", //第一筆用電折線圖
            dataType: 'json',
            data: {
                "address": "0",
                "channel": "0",
                "datetime": $("#datetime").val()
                //傳送2017/06取得資料格式為該月第一筆最大需量的270筆(每10秒)如2017-06-10 12:15-12:45
            },
            success: function (response) {
                daily_demand(response);
                remove_spinner(spinner_daily_maxDemand_period);
            },
            error: function () {
                alert("no data");
            }
        });

        //該月前三高需量

        var spinner_Demand_high = show_spinner($("#Demand_high"));
        $.ajax({
            type: "GET", //傳值方式有分 post & get
            url: "/api/v1.0/peak_periods_in_month", //第一筆用電折線圖
            dataType: 'json',
            data: {
                "address": "0",
                "channel": "0",
                "datetime": $("#datetime").val()
                //傳送2017/06取得資料格式為該月第一筆最大需量的270筆(每10秒)如2017-06-10 12:15-12:45
            },
            success: function (response) {
                Demand_high(response);
                remove_spinner(spinner_Demand_high);
            },
            error: function (response) {
                alert("no data");
            }
        });
        Demand_high();

        //最高需量折線圖
        $(".col-sm-12> nav > ul > li > a").click(function () {
            var data_select = $(this).text();
            if (data_select = "最高需量用電折線圖") {
                first_graph();
                //second_graph();
                //third_graph();
            }
        });

    });
});

// function meter(meterdata) {
//     for (var meter in meterdata) {
//         $("#showmeter").append('<div class="info-box red-bg">\
//                             <div class="count">' +meter["name"]+ meter["channel"] + '/' + meter["address"] + '</div>\
//                             <button type="button" class="btn btn-info col-md-12" style="border-radius:10px;">\
//                                 <div style="font-size: 18px ; font-family:Microsoft JhengHei;">用電資訊</div>\
//                             </button>\
//                         </div>');
//     }
// }
function first_graph() {

    var spinner_first_graph = show_spinner($("#first_graph"));
    var spinner_second_graph = show_spinner($("#second_graph"));
    var spinner_third_graph = show_spinner($("#third_graph"));
    $.ajax({
        type: "GET", //傳值方式有分 post & get
        url: "/api/v1.0/peak_periods_in_month_interval", //第一筆用電折線圖
        dataType: 'json',
        data: {
            "address": "0",
            "channel": "0",
            "datetime": $("#datetime").val() //傳送2017/06取得資料格式為該月第一筆最大需量的270筆(每10秒)如2017-06-10 12:15-12:45
        },
        success: function (response) {
            power(["first_graph", "second_graph", "third_graph"], response);
            remove_spinner(spinner_first_graph);
            remove_spinner(spinner_second_graph);
            remove_spinner(spinner_third_graph);
        },
        error: function () {
            alert("no data");
        }
    });
}

function show_spinner(div) {
    $(div).empty();
    return $('<div class="spinner"> \
                <div class="rect1"></div> \
                <div class="rect2"></div> \
                <div class="rect3"></div> \
                <div class="rect4"></div> \
                <div class="rect5"></div> \
              </div>').appendTo(div);
}

function remove_spinner(spinner) {
    spinner.remove();
}


var speed = "10000";
var first = 0;
var pause = "60000";
setInterval(realtime_demand, pause);

function realtime_demand() {
    $.ajax({
        type: "GET", //傳值方式有分 post & get
        url: "/api/v1.0/demand_min", //第二筆用電折線圖
        dataType: 'json',
        success: function (response) {
            $('#real_demand > #total >span ').remove();
            $('#real_demand ').animate({}, speed).show(function () {
                total = '<span>' + response["demand_min"] + ' </span>';
                $('#real_demand > #total').append(total);
            });
        },
        error: function () {
            alert("no data");
        }
    });
}<file_sep>import datetime
import calendar
import time


def get_interval_of_day(today):
    today = datetime.datetime.strptime(today, '%Y-%m-%d')
    return (datetime.datetime.combine(today, datetime.time.min),
            datetime.datetime.combine(today, datetime.time.max))


def get_interval_of_month(today):
    today = datetime.datetime.strptime(today, '%Y-%m-%d')
    _, last_day_num = calendar.monthrange(today.year, today.month)
    first_date = datetime.date(today.year, today.month, 1)
    last_date = datetime.date(today.year, today.month, last_day_num)

    return (datetime.datetime.combine(first_date, datetime.time.min),
            datetime.datetime.combine(last_date, datetime.time.max))
<file_sep>from flask import jsonify, request
from sqlalchemy import func, and_, or_, between, exists
from . import api
from datetime import timedelta
from decimal import Decimal
import datetime
import math
import json
from .. import db
from ..models import Demand
from . import helper


@api.route('/demand', methods=['POST', 'GET'])
def demand_post():
    if request.method == 'POST':
        if request.is_json:
            req_json = request.get_json()
            print(type(req_json))
            insert_data = Demand(
                req_json['address'],
                req_json['channel'],
                req_json['model'],
                req_json['datetime'],
                req_json['demand_min']['value'],
                req_json['demand_quarter']['value'],
                req_json['instantaneous_power'][0]['value'],
                req_json['instantaneous_power'][1]['value'],
                req_json['instantaneous_power'][2]['value'],
                req_json['instantaneous_power'][3]['value'])
            db.session.add(insert_data)
            db.session.commit()

    return jsonify({"message": "feedback success"}), 201


'''
@api.route('/demand2', methods=['POST', 'GET'])
def demand_post():
    if request.method == 'POST':
        print(request.is_json)

        if request.is_json:
            print("json received.")
            req_json = request.get_json()
            print(req_json['instantaneous_power'][0]['tag'])
            insert_data = Demand(
                req_json['address'],
                req_json['channel'],
                req_json['model'],
                req_json['datetime'],
                req_json['demand_min']['value'],
                req_json['demand_quarter']['value'],
                req_json['instantaneous_power'][0]['value'],
                req_json['instantaneous_power'][1]['value'],
                req_json['instantaneous_power'][2]['value'],
                req_json['instantaneous_power'][3]['value'])
            db.session.add(insert_data)
            db.session.commit()

    return jsonify({"message": "feedback success"}), 201
'''


@api.route('/demand_min')
def demand_min():
    # Get the identification of the device
    req_address = request.args.get('address', default="0", type=str)
    req_channel = request.args.get('channel', default="0", type=str)

    # Try get data of the latest instantaneous power
    power_data = db.session.query(Demand.datetime, Demand.demand_min).filter(
        Demand.address == req_address,
        Demand.channel == req_channel).order_by(Demand.datetime.desc()).first()

    # Pack the result
    data_output = {}
    if power_data:
        data_output['time'] = power_data.datetime.strftime("%Y-%m-%d %H:%M:%S")
        data_output['demand_min'] = power_data.demand_min

    return jsonify(data_output), 201


@api.route('/peak_period_in_day')
def get_peak_period_in_day():
        # Get the identification of the device, and the time to check
    req_address = request.args.get('address', default="0", type=str)
    req_channel = request.args.get('channel', default="0", type=str)
    req_datetime = request.args.get('datetime',
                                    default=datetime.datetime.now().strftime("%Y-%m-%d"),
                                    type=str)

    req_interval = helper.get_interval_of_day(req_datetime)

    # Try get data of the latest instantaneous power
    power_data = db.session.query(Demand.datetime, Demand.demand_quarter).filter(
        Demand.address == req_address,
        Demand.channel == req_channel,
        func.SECOND(Demand.datetime) == 0,
        Demand.datetime.between(
            *req_interval)).order_by(Demand.demand_quarter.desc()).first()

    data_output = {}
    final_data_output = {}
    if power_data:
        data_output['time'] = power_data.datetime.strftime("%Y-%m-%d %H:%M:%S")
        data_output['peak_demand'] = power_data.demand_quarter
    final_data_output['peak'] = data_output
    date = power_data.datetime
    interval_start = date - timedelta(minutes=30)
    interval_end = date + timedelta(minutes=15)

    interval_power_data = db.session.query(Demand.datetime, Demand.Total_value).filter(
        Demand.address == req_address,
        Demand.channel == req_channel,
        Demand.datetime.between(interval_start, interval_end))

    # Pack the result

    final_data_output['demands'] = []
    for data in interval_power_data:
        final_data_output['demands'].append({'time': data.datetime.strftime("%Y-%m-%d %H:%M:%S"),
                                             'Value': data.Total_value})

    return jsonify(final_data_output), 201


@api.route('/peak_period_everyday_in_month')
def get_peak_period_everyday_in_month():
        # Get the identification of the device, and the time to check
    req_address = request.args.get('address', default="0", type=str)
    req_channel = request.args.get('channel', default="0", type=str)
    req_datetime = request.args.get('datetime',
                                    default=datetime.datetime.now().strftime("%Y-%m-%d"),
                                    type=str)

    req_interval = helper.get_interval_of_month(req_datetime)
    power_data = []
    data_output = []
    date = req_interval[0]
    # Try get data of the latest instantaneous power
    for i in range(req_interval[0].day, req_interval[1].day):
        interval_start = req_interval[0] + timedelta(hours=24 * i - 24)
        interval_end = req_interval[0] + timedelta(hours=24 * i)

        power_data = db.session.query(Demand.datetime, Demand.demand_quarter).filter(
            Demand.address == req_address,
            Demand.channel == req_channel,
            func.DAY(Demand.datetime) == interval_start.day,
            Demand.datetime.between(
                interval_start, interval_end)).order_by(Demand.demand_quarter.desc()).first()

    # Pack the result
        if(power_data):
            data_output.append({'time': power_data.datetime.strftime("%Y-%m-%d %H:%M:%S"),
                                'peak_demand': power_data.demand_quarter})

    return jsonify(data_output), 201


@api.route('/peak_periods_in_month')
def get_peak_periods_in_month():
    # Get the identification of the device, and the time to check
    req_address = request.args.get('address', default="0", type=str)
    req_channel = request.args.get('channel', default="0", type=str)
    req_datetime = request.args.get('datetime',
                                    default=datetime.datetime.now().strftime("%Y-%m-%d"),
                                    type=str)

    req_interval = helper.get_interval_of_month(req_datetime)

    # Try get data of the latest instantaneous power
    power_data = db.session.query(Demand.datetime, Demand.demand_quarter).filter(
        Demand.address == req_address,
        Demand.channel == req_channel,
        or_(
            func.MINUTE(Demand.datetime) == 0,
            func.MINUTE(Demand.datetime) == 15,
            func.MINUTE(Demand.datetime) == 30,
            func.MINUTE(Demand.datetime) == 45,
            func.MINUTE(Demand.datetime) == 60),
        func.SECOND(Demand.datetime) == 0,
        Demand.datetime.between(
            *req_interval)).order_by(Demand.demand_quarter.desc()).order_by(Demand.datetime).limit(3)

    # Pack the result
    data_output = []
    if power_data:
        for idx in range(power_data.count()):
            data_output.append(
                {'peak_demand': power_data[idx].demand_quarter,
                 'time': power_data[idx].datetime.strftime("%Y-%m-%d %H:%M:%S")})

    return jsonify(data_output), 201


@api.route('/peak_periods_in_month_interval')
def get_peak_periods_in_month_interval():
    # Get the identification of the device, and the time to check
    req_address = request.args.get('address', default="0", type=str)
    req_channel = request.args.get('channel', default="0", type=str)
    req_datetime = request.args.get('datetime',
                                    default=datetime.datetime.now().strftime("%Y-%m-%d"),
                                    type=str)

    req_interval = helper.get_interval_of_month(req_datetime)

    # Try get data of the latest instantaneous power
    power_data = db.session.query(Demand.datetime, Demand.demand_quarter).filter(
        Demand.address == req_address,
        Demand.channel == req_channel,
        or_(
            func.MINUTE(Demand.datetime) == 0,
            func.MINUTE(Demand.datetime) == 15,
            func.MINUTE(Demand.datetime) == 30,
            func.MINUTE(Demand.datetime) == 45,
            func.MINUTE(Demand.datetime) == 60),
        func.SECOND(Demand.datetime) == 0,
        Demand.datetime.between(
            *req_interval)).order_by(Demand.demand_quarter.desc()).order_by(Demand.datetime).limit(3)

    # Pack the result
    final_data_output = []
    if power_data:
        for idx in range(power_data.count()):
            data_output = {}
            data_output['peak'] = {'peak_demand': power_data[idx].demand_quarter,
                                   'time': power_data[idx].datetime.strftime("%Y-%m-%d %H:%M:%S")}

            date = power_data[idx].datetime

            interval_start = date - timedelta(minutes=30)
            interval_end = date + timedelta(minutes=15)

            interval_power_data = db.session.query(Demand.datetime, Demand.Total_value).filter(
                Demand.address == req_address,
                Demand.channel == req_channel,
                Demand.datetime.between(interval_start, interval_end))

            data_output['demands'] = []
            for data in interval_power_data:
                data_output['demands'].append(
                    {'time': data.datetime.strftime("%Y-%m-%d %H:%M:%S"),
                     'Value': data.Total_value})
            final_data_output.append(data_output)

    return jsonify(final_data_output), 201
<file_sep>/////////////////////////////////////////C3.js圖 未使用
function linebarchart() {
    var chart = c3.generate({
        bindto: '#linebarchart',


        data: {
            x: 'Time',
            xFormat: '%H:%M:%S', // how the date is parsed
            json: [{
                    Time: "00:15:00",
                    Peak_count: '12',
                    Average_Demand: '200',
                    Workday_count: '20',
                    Workday_Demand: '400'
                },
                {
                    Time: "00:30:00",
                    Peak_count: '15',
                    Average_Demand: '100',
                    Workday_count: '30',
                    Workday_Demand: '400'
                },
                {
                    Time: "00:45:00",
                    Peak_count: '20',
                    Average_Demand: '300',
                    Workday_count: '20',
                    Workday_Demand: '500'
                },
                {
                    Time: "01:00:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "01:15:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "01:30:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "01:45:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "02:00:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "02:15:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                },
                {
                    Time: "02:30:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "02:45:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "03:00:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "03:15:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "03:30:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "03:45:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }, {
                    Time: "04:00:00",
                    Peak_count: '28',
                    Average_Demand: '400',
                    Workday_count: '5',
                    Workday_Demand: '500'
                }
            ],
            keys: {
                //                x: 'name', // it's possible to specify 'x' when category axis
                x: 'Time',
                value: ['Peak_count', 'Average_Demand', 'Workday_count', 'Workday_Demand']
            },
            axes: {
                Average_Demand: 'y2',
                Workday_Demand: 'y2'
            },
            types: {
                Peak_count: 'bar',
                Workday_count: 'bar'
            }

        },
        bar: {
            width: {
                ratio: 0.9 // this makes bar width 50% of length between ticks
            }
            // or
            //width: 100 // this makes bar width 100px
        },
        title: {
            text: 'Peak_count-Demand Diagram'
        },
        tooltip: {
            grouped: false // Default true
        },
        axis: {
            x: {
                label: {
                    text: 'Time',
                    position: 'outer-center'
                },
                type: 'timeseries',
                tick: {
                    format: ' %H:%M:%S' // how the date is displayed
                }
            },
            y: {
                show: true,
                label: {
                    text: 'Peak_count',
                    position: 'outer-middle'
                },


            },
            y2: {
                show: true,
                label: {
                    text: 'kW',
                    position: 'outer-middle'
                }
            }
        }
    });
}<file_sep>from flask import render_template
from . import main


@main.route('/')
def index():
    return render_template('index.html')
@main.route('/chart-flot')
def chart_flot():
    return render_template('chart-flot.html')
@main.route('/chart-other')
def chart_other():
    return render_template('chart-other.html')
@main.route('/demand-analysis')
def demand_analysis():
    return render_template('demand-analysis.html')
