<commit_before>'use strict';

viewModel.AnalyticPerformanceIndex = {};
var page = viewModel.AnalyticPerformanceIndex;

vm.currentMenu('Performance Index');
vm.currentTitle('Performance Index');
vm.breadcrumb([{ title: "KPI's", href: '#' }, { title: 'Performance Index', href: viewModel.appName + 'page/analyticperformanceindex' }]);

var Data = {
    LoadData: function () {
        fa.LoadData();
        fa.getProjectInfo();
        app.loading(false);
        this.InitGrid();
    },
    InitGrid : function(){
        toolkit.ajaxPost(viewModel.appName + "analyticlossanalysis/getavaildate", {}, function (res) {
            var minDatetemp = new Date(res.ScadaData[0]);
            var maxDatetemp = new Date(res.ScadaData[1]);
            $('#availabledatestartscada').html(kendo.toString(moment.utc(minDatetemp).format('DD-MMMM-YYYY')));
            $('#availabledateendscada').html(kendo.toString(moment.utc(maxDatetemp).format('DD-MMMM-YYYY')));
        })

        var param = {
            period: fa.period,
            dateStart: fa.dateStart,
            dateEnd: fa.dateEnd,
            turbine: fa.turbine,
            project: fa.project
        };

        $("#performance-grid").html("");
        $("#performance-grid").kendoGrid({
            dataSource: {
                serverSorting: true,
                serverFiltering: true,
                transport: {
                    read: {
                        url: viewModel.appName + "analyticperformanceindex/getperformanceindex",
                        type: "POST",
                        data: param,
                        dataType: "json",
                        contentType: "application/json; charset=utf-8"
                    },
                    parameterMap: function(options) {
                        return JSON.stringify(options);
                    }
                },
                pageSize: 10,
                schema: {
                    data: function(res) {
                        app.loading(false);
                        if (!app.isFine(res)) {
                            return;
                        }
                        return res.data.Data
                    },
                    total: function (res) {
                        if (!app.isFine(res)) {
                            return;
                        }
                        return res.data.Data.length;
                    }
                },
            },
            scrollable: true,
            sortable: true,
            pageable: true,
            height        : 550,
            detailInit : Data.InitGridDetail,
            dataBound: function () {
                this.expandRow(this.tbody.find("tr.k-master-row").first());
            },
            columns       : [
                { field: "Project", title: "Name", width: 110,headerAttributes: { style: "text-align: center" },attributes: { style: "padding-left: 20px;border-right:1px solid rgba(128, 128, 128, 0.26)" }},
                {
                    title: "Performance
"+kendo.toString(moment.utc(fa.dateStart).format('DD-MM-YYYY '))+" to " + kendo.toString(moment.utc(fa.dateEnd).format('DD-MM-YYYY')) ,
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndex", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPower", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "Power", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "Last 24 Hours",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexLast24Hours", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" }, format: "{0:n2}"},
                        { field: "PotentialPowerLast24Hours", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerLast24Hours", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "Last Week",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexLastWeek", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerLastWeek", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerLastWeek", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "MTD",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexMTD", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerMTD", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerMTD", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "YTD",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexYTD", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerYTD", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerYTD", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
            ]
        });
    },
    InitGridDetail: function (e) {
        $("
").appendTo(e.detailCell).kendoGrid({
            selectable: "multiple",
            dataSource: {
                data: e.data.Details,
                sort: [
                    { field: 'Turbine', dir: 'asc' }
                ],
                 // pageSize: 10,
            },
            scrollable: false,
            sortable: false,
            pageable: false,
             columns       : [
                { field: "Turbine", title: "Name", width: 100,headerAttributes: { style: "text-align: center" },attributes: { style: "padding-left: 30px;border-right:1px solid rgba(128, 128, 128, 0.26)" }},
                {
                    title: "Performance",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndex", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPower", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "Power", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "Last 24 Hours",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexLast24Hours", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center"}, format: "{0:n2}"},
                        { field: "PotentialPowerLast24Hours", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerLast24Hours", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "Last Week",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexLastWeek", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerLastWeek", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerLastWeek", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "MTD",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexMTD", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerMTD", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerMTD", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "YTD",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexYTD", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerYTD", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerYTD", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
            ]
        });
        $(".k-grid tbody .k-grid .k-grid-header").hide();
    },
}

$(function(){
    $('#btnRefresh').on('click', function () {
        Data.LoadData();
    });
    setTimeout(function(){
        Data.LoadData();
    },100);

})  <commit_msg>create something intelijen<commit_after>'use strict';

viewModel.AnalyticPerformanceIndex = {};
var page = viewModel.AnalyticPerformanceIndex;

vm.currentMenu('Performance Index');
vm.currentTitle('Performance Index');
vm.breadcrumb([{ title: "KPI's", href: '#' }, { title: 'Performance Index', href: viewModel.appName + 'page/analyticperformanceindex' }]);

var Data = {
    LoadData: function () {
        fa.LoadData();
        fa.getProjectInfo();
        app.loading(false);
        this.InitGrid();
    },
    InitGrid : function(){
        toolkit.ajaxPost(viewModel.appName + "analyticlossanalysis/getavaildate", {}, function (res) {
            var minDatetemp = new Date(res.ScadaData[0]);
            var maxDatetemp = new Date(res.ScadaData[1]);
            $('#availabledatestartscada').html(kendo.toString(moment.utc(minDatetemp).format('DD-MMMM-YYYY')));
            $('#availabledateendscada').html(kendo.toString(moment.utc(maxDatetemp).format('DD-MMMM-YYYY')));
        })
        var hideLast24 = false;
        var hideLastWeek = false;
        var hideMTD = false;
        var hideYTD = false;
        var maxDateData = new Date(app.getUTCDate(app.currentDateData));
        var maxDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));
        var last24hours = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate() - 1, 0, 0, 0, 0));
        var lastweek = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate() - 7, 0, 0, 0, 0));
        var startMonthDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), 1, 0, 0, 0, 0));
        var startYearDate = new Date(Date.UTC(moment(maxDateData).get('year'), 0, 1, 0, 0, 0, 0));

        if(fa.dateStart.getTime() === last24hours.getTime() && fa.dateEnd.getTime() === maxDate.getTime()) {
            hideLast24 = true;
        } else if(fa.dateStart.getTime() === lastweek.getTime() && fa.dateEnd.getTime() === maxDate.getTime()) {
            hideLastWeek = true;
        } else if(fa.dateStart.getTime() === startMonthDate.getTime() && fa.dateEnd.getTime() === maxDate.getTime()) {
            hideMTD = true;
        } else if(fa.dateStart.getTime() === startYearDate.getTime() && fa.dateEnd.getTime() === maxDate.getTime()) {
            hideYTD = true;
        }

        var param = {
            period: fa.period,
            dateStart: fa.dateStart,
            dateEnd: fa.dateEnd,
            turbine: fa.turbine,
            project: fa.project
        };

        $("#performance-grid").html("");
        $("#performance-grid").kendoGrid({
            dataSource: {
                serverSorting: true,
                serverFiltering: true,
                transport: {
                    read: {
                        url: viewModel.appName + "analyticperformanceindex/getperformanceindex",
                        type: "POST",
                        data: param,
                        dataType: "json",
                        contentType: "application/json; charset=utf-8"
                    },
                    parameterMap: function(options) {
                        return JSON.stringify(options);
                    }
                },
                pageSize: 10,
                schema: {
                    data: function(res) {
                        app.loading(false);
                        if (!app.isFine(res)) {
                            return;
                        }
                        return res.data.Data
                    },
                    total: function (res) {
                        if (!app.isFine(res)) {
                            return;
                        }
                        return res.data.Data.length;
                    }
                },
            },
            scrollable: true,
            sortable: true,
            pageable: true,
            height        : 550,
            detailInit : Data.InitGridDetail,
            dataBound: function () {
                this.expandRow(this.tbody.find("tr.k-master-row").first());
            },
            columns       : [
                { field: "Project", title: "Name", width: 110,headerAttributes: { style: "text-align: center" },attributes: { style: "padding-left: 20px;border-right:1px solid rgba(128, 128, 128, 0.26)" }},
                {
                    title: "Performance
"+kendo.toString(moment.utc(fa.dateStart).format('DD-MM-YYYY '))+" to " + kendo.toString(moment.utc(fa.dateEnd).format('DD-MM-YYYY')) ,
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndex", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPower", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "Power", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "Last 24 Hours",
                    hidden: hideLast24,
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexLast24Hours", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" }, format: "{0:n2}"},
                        { field: "PotentialPowerLast24Hours", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerLast24Hours", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "Last Week",
                    hidden: hideLastWeek,
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexLastWeek", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerLastWeek", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerLastWeek", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "MTD",
                    hidden: hideMTD,
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexMTD", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerMTD", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerMTD", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "YTD",
                    hidden: hideYTD,
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexYTD", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerYTD", title: "Potential Power
(MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerYTD", title: "Actual Power
 (MW)", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
            ]
        });
    },
    InitGridDetail: function (e) {
        $("
").appendTo(e.detailCell).kendoGrid({
            selectable: "multiple",
            dataSource: {
                data: e.data.Details,
                sort: [
                    { field: 'Turbine', dir: 'asc' }
                ],
                 // pageSize: 10,
            },
            scrollable: false,
            sortable: false,
            pageable: false,
             columns       : [
                { field: "Turbine", title: "Name", width: 100,headerAttributes: { style: "text-align: center" },attributes: { style: "padding-left: 30px;border-right:1px solid rgba(128, 128, 128, 0.26)" }},
                {
                    title: "Performance",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndex", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPower", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "Power", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "Last 24 Hours",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexLast24Hours", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center"}, format: "{0:n2}"},
                        { field: "PotentialPowerLast24Hours", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerLast24Hours", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "Last Week",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexLastWeek", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerLastWeek", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerLastWeek", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "MTD",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexMTD", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerMTD", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerMTD", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
                {
                    title: "YTD",
                    headerAttributes: { style: 'font-weight: bold; text-align: center;' },
                    columns: [
                        { field: "PerformanceIndexYTD", title: "PI", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PotentialPowerYTD", title: "Potential Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center" },format: "{0:n2}"},
                        { field: "PowerYTD", title: "Actual Power", width: 100,headerAttributes: { style: "text-align: center" },attributes:{ style: "text-align: center;border-right:1px solid rgba(128, 128, 128, 0.26)" },format: "{0:n2}"},
                    ]
                },
            ]
        });
        $(".k-grid tbody .k-grid .k-grid-header").hide();
    },
}

$(function(){
    $('#btnRefresh').on('click', function () {
        Data.LoadData();
    });
    setTimeout(function(){
        Data.LoadData();
    },100);

})  <|endoftext|>


<commit_before>import resolver from './helpers/resolver';
import {
  setResolver
} from 'ember-qunit';
import { start } from 'ember-cli-qunit';

setResolver(resolver);
start();
<commit_msg>fix deprecation on test import<commit_after>import resolver from './helpers/resolver';
import { setResolver } from '@ember/test-helpers';
import { start } from 'ember-cli-qunit';

setResolver(resolver);
start();
<|endoftext|>


<commit_before>Ti.include('httpclient.js');
Ti.include('workitemCell.js');

var win = Ti.UI.currentWindow;
var tab = Ti.UI.currentWindow.tabGroup.tabs[1];
var emptyRow = WorkitemCell.createMessageCell('オファーされているタスクはありません');

var reloadButton = Ti.UI.createButton({
	systemButton : Ti.UI.iPhone.SystemButton.REFRESH
});
var tableView = Ti.UI.createTableView();
var activityIndicator = Titanium.UI.createActivityIndicator({
	style: Titanium.UI.iPhone.ActivityIndicatorStyle.BIG
});
var workitems = [];

function updateTable(client) {
	var o = JSON.parse(client.responseText);
	workitems = o.workitems || [];
	workitems.sort(function(a, b) { /* 日付逆順 */
		if (a.offerDatetime < b.offerDatetime) {
			return 1;
		}
		if (a.offerDatetime > b.offerDatetime) {
			return -1;
		}
		return 0;
	});
	var data = [];
	for ( var i = 0; i < workitems.length; i++) {
		var row = WorkitemCell.createWorkitemCell(workitems[i]);
		data.push(row);
	}
	tab.setBadge(workitems.length > 0 ? workitems.length : null);
	if(workitems.length == 0) {
		data.push(emptyRow);
	}
	tableView.setData(data);
}

function update() {
	var contextRoot = Ti.App.Properties.getString('url');
	HttpClient.send({
		url : contextRoot + 'API/PE/Workitem/listOffered',
		parameters : [],
		success : updateTable
	});
}

reloadButton.addEventListener('click', update);
Ti.UI.currentWindow.rightNavButton = reloadButton;

win.addEventListener('focus', function(){
	if(workitems == null) {
		update();
	}
})

/** 状態のクリア。認証設定を変えたときに呼び出す */
function clear() {
	tab.setBadge(null);
	workitems = null;
	tableView.setData([]);
}
Ti.App.addEventListener('clearAuth', clear);

/**
 * タスク引き受け処理
 * @param workitemId
 */
function accept(workitemId) {
	Ti.API.debug("accept: " + workitemId);
	activityIndicator.show();
	var contextRoot = Ti.App.Properties.getString('url');
	HttpClient.send({
		url : contextRoot + 'API/PE/Workitem/batchAccept',
		parameters : [ [ 'workitemIds', workitemId ] ],
		success : update,
		indicator : activityIndicator
	});
}

/**
 * タスク選択時の処理
 */
tableView.addEventListener('click', function(e) {
	var options = [];
	options.push('引き受ける');
	options.push('キャンセル');
	dialog = Ti.UI.createOptionDialog({
		options : options,
		cancel : 1
	});
	var acceptWorkitemId = workitems[e.index].id;
	dialog.addEventListener('click', function(e) {
		if (e.cancel == e.index) {
			return;
		} else {
			accept(acceptWorkitemId);
		}
	});
	dialog.show();
});

win.add(tableView);
win.add(activityIndicator);
update();
<commit_msg>オファー引き受け時に Activity Indicator が消えない問題を修正<commit_after>Ti.include('httpclient.js');
Ti.include('workitemCell.js');

var win = Ti.UI.currentWindow;
var tab = Ti.UI.currentWindow.tabGroup.tabs[1];
var emptyRow = WorkitemCell.createMessageCell('オファーされているタスクはありません');

var reloadButton = Ti.UI.createButton({
	systemButton : Ti.UI.iPhone.SystemButton.REFRESH
});
var tableView = Ti.UI.createTableView();
var activityIndicator = Titanium.UI.createActivityIndicator({
	style: Titanium.UI.iPhone.ActivityIndicatorStyle.DARK
});
var workitems = [];

function updateTable(client) {
	var o = JSON.parse(client.responseText);
	workitems = o.workitems || [];
	workitems.sort(function(a, b) { /* 日付逆順 */
		if (a.offerDatetime < b.offerDatetime) {
			return 1;
		}
		if (a.offerDatetime > b.offerDatetime) {
			return -1;
		}
		return 0;
	});
	var data = [];
	for ( var i = 0; i < workitems.length; i++) {
		var row = WorkitemCell.createWorkitemCell(workitems[i]);
		data.push(row);
	}
	tab.setBadge(workitems.length > 0 ? workitems.length : null);
	if(workitems.length == 0) {
		data.push(emptyRow);
	}
	tableView.setData(data);
	activityIndicator.hide();
}

function update() {
	var contextRoot = Ti.App.Properties.getString('url');
	HttpClient.send({
		url : contextRoot + 'API/PE/Workitem/listOffered',
		parameters : [],
		success : updateTable
	});
}

reloadButton.addEventListener('click', update);
Ti.UI.currentWindow.rightNavButton = reloadButton;

win.addEventListener('focus', function(){
	if(workitems == null) {
		update();
	}
})

/** 状態のクリア。認証設定を変えたときに呼び出す */
function clear() {
	tab.setBadge(null);
	workitems = null;
	tableView.setData([]);
}
Ti.App.addEventListener('clearAuth', clear);

/**
 * タスク引き受け処理
 * @param workitemId
 */
function accept(workitemId) {
	Ti.API.debug("accept: " + workitemId);
	activityIndicator.show();
	var contextRoot = Ti.App.Properties.getString('url');
	HttpClient.send({
		url : contextRoot + 'API/PE/Workitem/batchAccept',
		parameters : [ [ 'workitemIds', workitemId ] ],
		success : update,
		indicator : activityIndicator
	});
}

/**
 * タスク選択時の処理
 */
tableView.addEventListener('click', function(e) {
	var options = [];
	options.push('引き受ける');
	options.push('キャンセル');
	dialog = Ti.UI.createOptionDialog({
		options : options,
		cancel : 1
	});
	var acceptWorkitemId = workitems[e.index].id;
	dialog.addEventListener('click', function(e) {
		if (e.cancel == e.index) {
			return;
		} else {
			accept(acceptWorkitemId);
		}
	});
	dialog.show();
});

win.add(tableView);
win.add(activityIndicator);
update();
<|endoftext|>


<commit_before>'use strict';

window.moment = require('moment');
window.jQuery = require('jquery');
window.$ = window.jQuery;
require('fullcalendar');
require('fullcalendar/dist/lang-all.js')

var angular = require('angular');
// angular modules
require('angular-ui-router');
require('angular-aria');
require('angular-animate');
require('angular-touch');
require('angular-bootstrap-npm');
require('angular-translate');
require('angular-chart.js');
require('angular-ui-calendar');
require('angular-resource');
require('angular-scroll');
require('angular-social-links');
require('./ext/imgLiquid');
require('./templates');
require('./controllers/_index');
require('./services/_index');
require('./directives/_index');
require('./filters/_index');
require('./lb-services.js');

// create and bootstrap application
angular.element(document).ready(function() {

  var requires = [
    'ui.router',
    'templates',
    'app.controllers',
    'app.services',
    'app.directives',
    'app.filters',
    'ngTouch',
    'ui.bootstrap',
    'pascalprecht.translate',
    'chart.js',
    'ui.calendar',
    'ngResource',
    'lbServices',
    'duScroll',
    'socialLinks',
    'ngAnimate'
  ];

  // mount on window for testing
  window.app = angular.module('app', requires)
    .constant('AppSettings', require('./constants'))
    .config(require('./routes'))
    .config(require('./translations'))
    .run(require('./on_run'));

  angular.bootstrap(document, ['app']);
});
<commit_msg>Add the ngAria module<commit_after>'use strict';

window.moment = require('moment');
window.jQuery = require('jquery');
window.$ = window.jQuery;
require('fullcalendar');
require('fullcalendar/dist/lang-all.js')

var angular = require('angular');
// angular modules
require('angular-ui-router');
require('angular-aria');
require('angular-animate');
require('angular-touch');
require('angular-bootstrap-npm');
require('angular-translate');
require('angular-chart.js');
require('angular-ui-calendar');
require('angular-resource');
require('angular-scroll');
require('angular-social-links');
require('./ext/imgLiquid');
require('./templates');
require('./controllers/_index');
require('./services/_index');
require('./directives/_index');
require('./filters/_index');
require('./lb-services.js');

// create and bootstrap application
angular.element(document).ready(function() {

  var requires = [
    'ui.router',
    'templates',
    'app.controllers',
    'app.services',
    'app.directives',
    'app.filters',
    'ngTouch',
    'ui.bootstrap',
    'pascalprecht.translate',
    'chart.js',
    'ui.calendar',
    'ngResource',
    'lbServices',
    'duScroll',
    'socialLinks',
    'ngAnimate',
    'ngAria'
  ];

  // mount on window for testing
  window.app = angular.module('app', requires)
    .constant('AppSettings', require('./constants'))
    .config(require('./routes'))
    .config(require('./translations'))
    .run(require('./on_run'));

  angular.bootstrap(document, ['app']);
});
<|endoftext|>


<commit_before>$.fn.parallaxize = (function (global, $) {
    'use strict';

    function Parallax() {
        this.init.apply(this, Array.prototype.slice.call(arguments));
    }

    Parallax.prototype = {
        init: function (parent, settings) {
            this.initializeConfig(settings);
            this.config('element', parent);
            this.config('width', 1);
            this.config('height', 1);

            this.initializeDOM();
            this.initializeBindings();
        },

        initializeConfig: function (settings) {
            var config = {};
            settings = $.fn.extend({variation: 20}, settings);

            var getGetter = function (object) {
                return function (key, value) {
                    if (typeof key === 'undefined') {
                        return object;
                    }
                    if (typeof value === 'undefined') {
                        return object[key];
                    }
                    return object[key] = value;
                }
            };

            this.config = getGetter(config);
            this.setting = getGetter(settings);
        },

        initializeDOM: function () {
            var elem = this.config('element'),
                image = new Image(),
                image_elem = $(image),
                me = this;
            elem.prepend(image_elem);
            image_elem.hide();

            var synchronous = true;
            image.onload = function () {
                me.config('height', image_elem.height());
                me.config('width', image_elem.width());
                me.translate(false);

                if (synchronous) {
                    image_elem.show();
                } else {
                    image_elem.fadeIn(250);
                }
            };
            image.src = elem.data('background-image');
            setTimeout(function () {
                synchronous = false;
            }, 150);
            this.config('image', image_elem);

            elem.addClass('parallaxic-container');
            image_elem.addClass('parallaxic-image');

        },

        initializeBindings: function () {
            var me = this;
            $(global).scroll(function () {
                me.translate();
            });

            $(global).resize(function () {
                me.translate(false);
            });
        },

        translate: function (cache) {
            var transform = [
                this.resizeTranslation(cache),
                this.positionTranslation()
            ].join(' ');

            this.config('image').css({
                transform: transform,
                '-webkit-transform': transform,
                '-moz-transform': transform,
                '-o-transform': transform
            });
        },

        resizeTranslation: function (cached) {
            var scale;
            if (cached !== false) {
                scale = this.config('scale');
                if (scale) {
                    return 'scale(' + scale + ')';
                }
            }

            var variation = this.setting('variation'),
                elem = this.config('element'),
                image = this.config('image'),
                height = elem.height(),
                image_height = this.config('height'), image_width = this.config('width'),
                potential_height = height + variation * 2,
                new_width = elem.width(), new_height;

            new_height = (image_height / image_width) * new_width;

            if (new_height < potential_height) {
                new_height = potential_height;
                new_width = (image_width / image_height) * new_height;
            }

            scale = Math.ceil(new_height / image_height * 1000) / 1000;

            //if (Modernizr && !Modernizr.csstransforms) {
            //    image.css({
            //        width: new_width,
            //        height: new_height
            //    });
            //    return '';
            //}

            this.config('scale', scale);
            return 'scale(' + scale + ')';
        },

        positionTranslation: function () {

            var variation = this.setting('variation'),
                elem = this.config('element'),
                image = this.config('image'),
                height = elem.height(), width = elem.width(),
                image_height = this.config('height'), image_width = this.config('width'),
                top = (height - image_height) / 2,
                left = (width - image_width) / 2,
                scroll_percentage = this.getScrollPercentage();

            top += (variation * 2 * scroll_percentage) - variation;

            // First assume translate
            //var method_start = 'translate(', method_end = ')';
            //
            //if (Modernizr) {
            //    if (Modernizr.csstransforms3d) {
            //        method_start = 'translate3d(';
            //        method_end = ', 0px)';
            //    } else if (!Modernizr.csstransforms) {
            //        return '';
            //    }
            //}
            //return method_start + Math.round(left) + 'px, ' + Math.round(top) + 'px' + method_end;

            return ['translate3d(', Math.round(left), 'px, ', Math.round(top), 'px, ', '0px)'].join('');
        },

        getScrollPercentage: function () {
            var elem = this.config('element'),
                image = this.config('image'),
                main = $(global),
                min = elem.offset().top - main.height(),
                max = elem.offset().top + elem.height() - min,
                scroll = main.scrollTop() - min;

            return Math.max(0, Math.min(1, scroll / max));
        }

    };

    return function (settings) {
        this.data('parallax', new Parallax(this, settings))
    };

}(window, $));
<commit_msg>:bug: fix(browser): Adjust the parallax JS to respect scale when calculating left shift Scale was not being taken into account (since I assumed that scaling would adjust the images initial x/y coordinate, [this doesn't look to be the case](http://jsfiddle.net/rhj0kL8L/) as browsers keep the same bounding box and simply scale at the rendering level. To fix this, we simply adjust the offset by the inverse scale.<commit_after>$.fn.parallaxize = (function (global, $) {
    'use strict';

    function Parallax() {
        this.init.apply(this, Array.prototype.slice.call(arguments));
    }

    Parallax.prototype = {
        init: function (parent, settings) {
            this.initializeConfig(settings);
            this.config('element', parent);
            this.config('width', 1);
            this.config('height', 1);

            this.initializeDOM();
            this.initializeBindings();
        },

        initializeConfig: function (settings) {
            var config = {};
            settings = $.fn.extend({variation: 20}, settings);

            var getGetter = function (object) {
                return function (key, value) {
                    if (typeof key === 'undefined') {
                        return object;
                    }
                    if (typeof value === 'undefined') {
                        return object[key];
                    }
                    return object[key] = value;
                }
            };

            this.config = getGetter(config);
            this.setting = getGetter(settings);
        },

        initializeDOM: function () {
            var elem = this.config('element'),
                image = new Image(),
                image_elem = $(image),
                me = this;
            elem.prepend(image_elem);
            image_elem.hide();

            var synchronous = true;
            image.onload = function () {
                me.config('height', image_elem.height());
                me.config('width', image_elem.width());
                me.translate(false);

                if (synchronous) {
                    image_elem.show();
                } else {
                    image_elem.fadeIn(250);
                }
            };
            image.src = elem.data('background-image');
            setTimeout(function () {
                synchronous = false;
            }, 150);
            this.config('image', image_elem);

            elem.addClass('parallaxic-container');
            image_elem.addClass('parallaxic-image');

        },

        initializeBindings: function () {
            var me = this;
            $(global).scroll(function () {
                me.translate();
            });

            $(global).resize(function () {
                me.translate(false);
            });
        },

        translate: function (cache) {
            var transform = [
                this.resizeTranslation(cache),
                this.positionTranslation()
            ].join(' ');

            this.config('image').css({
                transform: transform,
                '-webkit-transform': transform,
                '-moz-transform': transform,
                '-o-transform': transform
            });
        },

        resizeTranslation: function (cached) {
            var scale;
            if (cached !== false) {
                scale = this.config('scale');
                if (scale) {
                    return 'scale(' + scale + ')';
                }
            }

            var variation = this.setting('variation'),
                elem = this.config('element'),
                image = this.config('image'),
                height = elem.height(),
                image_height = this.config('height'), image_width = this.config('width'),
                potential_height = height + variation * 2,
                new_width = elem.width(), new_height;

            new_height = (image_height / image_width) * new_width;

            if (new_height < potential_height) {
                new_height = potential_height;
                new_width = (image_width / image_height) * new_height;
            }

            scale = Math.ceil(new_height / image_height * 1000) / 1000;

            //if (Modernizr && !Modernizr.csstransforms) {
            //    image.css({
            //        width: new_width,
            //        height: new_height
            //    });
            //    return '';
            //}

            this.config('scale', scale);
            return 'scale(' + scale + ')';
        },

        positionTranslation: function () {

            var variation = this.setting('variation'),
                scale = this.config('scale'),
                elem = this.config('element'),
                image = this.config('image'),
                height = elem.height(), width = elem.width(),
                image_height = this.config('height'), image_width = this.config('width'),
                top = (height - image_height) / 2,
                left = (width - image_width) / 2,
                scroll_percentage = this.getScrollPercentage();

            top += (variation * 2 * scroll_percentage) - variation;

            // First assume translate
            //var method_start = 'translate(', method_end = ')';
            //
            //if (Modernizr) {
            //    if (Modernizr.csstransforms3d) {
            //        method_start = 'translate3d(';
            //        method_end = ', 0px)';
            //    } else if (!Modernizr.csstransforms) {
            //        return '';
            //    }
            //}
            //return method_start + Math.round(left) + 'px, ' + Math.round(top) + 'px' + method_end;

            return ['translate3d(', Math.round(left / scale), 'px, ', Math.round(top), 'px, ', '0px)'].join('');
        },

        getScrollPercentage: function () {
            var elem = this.config('element'),
                image = this.config('image'),
                main = $(global),
                min = elem.offset().top - main.height(),
                max = elem.offset().top + elem.height() - min,
                scroll = main.scrollTop() - min;

            return Math.max(0, Math.min(1, scroll / max));
        }

    };

    return function (settings) {
        this.data('parallax', new Parallax(this, settings))
    };

}(window, $));
<|endoftext|>


<commit_before>/*
 * grunt-contrib-mincss
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Tim Branyen, contributors
 * Licensed under the MIT license.
 * https://github.com/gruntjs/grunt-contrib-mincss/blob/master/LICENSE-MIT
 */

module.exports = function(grunt) {
  'use strict';

  grunt.registerMultiTask('mincss', 'Minify CSS files', function() {
    var helpers = require('grunt-contrib-lib').init(grunt);
    var options = helpers.options(this);

    grunt.verbose.writeflags(options, 'Options');

    // TODO: ditch this when grunt v0.4 is released
    this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);

    var srcFiles;
    var taskOutputMin;
    var taskOutputMax;
    var sourceCode;
    var sourceCompressed;

    this.files.forEach(function(file) {
      srcFiles = grunt.file.expandFiles(file.src);

      taskOutputMin = [];
      taskOutputMax = [];

      srcFiles.forEach(function(srcFile) {
        sourceCode = grunt.file.read(srcFile);
        sourceCompressed = minifyCSS(sourceCode);

        taskOutputMin.push(sourceCompressed);
        taskOutputMax.push(sourceCode);
      });

      if (taskOutputMin.length > 0) {
        taskOutputMin = taskOutputMin.join('');
        taskOutputMax = taskOutputMax.join('');

        grunt.file.write(file.dest, taskOutputMin);
        grunt.log.writeln('File ' + file.dest + ' created.');

        minMaxInfo(taskOutputMin, taskOutputMax);
      }
    });
  });

  var minifyCSS = function(source) {
    try {
      return require('clean-css').process(source);
    } catch (e) {
      grunt.log.error(e);
      grunt.fail.warn('css minification failed.');
    }
  };

  var minMaxGzip = function(src) {
    return src ? require('gzip-js').zip(src, {}) : '';
  };

  var minMaxInfo = function(min, max) {
    var gzipSize = String(minMaxGzip(min).length);
    grunt.log.writeln('Uncompressed size: ' + String(max.length).green + ' bytes.');
    grunt.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + String(min.length).green + ' bytes minified).');
  };
};<commit_msg>quick tweak to last commit.<commit_after>/*
 * grunt-contrib-mincss
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Tim Branyen, contributors
 * Licensed under the MIT license.
 * https://github.com/gruntjs/grunt-contrib-mincss/blob/master/LICENSE-MIT
 */

module.exports = function(grunt) {
  'use strict';

  grunt.registerMultiTask('mincss', 'Minify CSS files', function() {
    var helpers = require('grunt-contrib-lib').init(grunt);
    var options = helpers.options(this);

    grunt.verbose.writeflags(options, 'Options');

    // TODO: ditch this when grunt v0.4 is released
    this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);

    var srcFiles;
    var taskOutputMin;
    var taskOutputMax;
    var sourceCode;
    var sourceCompressed;

    this.files.forEach(function(file) {
      srcFiles = grunt.file.expandFiles(file.src);

      taskOutputMin = [];
      taskOutputMax = [];

      srcFiles.forEach(function(srcFile) {
        sourceCode = grunt.file.read(srcFile);
        sourceCompressed = minifyCSS(sourceCode);

        taskOutputMin.push(sourceCompressed);
        taskOutputMax.push(sourceCode);
      });

      if (taskOutputMin.length > 0) {
        taskOutputMin = taskOutputMin.join('');
        taskOutputMax = taskOutputMax.join('\n');

        grunt.file.write(file.dest, taskOutputMin);
        grunt.log.writeln('File ' + file.dest + ' created.');

        minMaxInfo(taskOutputMin, taskOutputMax);
      }
    });
  });

  var minifyCSS = function(source) {
    try {
      return require('clean-css').process(source);
    } catch (e) {
      grunt.log.error(e);
      grunt.fail.warn('css minification failed.');
    }
  };

  var minMaxGzip = function(src) {
    return src ? require('gzip-js').zip(src, {}) : '';
  };

  var minMaxInfo = function(min, max) {
    var gzipSize = String(minMaxGzip(min).length);
    grunt.log.writeln('Uncompressed size: ' + String(max.length).green + ' bytes.');
    grunt.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + String(min.length).green + ' bytes minified).');
  };
};<|endoftext|>


<commit_before>OV.FinalizeModel = function (model, getDefaultMaterial)
{
    function FinalizeMesh (model, mesh, getDefaultMaterialIndex)
    {
        function CalculateCurveNormals (mesh)
        {
            function AddAverageNormal (mesh, triangle, vertexIndex, triangleNormals, vertexToTriangles)
            {
                function IsNormalInArray (array, normal)
                {
                    for (let i = 0; i < array.length; i++) {
                        let current = array[i];
                        if (OV.CoordIsEqual3D (current, normal)) {
                            return true;
                        }
                    }
                    return false;
                }

                let averageNormals = [];
                let neigTriangles = vertexToTriangles[vertexIndex];
                for (let i = 0; i < neigTriangles.length; i++) {
                    let neigIndex = neigTriangles[i];
                    let neigTriangle = mesh.GetTriangle (neigIndex);
                    if (triangle.curve === neigTriangle.curve) {
                        let triangleNormal = triangleNormals[neigIndex];
                        if (!IsNormalInArray (averageNormals, triangleNormal)) {
                            averageNormals.push (triangleNormal);
                        }
                    }
                }

                let averageNormal = new OV.Coord3D (0.0, 0.0, 0.0);
                for (let i = 0; i < averageNormals.length; i++) {
                    averageNormal = OV.AddCoord3D (averageNormal, averageNormals[i]);
                }
                averageNormal.MultiplyScalar (1.0 / averageNormals.length);
                averageNormal.Normalize ();
                return mesh.AddNormal (averageNormal);
            }

            let triangleNormals = [];
            let vertexToTriangles = {};

            for (let vertexIndex = 0; vertexIndex < mesh.VertexCount (); vertexIndex++) {
                vertexToTriangles[vertexIndex] = [];
            }

            for (let triangleIndex = 0; triangleIndex < mesh.TriangleCount (); triangleIndex++) {
                let triangle = mesh.GetTriangle (triangleIndex);
                let v0 = mesh.GetVertex (triangle.v0);
                let v1 = mesh.GetVertex (triangle.v1);
                let v2 = mesh.GetVertex (triangle.v2);
                let normal = OV.CalculateTriangleNormal (v0, v1, v2);
                triangleNormals.push (normal);
                vertexToTriangles[triangle.v0].push (triangleIndex);
                vertexToTriangles[triangle.v1].push (triangleIndex);
                vertexToTriangles[triangle.v2].push (triangleIndex);
            }

            for (let triangleIndex = 0; triangleIndex < mesh.TriangleCount (); triangleIndex++) {
                let triangle = mesh.GetTriangle (triangleIndex);
                if (!triangle.HasNormals ()) {
                    let n0 = AddAverageNormal (mesh, triangle, triangle.v0, triangleNormals, vertexToTriangles);
                    let n1 = AddAverageNormal (mesh, triangle, triangle.v1, triangleNormals, vertexToTriangles);
                    let n2 = AddAverageNormal (mesh, triangle, triangle.v2, triangleNormals, vertexToTriangles);
                    triangle.SetNormals (n0, n1, n2);
                }
            }
        }

        function FinalizeTriangle (mesh, triangle, status)
        {
            if (!triangle.HasNormals ()) {
                if (triangle.curve === null || triangle.curve === 0) {
                    let v0 = mesh.GetVertex (triangle.v0);
                    let v1 = mesh.GetVertex (triangle.v1);
                    let v2 = mesh.GetVertex (triangle.v2);
                    let normal = OV.CalculateTriangleNormal (v0, v1, v2);
                    let normalIndex = mesh.AddNormal (normal);
                    triangle.SetNormals (normalIndex, normalIndex, normalIndex);
                } else {
                    status.calculateCurveNormals = true;
                }
            }
            if (triangle.mat === null) {
                triangle.mat = status.getDefaultMaterialIndex ();
            }
            if (triangle.curve === null) {
                triangle.curve = 0;
            }
        }

        let status = {
            getDefaultMaterialIndex : getDefaultMaterialIndex,
            calculateCurveNormals : false
        };

        for (let i = 0; i < mesh.TriangleCount (); i++) {
            let triangle = mesh.GetTriangle (i);
            FinalizeTriangle (mesh, triangle, status);
        }

        if (status.calculateCurveNormals) {
            CalculateCurveNormals (mesh);
        }

        let hasVertexColors = (mesh.VertexCount () === mesh.VertexColorCount ());
        if (hasVertexColors) {
            for (let i = 0; i < mesh.TriangleCount (); i++) {
                let triangle = mesh.GetTriangle (i);
                if (triangle.mat !== null) {
                    let material = model.GetMaterial (triangle.mat);
                    material.vertexColors = true;
                }
            }
        }
    }

    let defaultMaterialIndex = null;
    let getDefaultMaterialIndex = function () {
        if (defaultMaterialIndex === null) {
            let defaultMaterial = getDefaultMaterial ();
            defaultMaterial.isDefault = true;
            defaultMaterialIndex = model.AddMaterial (defaultMaterial);
        }
        return defaultMaterialIndex;
    };

    for (let i = 0; i < model.MeshCount (); i++) {
        let mesh = model.GetMesh (i);
        if (mesh.TriangleCount () === 0) {
            model.RemoveMesh (i);
            i = i - 1;
            continue;
        }
        FinalizeMesh (model, mesh, getDefaultMaterialIndex);
    }

    let rootNode = model.GetRootNode ();
    let emptyNodes = [];
    rootNode.EnumerateChildren ((node) => {
        if (node.IsEmpty ()) {
            emptyNodes.push (node);
        }
    });
    for (let nodeIndex = 0; nodeIndex < emptyNodes.length; nodeIndex++) {
        let node = emptyNodes[nodeIndex];
        let parentNode = node.GetParent ();
        if (parentNode === null) {
            continue;
        }
        parentNode.RemoveChildNode (node);
        if (parentNode.IsEmpty ()) {
            emptyNodes.push (parentNode);
        }
    }
};

OV.CheckModel = function (model)
{
    function IsCorrectValue (val)
    {
        if (val === undefined || val === null) {
            return false;
        }
        return true;
    }

    function IsCorrectNumber (val)
    {
        if (!IsCorrectValue (val)) {
            return false;
        }
        if (isNaN (val)) {
            return false;
        }
        return true;
    }

    function IsCorrectIndex (val, count)
    {
        if (!IsCorrectNumber (val)) {
            return false;
        }
        if (val < 0 || val >= count) {
            return false;
        }
        return true;
    }

    function CheckMesh (model, mesh)
    {
        function CheckTriangle (model, mesh, triangle)
        {
            if (!IsCorrectIndex (triangle.v0, mesh.VertexCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.v1, mesh.VertexCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.v2, mesh.VertexCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.n0, mesh.NormalCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.n1, mesh.NormalCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.n2, mesh.NormalCount ())) {
                return false;
            }
            if (triangle.HasTextureUVs ()) {
                if (!IsCorrectIndex (triangle.u0, mesh.TextureUVCount ())) {
                    return false;
                }
                    if (!IsCorrectIndex (triangle.u1, mesh.TextureUVCount ())) {
                    return false;
                }
                if (!IsCorrectIndex (triangle.u2, mesh.TextureUVCount ())) {
                    return false;
                }
            }
            if (!IsCorrectIndex (triangle.mat, model.MaterialCount ())) {
                return false;
            }
            if (!IsCorrectNumber (triangle.curve)) {
                return false;
            }

            return true;
        }

        for (let i = 0; i < mesh.VertexCount (); i++) {
            let vertex = mesh.GetVertex (i);
            if (!IsCorrectNumber (vertex.x)) {
                return false;
            }
            if (!IsCorrectNumber (vertex.y)) {
                return false;
            }
            if (!IsCorrectNumber (vertex.z)) {
                return false;
            }
        }

        for (let i = 0; i < mesh.NormalCount (); i++) {
            let normal = mesh.GetNormal (i);
            if (!IsCorrectNumber (normal.x)) {
                return false;
            }
            if (!IsCorrectNumber (normal.y)) {
                return false;
            }
            if (!IsCorrectNumber (normal.z)) {
                return false;
            }
        }

        for (let i = 0; i < mesh.TextureUVCount (); i++) {
            let uv = mesh.GetTextureUV (i);
            if (!IsCorrectNumber (uv.x)) {
                return false;
            }
            if (!IsCorrectNumber (uv.y)) {
                return false;
            }
        }

        for (let i = 0; i < mesh.TriangleCount (); i++) {
            let triangle = mesh.GetTriangle (i);
            if (!CheckTriangle (model, mesh, triangle)) {
                return false;
            }
        }

        return true;
    }

    for (let i = 0; i < model.MeshCount (); i++) {
        let mesh = model.GetMesh (i);
        if (!CheckMesh (model, mesh)) {
            return false;
        }
    }
    return true;
};
<commit_msg>Minor modification.<commit_after>OV.FinalizeModel = function (model, getDefaultMaterial)
{
    function FinalizeMesh (model, mesh, getDefaultMaterialIndex)
    {
        function CalculateCurveNormals (mesh)
        {
            function AddAverageNormal (mesh, triangle, vertexIndex, triangleNormals, vertexToTriangles)
            {
                function IsNormalInArray (array, normal)
                {
                    for (let i = 0; i < array.length; i++) {
                        let current = array[i];
                        if (OV.CoordIsEqual3D (current, normal)) {
                            return true;
                        }
                    }
                    return false;
                }

                let averageNormals = [];
                let neigTriangles = vertexToTriangles[vertexIndex];
                for (let i = 0; i < neigTriangles.length; i++) {
                    let neigIndex = neigTriangles[i];
                    let neigTriangle = mesh.GetTriangle (neigIndex);
                    if (triangle.curve === neigTriangle.curve) {
                        let triangleNormal = triangleNormals[neigIndex];
                        if (!IsNormalInArray (averageNormals, triangleNormal)) {
                            averageNormals.push (triangleNormal);
                        }
                    }
                }

                let averageNormal = new OV.Coord3D (0.0, 0.0, 0.0);
                for (let i = 0; i < averageNormals.length; i++) {
                    averageNormal = OV.AddCoord3D (averageNormal, averageNormals[i]);
                }
                averageNormal.MultiplyScalar (1.0 / averageNormals.length);
                averageNormal.Normalize ();
                return mesh.AddNormal (averageNormal);
            }

            let triangleNormals = [];
            let vertexToTriangles = {};

            for (let vertexIndex = 0; vertexIndex < mesh.VertexCount (); vertexIndex++) {
                vertexToTriangles[vertexIndex] = [];
            }

            for (let triangleIndex = 0; triangleIndex < mesh.TriangleCount (); triangleIndex++) {
                let triangle = mesh.GetTriangle (triangleIndex);
                let v0 = mesh.GetVertex (triangle.v0);
                let v1 = mesh.GetVertex (triangle.v1);
                let v2 = mesh.GetVertex (triangle.v2);
                let normal = OV.CalculateTriangleNormal (v0, v1, v2);
                triangleNormals.push (normal);
                vertexToTriangles[triangle.v0].push (triangleIndex);
                vertexToTriangles[triangle.v1].push (triangleIndex);
                vertexToTriangles[triangle.v2].push (triangleIndex);
            }

            for (let triangleIndex = 0; triangleIndex < mesh.TriangleCount (); triangleIndex++) {
                let triangle = mesh.GetTriangle (triangleIndex);
                if (!triangle.HasNormals ()) {
                    let n0 = AddAverageNormal (mesh, triangle, triangle.v0, triangleNormals, vertexToTriangles);
                    let n1 = AddAverageNormal (mesh, triangle, triangle.v1, triangleNormals, vertexToTriangles);
                    let n2 = AddAverageNormal (mesh, triangle, triangle.v2, triangleNormals, vertexToTriangles);
                    triangle.SetNormals (n0, n1, n2);
                }
            }
        }

        function FinalizeTriangle (mesh, triangle, status)
        {
            if (!triangle.HasNormals ()) {
                if (triangle.curve === null || triangle.curve === 0) {
                    let v0 = mesh.GetVertex (triangle.v0);
                    let v1 = mesh.GetVertex (triangle.v1);
                    let v2 = mesh.GetVertex (triangle.v2);
                    let normal = OV.CalculateTriangleNormal (v0, v1, v2);
                    let normalIndex = mesh.AddNormal (normal);
                    triangle.SetNormals (normalIndex, normalIndex, normalIndex);
                } else {
                    status.calculateCurveNormals = true;
                }
            }
            if (triangle.mat === null) {
                triangle.mat = status.getDefaultMaterialIndex ();
            }
            if (triangle.curve === null) {
                triangle.curve = 0;
            }
        }

        let status = {
            getDefaultMaterialIndex : getDefaultMaterialIndex,
            calculateCurveNormals : false
        };

        let hasVertexColors = (mesh.VertexCount () === mesh.VertexColorCount ());
        for (let i = 0; i < mesh.TriangleCount (); i++) {
            let triangle = mesh.GetTriangle (i);
            FinalizeTriangle (mesh, triangle, status);
            if (hasVertexColors) {
                let material = model.GetMaterial (triangle.mat);
                material.vertexColors = true;
            }
        }

        if (status.calculateCurveNormals) {
            CalculateCurveNormals (mesh);
        }
    }

    let defaultMaterialIndex = null;
    let getDefaultMaterialIndex = function () {
        if (defaultMaterialIndex === null) {
            let defaultMaterial = getDefaultMaterial ();
            defaultMaterial.isDefault = true;
            defaultMaterialIndex = model.AddMaterial (defaultMaterial);
        }
        return defaultMaterialIndex;
    };

    for (let i = 0; i < model.MeshCount (); i++) {
        let mesh = model.GetMesh (i);
        if (mesh.TriangleCount () === 0) {
            model.RemoveMesh (i);
            i = i - 1;
            continue;
        }
        FinalizeMesh (model, mesh, getDefaultMaterialIndex);
    }

    let rootNode = model.GetRootNode ();
    let emptyNodes = [];
    rootNode.EnumerateChildren ((node) => {
        if (node.IsEmpty ()) {
            emptyNodes.push (node);
        }
    });
    for (let nodeIndex = 0; nodeIndex < emptyNodes.length; nodeIndex++) {
        let node = emptyNodes[nodeIndex];
        let parentNode = node.GetParent ();
        if (parentNode === null) {
            continue;
        }
        parentNode.RemoveChildNode (node);
        if (parentNode.IsEmpty ()) {
            emptyNodes.push (parentNode);
        }
    }
};

OV.CheckModel = function (model)
{
    function IsCorrectValue (val)
    {
        if (val === undefined || val === null) {
            return false;
        }
        return true;
    }

    function IsCorrectNumber (val)
    {
        if (!IsCorrectValue (val)) {
            return false;
        }
        if (isNaN (val)) {
            return false;
        }
        return true;
    }

    function IsCorrectIndex (val, count)
    {
        if (!IsCorrectNumber (val)) {
            return false;
        }
        if (val < 0 || val >= count) {
            return false;
        }
        return true;
    }

    function CheckMesh (model, mesh)
    {
        function CheckTriangle (model, mesh, triangle)
        {
            if (!IsCorrectIndex (triangle.v0, mesh.VertexCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.v1, mesh.VertexCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.v2, mesh.VertexCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.n0, mesh.NormalCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.n1, mesh.NormalCount ())) {
                return false;
            }
            if (!IsCorrectIndex (triangle.n2, mesh.NormalCount ())) {
                return false;
            }
            if (triangle.HasTextureUVs ()) {
                if (!IsCorrectIndex (triangle.u0, mesh.TextureUVCount ())) {
                    return false;
                }
                    if (!IsCorrectIndex (triangle.u1, mesh.TextureUVCount ())) {
                    return false;
                }
                if (!IsCorrectIndex (triangle.u2, mesh.TextureUVCount ())) {
                    return false;
                }
            }
            if (!IsCorrectIndex (triangle.mat, model.MaterialCount ())) {
                return false;
            }
            if (!IsCorrectNumber (triangle.curve)) {
                return false;
            }

            return true;
        }

        for (let i = 0; i < mesh.VertexCount (); i++) {
            let vertex = mesh.GetVertex (i);
            if (!IsCorrectNumber (vertex.x)) {
                return false;
            }
            if (!IsCorrectNumber (vertex.y)) {
                return false;
            }
            if (!IsCorrectNumber (vertex.z)) {
                return false;
            }
        }

        for (let i = 0; i < mesh.NormalCount (); i++) {
            let normal = mesh.GetNormal (i);
            if (!IsCorrectNumber (normal.x)) {
                return false;
            }
            if (!IsCorrectNumber (normal.y)) {
                return false;
            }
            if (!IsCorrectNumber (normal.z)) {
                return false;
            }
        }

        for (let i = 0; i < mesh.TextureUVCount (); i++) {
            let uv = mesh.GetTextureUV (i);
            if (!IsCorrectNumber (uv.x)) {
                return false;
            }
            if (!IsCorrectNumber (uv.y)) {
                return false;
            }
        }

        for (let i = 0; i < mesh.TriangleCount (); i++) {
            let triangle = mesh.GetTriangle (i);
            if (!CheckTriangle (model, mesh, triangle)) {
                return false;
            }
        }

        return true;
    }

    for (let i = 0; i < model.MeshCount (); i++) {
        let mesh = model.GetMesh (i);
        if (!CheckMesh (model, mesh)) {
            return false;
        }
    }
    return true;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs-extra');
var async = require('async');
var exec = require('child_process').exec;
var colors = require('colors');

function doExec(text) {
    return function (done) {
        exec(text, function (err, stdout, stderr) {
            if (stdout) console.log(stdout.grey);
            if (stderr) console.log(stderr.red);
            done(err);
        });
    };
}

// Let's get started
console.log('starting build...'.bgMagenta);

// Copy assets to www
require('./copy-assets');

// Clean
fs.removeSync('./platforms');
fs.removeSync('./plugins');

async.series([
    doExec('cordova platform add android firefoxos ios'),
    doExec('cordova plugin add https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git'),
    // PR in progress for org.apache.cordova.camera to add dataURIs for ffos
    doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-camera.git')
], function (err) {
    // Done!
    if (err) return console.log('finished build, but there were errors!'.bgMagenta);
    console.log('finished build with no errors.'.bgMagenta);
});

<commit_msg>Add network-information plugin. Related to GH-885<commit_after>#!/usr/bin/env node

var fs = require('fs-extra');
var async = require('async');
var exec = require('child_process').exec;
var colors = require('colors');

function doExec(text) {
    return function (done) {
        exec(text, function (err, stdout, stderr) {
            if (stdout) console.log(stdout.grey);
            if (stderr) console.log(stderr.red);
            done(err);
        });
    };
}

// Let's get started
console.log('starting build...'.bgMagenta);

// Copy assets to www
require('./copy-assets');

// Clean
fs.removeSync('./platforms');
fs.removeSync('./plugins');

async.series([
    doExec('cordova platform add android firefoxos ios'),
    doExec('cordova plugin add https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git'),
    doExec('cordova plugin add org.apache.cordova.network-information'),
    // PR in progress for org.apache.cordova.camera to add dataURIs for ffos
    doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-camera.git')
], function (err) {
    // Done!
    if (err) return console.log('finished build, but there were errors!'.bgMagenta);
    console.log('finished build with no errors.'.bgMagenta);
});

<|endoftext|>


<commit_before>#!/usr/bin/env node
// Upload Uppy releases to Edgly.net CDN. Copyright (c) 2018, Transloadit Ltd.
//
// This file:
//
//  - Assumes EDGLY_KEY and EDGLY_SECRET are available (e.g. set via Travis secrets)
//  - Assumes a fully built uppy is in root dir (unless a specific tag was specified, then it's fetched from npm)
//  - Collects dist/ files that would be in an npm package release, and uploads to eg. https://transloadit.edgly.net/releases/uppy/v1.0.1/uppy.css
//  - Uses local package by default, if [version] argument was specified, takes package from npm
//
// Run as:
//
//  npm run uploadcdn <package-name> [version]
//
// Authors:
//
//  - Kevin van Zonneveld <kevin@transloadit.com>

const path = require('path')
const AWS = require('aws-sdk')
const packlist = require('npm-packlist')
const tar = require('tar')
const pacote = require('pacote')
const concat = require('concat-stream')
const mime = require('mime-types')
const { promisify } = require('util')
const readFile = promisify(require('fs').readFile)
const finished = promisify(require('stream').finished)

function delay (ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

const AWS_REGION = 'us-east-1'
const AWS_BUCKET = 'crates.edgly.net'
const AWS_DIRECTORY = '756b8efaed084669b02cb99d4540d81f/default'

/**
 * Get remote dist/ files by fetching the tarball for the given version
 * from npm and filtering it down to package/dist/ files.
 *
 * @param {string} Package name, eg. @uppy/robodog
 * @param {string} Package version, eg. "1.2.0"
 * @returns a Map<string, Buffer>, filename → content
 */
async function getRemoteDistFiles (packageName, version) {
  const files = new Map()
  const tarball = pacote.tarball.stream(`${packageName}@${version}`)
    .pipe(new tar.Parse())

  tarball.on('entry', (readEntry) => {
    if (readEntry.path.startsWith('package/dist/')) {
      readEntry
        .pipe(concat((buf) => {
          files.set(readEntry.path.replace(/^package\/dist\//, ''), buf)
        }))
        .on('error', (err) => {
          tarball.emit('error', err)
        })
    } else {
      readEntry.resume()
    }
  })

  await finished(tarball)
  return files
}

/**
 * Get local dist/ files by asking npm-packlist what files would be added
 * to an npm package during publish, and filtering those down to just dist/ files.
 *
 * @param {string} Base file path of the package, eg. ./packages/@uppy/locales
 * @returns a Map<string, Buffer>, filename → content
 */
async function getLocalDistFiles (packagePath) {
  const files = (await packlist({ path: packagePath }))
    .filter(f => f.startsWith('dist/'))
    .map(f => f.replace(/^dist\//, ''))

  const entries = await Promise.all(
    files.map(async (f) => [
      f,
      await readFile(path.join(packagePath, 'dist', f))
    ])
  )

  return new Map(entries)
}

async function main (packageName, version) {
  if (!packageName) {
    console.error('usage: upload-to-cdn <packagename> [version]')
    console.error('Must provide a package name')
    process.exit(1)
  }

  if (!process.env.EDGLY_KEY || !process.env.EDGLY_SECRET) {
    console.error('Missing EDGLY_KEY or EDGLY_SECRET env variables, bailing')
    process.exit(1)
  }

  // version should only be a positional arg and semver string
  // this deals with usage like `npm run uploadcdn uppy -- --force`
  // where we force push a local build
  if (version.startsWith('-')) version = undefined

  const s3 = new AWS.S3({
    credentials: new AWS.Credentials({
      accessKeyId: process.env.EDGLY_KEY,
      secretAccessKey: process.env.EDGLY_SECRET
    }),
    region: AWS_REGION
  })

  const remote = !!version
  if (!remote) {
    version = require(`../packages/${packageName}/package.json`).version
  }

  // Warn if uploading a local build not from CI:
  // - If we're on CI, this should be a release commit.
  // - If we're local, normally we should upload a released version, not a local build.
  if (!remote && !process.env.CI) {
    console.log('Warning, writing a local build to the CDN, this is usually not what you want. Sleeping 3s. Press CTRL+C!')
    await delay(3000)
  }

  const packagePath = remote
    ? `${packageName}@${version}`
    : path.join(__dirname, '..', 'packages', packageName)

  // uppy → releases/uppy/
  // @uppy/robodog → releases/uppy/robodog/
  // @uppy/locales → releases/uppy/locales/
  const dirName = packageName.startsWith('@uppy/')
    ? packageName.replace(/^@/, '')
    : 'uppy'

  const outputPath = path.posix.join('releases', dirName, `v${version}`)

  const { Contents: existing } = await s3.listObjects({
    Bucket: AWS_BUCKET,
    Prefix: `${AWS_DIRECTORY}/${outputPath}/`
  }).promise()
  if (existing.length > 0) {
    if (process.argv.includes('--force')) {
      console.warn(`WARN Release files for ${dirName} v${version} already exist, overwriting...`)
    } else {
      console.error(`Release files for ${dirName} v${version} already exist, exiting...`)
      process.exit(1)
    }
  }

  const files = remote
    ? await getRemoteDistFiles(packageName, version)
    : await getLocalDistFiles(packagePath)

  for (const [filename, buffer] of files.entries()) {
    const key = path.posix.join(AWS_DIRECTORY, outputPath, filename)
    console.log(`pushing s3://${AWS_BUCKET}/${key}`)
    await s3.putObject({
      Bucket: AWS_BUCKET,
      Key: key,
      ContentType: mime.lookup(filename),
      Body: buffer
    }).promise()
  }
}

main(...process.argv.slice(2)).catch((err) => {
  console.error(err.stack)
  process.exit(1)
})
<commit_msg>Fix uploadcdn for local build<commit_after>#!/usr/bin/env node
// Upload Uppy releases to Edgly.net CDN. Copyright (c) 2018, Transloadit Ltd.
//
// This file:
//
//  - Assumes EDGLY_KEY and EDGLY_SECRET are available (e.g. set via Travis secrets)
//  - Assumes a fully built uppy is in root dir (unless a specific tag was specified, then it's fetched from npm)
//  - Collects dist/ files that would be in an npm package release, and uploads to eg. https://transloadit.edgly.net/releases/uppy/v1.0.1/uppy.css
//  - Uses local package by default, if [version] argument was specified, takes package from npm
//
// Run as:
//
//  npm run uploadcdn <package-name> [version]
//
// Authors:
//
//  - Kevin van Zonneveld <kevin@transloadit.com>

const path = require('path')
const AWS = require('aws-sdk')
const packlist = require('npm-packlist')
const tar = require('tar')
const pacote = require('pacote')
const concat = require('concat-stream')
const mime = require('mime-types')
const { promisify } = require('util')
const readFile = promisify(require('fs').readFile)
const finished = promisify(require('stream').finished)

function delay (ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

const AWS_REGION = 'us-east-1'
const AWS_BUCKET = 'crates.edgly.net'
const AWS_DIRECTORY = '756b8efaed084669b02cb99d4540d81f/default'

/**
 * Get remote dist/ files by fetching the tarball for the given version
 * from npm and filtering it down to package/dist/ files.
 *
 * @param {string} Package name, eg. @uppy/robodog
 * @param {string} Package version, eg. "1.2.0"
 * @returns a Map<string, Buffer>, filename → content
 */
async function getRemoteDistFiles (packageName, version) {
  const files = new Map()
  const tarball = pacote.tarball.stream(`${packageName}@${version}`)
    .pipe(new tar.Parse())

  tarball.on('entry', (readEntry) => {
    if (readEntry.path.startsWith('package/dist/')) {
      readEntry
        .pipe(concat((buf) => {
          files.set(readEntry.path.replace(/^package\/dist\//, ''), buf)
        }))
        .on('error', (err) => {
          tarball.emit('error', err)
        })
    } else {
      readEntry.resume()
    }
  })

  await finished(tarball)
  return files
}

/**
 * Get local dist/ files by asking npm-packlist what files would be added
 * to an npm package during publish, and filtering those down to just dist/ files.
 *
 * @param {string} Base file path of the package, eg. ./packages/@uppy/locales
 * @returns a Map<string, Buffer>, filename → content
 */
async function getLocalDistFiles (packagePath) {
  const files = (await packlist({ path: packagePath }))
    .filter(f => f.startsWith('dist/'))
    .map(f => f.replace(/^dist\//, ''))

  const entries = await Promise.all(
    files.map(async (f) => [
      f,
      await readFile(path.join(packagePath, 'dist', f))
    ])
  )

  return new Map(entries)
}

async function main (packageName, version) {
  if (!packageName) {
    console.error('usage: upload-to-cdn <packagename> [version]')
    console.error('Must provide a package name')
    process.exit(1)
  }

  if (!process.env.EDGLY_KEY || !process.env.EDGLY_SECRET) {
    console.error('Missing EDGLY_KEY or EDGLY_SECRET env variables, bailing')
    process.exit(1)
  }

  // version should only be a positional arg and semver string
  // this deals with usage like `npm run uploadcdn uppy -- --force`
  // where we force push a local build
  if (version && version.startsWith('-')) version = undefined

  const s3 = new AWS.S3({
    credentials: new AWS.Credentials({
      accessKeyId: process.env.EDGLY_KEY,
      secretAccessKey: process.env.EDGLY_SECRET
    }),
    region: AWS_REGION
  })

  const remote = !!version
  if (!remote) {
    version = require(`../packages/${packageName}/package.json`).version
  }

  // Warn if uploading a local build not from CI:
  // - If we're on CI, this should be a release commit.
  // - If we're local, normally we should upload a released version, not a local build.
  if (!remote && !process.env.CI) {
    console.log('Warning, writing a local build to the CDN, this is usually not what you want. Sleeping 3s. Press CTRL+C!')
    await delay(3000)
  }

  const packagePath = remote
    ? `${packageName}@${version}`
    : path.join(__dirname, '..', 'packages', packageName)

  // uppy → releases/uppy/
  // @uppy/robodog → releases/uppy/robodog/
  // @uppy/locales → releases/uppy/locales/
  const dirName = packageName.startsWith('@uppy/')
    ? packageName.replace(/^@/, '')
    : 'uppy'

  const outputPath = path.posix.join('releases', dirName, `v${version}`)

  const { Contents: existing } = await s3.listObjects({
    Bucket: AWS_BUCKET,
    Prefix: `${AWS_DIRECTORY}/${outputPath}/`
  }).promise()
  if (existing.length > 0) {
    if (process.argv.includes('--force')) {
      console.warn(`WARN Release files for ${dirName} v${version} already exist, overwriting...`)
    } else {
      console.error(`Release files for ${dirName} v${version} already exist, exiting...`)
      process.exit(1)
    }
  }

  const files = remote
    ? await getRemoteDistFiles(packageName, version)
    : await getLocalDistFiles(packagePath)

  for (const [filename, buffer] of files.entries()) {
    const key = path.posix.join(AWS_DIRECTORY, outputPath, filename)
    console.log(`pushing s3://${AWS_BUCKET}/${key}`)
    await s3.putObject({
      Bucket: AWS_BUCKET,
      Key: key,
      ContentType: mime.lookup(filename),
      Body: buffer
    }).promise()
  }
}

main(...process.argv.slice(2)).catch((err) => {
  console.error(err.stack)
  process.exit(1)
})
<|endoftext|>


<commit_before>var isClicked = false;

//jQuery for page scrolling feature - requires jQuery Easing plugin

// burger collapse, by adding and removing css class
$(document).ready(function () {
    $('#nav-icon1').click(function (e) {
        $("#nav-icon1").toggleClass('open');
        $(".fel-navbar").toggleClass("collapsed-nav");
        $(".main-for-transform").toggleClass("transform-main");
    });
});

$('.img-holder').imageScroll({
    speed: 0.1
});

var vid = document.getElementById("my-video");
var isplaying = true;

$(document).ready(function () {
    $('#playpause').click(function (e) {
        if (isplaying) {
            vid.pause();
            $(".play-pause").removeClass("pause");
            $(".play-pause").addClass("play");
            isplaying = false;
        } else {
            vid.play();
            $(".play-pause").removeClass("play");
            $(".play-pause").addClass("pause");
            isplaying = true;
        }
    });
});

var sections = $('section')
    , nav = $('.fel-navbar');

$(window).on('scroll', function () {
    var cur_pos = $(this).scrollTop();

    sections.each(function() {
        var top = $(this).offset().top,
            bottom = top + $(this).outerHeight();

        if (cur_pos >= top && cur_pos <= bottom) {
            nav.find('a').removeClass('active');
            nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
        }
    });
});

nav.find('a').on('click', function () {
    var $el = $(this)
        , id = $el.attr('href');

    $('html, body').animate({
        scrollTop: $(id).offset().top + 20
    }, 500);

    return false;
});
<commit_msg>ohne das der content verschoben wird...<commit_after>var isClicked = false;

//jQuery for page scrolling feature - requires jQuery Easing plugin

// burger collapse, by adding and removing css class
$(document).ready(function () {
    $('#nav-icon1').click(function (e) {
        $("#nav-icon1").toggleClass('open');
        $(".fel-navbar").toggleClass("collapsed-nav");
    });
});

$('.img-holder').imageScroll({
    speed: 0.1
});

var vid = document.getElementById("my-video");
var isplaying = true;

$(document).ready(function () {
    $('#playpause').click(function (e) {
        if (isplaying) {
            vid.pause();
            $(".play-pause").removeClass("pause");
            $(".play-pause").addClass("play");
            isplaying = false;
        } else {
            vid.play();
            $(".play-pause").removeClass("play");
            $(".play-pause").addClass("pause");
            isplaying = true;
        }
    });
});

var sections = $('section')
    , nav = $('.fel-navbar');

$(window).on('scroll', function () {
    var cur_pos = $(this).scrollTop();

    sections.each(function() {
        var top = $(this).offset().top,
            bottom = top + $(this).outerHeight();

        if (cur_pos >= top && cur_pos <= bottom) {
            nav.find('a').removeClass('active');
            nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
        }
    });
});

nav.find('a').on('click', function () {
    var $el = $(this)
        , id = $el.attr('href');

    $('html, body').animate({
        scrollTop: $(id).offset().top + 20
    }, 500);

    return false;
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Paper from 'material-ui/Paper';
import { Toolbar } from 'material-ui/Toolbar';
import WindowToolbarTitle from '../WindowToolbarTitle';

class HistoryToolbar extends Component {
    render() {
        const { namespace, selectedKey } = this.props;

        return (
            <Paper style={{ zIndex: 5 }}>
                <Toolbar>
                    <WindowToolbarTitle path={`${namespace}/${selectedKey}`} />
                </Toolbar>
            </Paper>
        );
    }
}

HistoryToolbar.propTypes = {
    selectedKey: PropTypes.string,
    namespace: PropTypes.string,
};

export default HistoryToolbar;
<commit_msg>HistoryToolbar: fix ‘undefined’ title<commit_after>import React, { Component, PropTypes } from 'react';
import Paper from 'material-ui/Paper';
import { Toolbar } from 'material-ui/Toolbar';
import WindowToolbarTitle from '../WindowToolbarTitle';

class HistoryToolbar extends Component {
    render() {
        const { namespace, selectedKey } = this.props;
        const path = `${namespace}/` + (selectedKey ? `${selectedKey}/History` : 'History');

        return (
            <Paper style={{ zIndex: 5 }}>
                <Toolbar>
                    <WindowToolbarTitle path={path} />
                </Toolbar>
            </Paper>
        );
    }
}

HistoryToolbar.propTypes = {
    selectedKey: PropTypes.string,
    namespace: PropTypes.string,
};

export default HistoryToolbar;
<|endoftext|>


<commit_before>"use strict";

describe("morph", function() {
  var mockConfigurator = {
    configurationFor: function(name) {
      return {};
    },
    getRetrievers: function(name) {
      return {};
    },
    getConfAndDelegate: function(name, obj) {
      obj.attributes = {
        "pos" : {
          "long" : "Part of Speech",
          "short" : "pos",
          "values" : {
            "noun" : {
              "long" : "noun",
              "short" : "noun",
              "postag" : "n",
              "style" : {
                "color" : "black"
              }
            },
            "adj" : {
              "long" : "adjective",
              "short" : "adj",
              "postag" : "a",
              "style" : {
                "color" : "blue"
              }
            }
          }
        },
        "pers" : {
          "long" : "Person",
          "short" : "pers",
          "values" : {
            "1st" : {
              "long" : "first person",
              "short" : "1st",
              "postag" : "1"
            },
            "2nd" : {
              "long" : "second person",
              "short" : "2nd",
              "postag" : "2"
            }
          }
        }
      };
      obj.postagSchema = ['pos', 'pers'];
      obj.styledThrough = 'pos';
      obj.conf = {};
    }
  };

  var createTokens = function() {
    return {
      '01': {
        id: '01',
        string: 't1',
        morphology: {
          lemma: 'lemma1',
          postag: 'n-'
        }
      },
      '02': {
        id: '02',
        string: 't2',
        morphology: {
          lemma: 'lemma2',
          postag: 'a1'
        }
      }
    };
  };

  beforeEach(module("arethusa.core", function($provide) {
    $provide.value('configurator', mockConfigurator);
  }));

  beforeEach(module("arethusa.morph"));

  var morph;
  var state;
  beforeEach(inject(function(_morph_, _state_) {
    state = _state_;
    state.tokens = createTokens();
    morph = _morph_;
    morph.init();
  }));

  describe('this.postagToAttributes', function() {
    it('expands a postag to full key value pairs', function() {
      var form = { postag: 'a1' };
      var res  = angular.extend({}, form, { attributes: { pos: 'adj', pers: '1st' }});
      morph.postagToAttributes(form);
      expect(form).toEqual(res);
    });
  });

  describe('this.attributesToPostag', function() {
    it('creates a postag string out of attributes', function() {
      var attrs = { pos: 'noun', pers: '2nd' };
      var res = 'n2';
      var postag = morph.attributesToPostag(attrs);
      expect(postag).toEqual(res);
    });

    it('fills with - according to the postagSchema, when an attribute is undefined', function() {
      var attrs = { pers: '1st' };
      var res = '-1';
      var postag = morph.attributesToPostag(attrs);
      expect(postag).toEqual(res);
    });
  });

  describe('this.updatePostag', function() {
    it('updates a postag at a specific datapoint', function() {
      var form = { postag: '--' };
      morph.updatePostag(form, 'pos', 'noun');
      expect(form.postag).toEqual('n-');
    });
  });

  describe('this.emptyPostag', function() {
    it('returns an empty postag according to the configured postagSchema', function() {
      expect(morph.emptyPostag()).toEqual('--');
    });
  });
});
<commit_msg>Add lots of morph.queryForm() specs<commit_after>"use strict";

describe("morph", function() {
  var mockConfigurator = {
    configurationFor: function(name) {
      return {};
    },
    getRetrievers: function(name) {
      return {};
    },
    getConfAndDelegate: function(name, obj) {
      obj.attributes = {
        "pos" : {
          "long" : "Part of Speech",
          "short" : "pos",
          "values" : {
            "noun" : {
              "long" : "noun",
              "short" : "noun",
              "postag" : "n",
              "style" : {
                "color" : "black"
              }
            },
            "adj" : {
              "long" : "adjective",
              "short" : "adj",
              "postag" : "a",
              "style" : {
                "color" : "blue"
              }
            }
          }
        },
        "pers" : {
          "long" : "Person",
          "short" : "pers",
          "values" : {
            "1st" : {
              "long" : "first person",
              "short" : "1st",
              "postag" : "1"
            },
            "2nd" : {
              "long" : "second person",
              "short" : "2nd",
              "postag" : "2"
            }
          }
        }
      };
      obj.postagSchema = ['pos', 'pers'];
      obj.styledThrough = 'pos';
      obj.conf = {};
    }
  };

  var createTokens = function() {
    return {
      '01': {
        id: '01',
        string: 't1',
        morphology: {
          lemma: 'lemma1',
          postag: 'n-'
        }
      },
      '02': {
        id: '02',
        string: 't2',
        morphology: {
          lemma: 'lemma2',
          postag: 'a1'
        }
      }
    };
  };

  beforeEach(module("arethusa.core", function($provide) {
    $provide.value('configurator', mockConfigurator);
  }));

  beforeEach(module("arethusa.morph"));

  var morph;
  var state;
  beforeEach(inject(function(_morph_, _state_) {
    state = _state_;
    state.tokens = createTokens();
    morph = _morph_;
    morph.init();
  }));

  describe('this.postagToAttributes', function() {
    it('expands a postag to full key value pairs', function() {
      var form = { postag: 'a1' };
      var res  = angular.extend({}, form, { attributes: { pos: 'adj', pers: '1st' }});
      morph.postagToAttributes(form);
      expect(form).toEqual(res);
    });
  });

  describe('this.attributesToPostag', function() {
    it('creates a postag string out of attributes', function() {
      var attrs = { pos: 'noun', pers: '2nd' };
      var res = 'n2';
      var postag = morph.attributesToPostag(attrs);
      expect(postag).toEqual(res);
    });

    it('fills with - according to the postagSchema, when an attribute is undefined', function() {
      var attrs = { pers: '1st' };
      var res = '-1';
      var postag = morph.attributesToPostag(attrs);
      expect(postag).toEqual(res);
    });
  });

  describe('this.updatePostag', function() {
    it('updates a postag at a specific datapoint', function() {
      var form = { postag: '--' };
      morph.updatePostag(form, 'pos', 'noun');
      expect(form.postag).toEqual('n-');
    });
  });

  describe('this.emptyPostag', function() {
    it('returns an empty postag according to the configured postagSchema', function() {
      expect(morph.emptyPostag()).toEqual('--');
    });
  });

  describe('this.queryForm', function() {
    it('looks up forms in the state object and selects them', function() {
      expect(state.hasSelections()).toBeFalsy();
      morph.matchAll = false;
      morph.formQuery = 'adj';
      morph.queryForm();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('02')).toBeTruthy();
    });

    it('can look up by multiple attributes at the same time', function() {
      expect(state.hasSelections()).toBeFalsy();
      morph.matchAll = false;
      morph.formQuery = 'adj noun';
      morph.queryForm();
      expect(state.isSelected('01')).toBeTruthy();
      expect(state.isSelected('02')).toBeTruthy();
    });

    it('does a fuzzy search through all attributes of forms', function() {
      expect(state.hasSelections()).toBeFalsy();
      morph.matchAll = false;
      morph.formQuery = '1st';
      morph.queryForm();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('02')).toBeTruthy();
    });

    it("doesn't create false hits", function() {
      expect(state.hasSelections()).toBeFalsy();
      morph.matchAll = false;
      morph.formQuery = '3rd';
      morph.queryForm();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('02')).toBeFalsy();
    });

    it('optionally searches for forms that satisfy multiple attributes', function() {
      expect(state.hasSelections()).toBeFalsy();
      morph.matchAll = true;
      morph.formQuery = 'noun 2nd';
      morph.queryForm();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('02')).toBeFalsy();

      morph.formQuery = 'adj 1st';
      morph.queryForm();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('02')).toBeTruthy();
    });

    it('only searches for short versions of attribute values for now', function() {
      expect(state.hasSelections()).toBeFalsy();
      morph.matchAll = false;
      morph.formQuery = 'adj';
      morph.queryForm();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('02')).toBeTruthy();

      morph.formQuery = 'adjective';
      morph.queryForm();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('02')).toBeFalsy();
    });
  });
});
<|endoftext|>