<commit_before>const assert = require('assert');
const _ = require('lodash');
const express = require('express');
const request = require('supertest');
const msgpackLite = require('msgpack-lite');

const msgPack = require('../index.js');

let app = null;
let sample_json = {'da test': 'worked'};
let sample_encoded = msgpackLite.encode(sample_json);
let sample_encoded_size = _.size(sample_encoded);

describe('Base Functionality', function() {
  before(function() {
    app = express();

    app.use(msgPack({auto_detect: true}));
    app.get('/test_json', function(req, res) {
	    res.status(200).json(sample_json);
    });
    app.get('/test_msgpack', function(req, res) {
      res.status(200).msgPack(sample_json);
    });
  });

  describe('#Demo App Test Requests (auto-detect JSON)', function() {
    it('Count Encoded Message Bytes', function(done) {
      request(app)
        .get('/test_json')
        .set('Accept', 'application/x-msgpack')
        .expect('Content-Type', /msgpack/)
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          let response_size = _.size(res.text);
          assert.equal(sample_encoded_size, response_size, `Response size is not correct (${sample_encoded_size} != ${response_size})`);
          done();
        });

    });

    it('Check Decoded Response Structure', function(done) {
      request(app)
        .get('/test_json')
        .set('Accept', 'application/x-msgpack')
        .expect('Content-Type', /msgpack/)
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          //let decoded_json = msgpackLite.decode(res.);
          //assert.deepEqual(sample_json, decoded_json, `Decoded JSON is not equal with the original (${decoded_json} != ${sample_json})`);
          done();
        });
    });
  });

  describe('#Demo App Test Requests (msgPack() extension method)', function() {
    it('Count Encoded Message Bytes', function(done) {
      request(app)
        .get('/test_msgpack')
        .set('Accept', 'application/x-msgpack')
        .expect('Content-Type', /msgpack/)
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          let response_size = _.size(res.text);
          assert.equal(sample_encoded_size, response_size, `Response size is not correct (${sample_encoded_size} != ${response_size})`);
          done();
        });
    });

    it('Check Decoded Response Structure', function(done) {
      request(app)
        .get('/test_msgpack')
        .set('Accept', 'application/x-msgpack')
        .expect('Content-Type', /msgpack/)
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          //let decoded_json = msgpackLite.decode(res.text);
          done();
        });
    });
  });
});<commit_msg>messing with testing<commit_after>const assert = require('assert');
const _ = require('lodash');
const express = require('express');
const request = require('supertest');
const msgpackLite = require('msgpack-lite');

const msgPack = require('../index.js');

let app = null;
let sample_json = {'da test': 'worked'};
let sample_encoded = msgpackLite.encode(sample_json);
let sample_encoded_size = _.size(sample_encoded);

describe('Base Functionality', function() {
  before(function() {
    app = express();

    app.use(msgPack({auto_detect: true}));
    app.get('/test_json', function(req, res) {
	    res.status(200).json(sample_json);
    });
    app.get('/test_msgpack', function(req, res) {
      res.status(200).msgPack(sample_json);
    });
  });

  describe('#Demo App Test Requests (auto-detect JSON)', function() {
    it('Count Encoded Message Bytes', function(done) {
      request(app)
        .get('/test_json')
        .set('Accept', 'application/x-msgpack')
        .expect('Content-Type', /msgpack/)
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          let response_size = _.size(res.text);
          assert.equal(sample_encoded_size, response_size, `Response size is not correct (${sample_encoded_size} != ${response_size})`);
          done();
        });

    });

    it('Check Decoded Response Structure', function(done) {
      request(app)
        .get('/test_json')
        .set('Accept', 'application/x-msgpack')
        .expect('Content-Type', /msgpack/)
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          done();
        });
    });
  });

  describe('#Demo App Test Requests (msgPack() extension method)', function() {
    it('Count Encoded Message Bytes', function(done) {
      request(app)
        .get('/test_msgpack')
        .set('Accept', 'application/x-msgpack')
        .expect('Content-Type', /msgpack/)
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          let response_size = _.size(res.text);
          assert.equal(sample_encoded_size, response_size, `Response size is not correct (${sample_encoded_size} != ${response_size})`);
          done();
        });
    });

    it('Check Decoded Response Structure', function(done) {
      request(app)
        .get('/test_msgpack')
        .set('Accept', 'application/x-msgpack')
        .expect('Content-Type', /msgpack/)
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          done();
        });
    });
  });
});<|endoftext|>


<commit_before>/**
 * @ngdoc module
 * @module hs.compositions
 * @name hs.compositions
 * @description Composition module
 */

define(['angular', 'ol', 'SparqlJson', 'angularjs-socialshare', 'map', 'ows.nonwms', 'config_parsers'],

    function (angular, ol, SparqlJson, social) {
        return {
            init() {
                angular.module('hs.compositions')
                    /**
                     * @module hs.compositions
                     * @name hs.compositions.controller
                     * @ngdoc controller
                     * @description Main controller of composition module
                     */
                    .controller('hs.compositions.controller', ['$scope', 'Core', 'hs.compositions.service', '$window', '$mdDialog', '$mdMedia', 'config', '$compile',
                        function ($scope, Core, Composition, $window, $mdDialog, $mdMedia, config, $compile) {
                            $scope.CS = Composition;
                            $scope.data = Composition.data;
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#page_size
                            * @public
                            * @type {number} 15
                            * @description Number of compositions displayed on one panel page
                            */
                            $scope.pageSize = 15;
                            $scope.compStart = 0;
                            $scope.compNext = $scope.pageSize;
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#panel_name
                            * @deprecated
                            * @type {string} composition_browser
                            * @description
                            */
                            $scope.panel_name = 'composition_browser';
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#keywords
                            * @public
                            * @type {Object}
                            * @description List of keywords (currently hard-coded selection), with their selection status (Boolean value) which sets if keyword will be applied in compositions lookup
                            */
                            $scope.keywords = {
                                "Basemap": false,
                                "Borders": false,
                                "PhysicalGeography": false,
                                "Demographics": false,
                                "Economics": false,
                                "SocioPoliticalConditions": false,
                                "Culture": false,
                                "Transport": false,
                                "LandUse": false,
                                "Environment": false,
                                "Water": false,
                                "Hazards": false,
                                "Cadastre": false,
                                "Infrastructure": false,
                                "RealEstate": false,
                                "Planning": false,
                                "ComplexInformation": false
                            };
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#sortBy
                            * @public
                            * @type {string} bbox
                            * @description Store current rule for sorting compositions in composition list (supported values: bbox, title, date)
                            */
                            $scope.sortBy = 'bbox';
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#filterByExtent
                            * @public
                            * @type {Boolean} true
                            * @description Store whether filter compositions by current window extent during composition search
                            */
                            $scope.filterByExtent = true;
                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#getPreviousCompositions
                             * @public
                             * @description Load previous list of compositions to display on pager (number per page set by {@link hs.compositions.controller#page_size hs.compositions.controller#page_size})
                             */
                            $scope.getPreviousCompositions = function () {
                                if ($scope.compStart - $scope.pageSize < 0) {
                                    $scope.compStart = 0;
                                    $scope.compNext = $scope.pageSize;
                                } else {
                                    $scope.compStart -= $scope.pageSize;
                                    $scope.compNext = $scope.compStart + $scope.pageSize;
                                }
                                $scope.loadCompositions();
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#getNextCompositions
                             * @public
                             * @description Load next list of compositions to display on pager (number per page set by {@link hs.compositions.controller#page_size hs.compositions.controller#page_size})
                             */
                            $scope.getNextCompositions = function () {
                                if ($scope.compNext != 0) {
                                    $scope.compStart = Math.floor($scope.compNext / $scope.pageSize) * $scope.pageSize;

                                    if ($scope.compNext + $scope.pageSize > $scope.compositionsCount) {
                                        $scope.compNext = $scope.compositionsCount;
                                    } else {
                                        $scope.compNext += $scope.pageSize;
                                    }
                                    $scope.loadCompositions();
                                }
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#loadCompositions
                             * @public
                             * @description Load list of compositions according to current filter values and pager position (filter, keywords, current extent, start composition, compositions number per page). Display compositions extent in map
                             */
                            $scope.loadCompositions = function () {
                                Composition.loadCompositions({
                                    query: $scope.query,
                                    sortBy: $scope.sortBy,
                                    filterExtent: $scope.filterByExtent,
                                    keywords: $scope.keywords,
                                    start: $scope.compStart,
                                    limit: $scope.pageSize
                                });
                            }

                            $scope.$watch('data.next', function () {
                                $scope.compNext = $scope.data.next;
                            })

                            /**
                             * Handler of "Only mine" filter change, delete editable variable if needed
                             * @module hs.compositions.controller
                             * @function miniFilterChanged
                             * DEPRECATED?
                             */
                            $scope.mineFilterChanged = function () {
                                if (angular.isDefined($scope.query.editable) && $scope.query.editable == false) delete $scope.query.editable;
                            }

                            $scope.getPageSize = function () {
                                let listHeight = screen.height;
                                if ($mdMedia("gt-sm")) {
                                    let panel = angular.element('#sidenav-right');
                                    listHeight = panel.height();
                                }
                                $scope.pageSize = Math.round((listHeight - 180) / 60);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#filterChanged
                             * @public
                             * @description Reloads compositions from start, used as callback when filters are changed in view
                             */
                            $scope.filterChanged = function () {
                                Composition.resetCompositionCounter();
                                $scope.compStart = 0;
                                $scope.compNext = $scope.pageSize;
                                $scope.loadCompositions();
                            }

                             /**
                             * @ngdoc method
                             * @name hs.compositions.controller#confirmDelete
                             * @public
                             * @param {object} composition Composition selected for deletion
                             * @param {object} ev
                             * @description Display delete dialog of composition
                             */
                            $scope.confirmDelete = function (composition, ev) {
                                $scope.compositionToDelete = composition;
                                if(config.design == 'md')
                                    deleteDialogBootstrap();
                                else
                                    shareDialogBootstrap()
                            }

                            function deleteDialogBootstrap(ev) {
                                if (!$scope.$$phase) $scope.$digest();
                                $("#hs-dialog-area #composition-delete-dialog").remove();
                                var el = angular.element('
');
                                $("#hs-dialog-area").append(el)
                                $compile(el)($scope);
                            }

                            function deleteDialog(ev) {
                                $mdDialog.show({
                                    parent: angular.element('#hsContainer'),
                                    targetEvent: ev,
                                    clickOutsideToClose: true,
                                    escapeToClose: true,
                                    scope: $scope,
                                    preserveScope: true,
                                    templateUrl: 'materialComponents/panelContents/compositionLoadUnsavedDialog.html',
                                    controller: function DialogController($scope, $mdDialog) {
                                        $scope.closeDialog = function () {
                                            $mdDialog.hide();
                                        }
                                    }
                                });
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#delete
                             * @public
                             * @param {object} composition Composition selected for deletion
                             * @description Delete selected composition from project (including deletion from composition server, useful for user created compositions)
                             */
                            $scope.delete = function (composition) {
                                Composition.deleteComposition(composition);
                            }

                            /**
                             * Load selected composition for editing
                             * @module hs.compositions.controller
                             * @function edit
                             * @param {object} composition Selected composition
                             */
                            $scope.edit = function (composition) {
                                $scope.data.useCallbackForEdit = true;
                                Composition.loadComposition(composition);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#highlightComposition
                             * @public
                             * @param {Object} composition Composition to highlight
                             * @param {Boolean} state Target state of composition ( True - highlighted, False - normal)
                             * @description Highlight (or dim) composition, toogle visual state of composition extent on map
                             */
                            $scope.highlightComposition = function (composition, state) {
                                Composition.highlightComposition(composition, state);
                            }

                            $scope.$on('map.extent_changed', function (event, data, b) {
                                if (Core.mainpanel != 'composition_browser' && Core.mainpanel != 'composition') return;
                                if ($scope.filterByExtent) $scope.loadCompositions();
                            });

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#shareComposition
                             * @public
                             * @param {object} record Composition to share
                             * @description Prepare share object on server and display share dialog to share composition
                             */
                            $scope.shareComposition = function (record, $event) {
                                Composition.shareComposition(record);
                                if(config.design == 'md')
                                    shareDialogMd($event);
                                else
                                    shareDialogBootstrap()
                            }

                            function shareDialogBootstrap($event) {
                                $("#hs-dialog-area #composition-share-dialog").remove();
                                var el = angular.element('

');
                                $("#hs-dialog-area").append(el)
                                $compile(el)($scope);
                            }

                            function shareDialogMd($event) {
                                $mdDialog.show({
                                    parent: angular.element('#hsContainer'),
                                    targetEvent: $event,
                                    clickOutsideToClose: true,
                                    escapeToClose: true,
                                    scope: $scope,
                                    preserveScope: true,
                                    templateUrl: 'components/compositions/partials/dialog_sharemd.html',
                                    controller: function DialogController($scope, $mdDialog) {
                                        $scope.closeDialog = function () {
                                            $mdDialog.hide();
                                        }
                                    }
                                });
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#detailComposition
                             * @public
                             * @param {object} record Composition to show details
                             * @description Load info about composition through service and display composition info dialog
                             */
                            $scope.detailComposition = function (record, $event) {
                                $scope.info = Composition.getCompositionInfo(record);
                                if(config.design == 'md')
                                    infoDialogMD($event);
                                else
                                    infoDialogBootstrap();
                            }

                            function infoDialogBootstrap() {
                                if (!$scope.$$phase) $scope.$digest();
                                $("#hs-dialog-area #composition-info-dialog").remove();
                                var el = angular.element('
');
                                $("#hs-dialog-area").append(el)
                                $compile(el)($scope);
                            }

                            function infoDialogMD($event) {
                                var parentEl = angular.element('#hsContainer');
                                $mdDialog.show({
                                    parent: parentEl,
                                    targetEvent: $event,
                                    clickOutsideToClose: true,
                                    escapeToClose: true,
                                    template:
                                    '<md-dialog aria-label="List dialog">' +
                                    '  <md-dialog-content layout="column" layout-padding>' +
                                    '    <md-list>' +
                                    '
' +
                                    '       Abstract{{info.abstract}}' +
                                    '
' +
                                    '
' +
                                    '       Thumbnail{{info.thumbnail}}' +
                                    '
' +
                                    '
' +
                                    '       Extent{{info.extent}}' +
                                    '
' +
                                    '
' +
                                    '       Layer{{layer.title}}' +
                                    '
' +
                                    '    </md-list>' +
                                    '  </md-dialog-content>' +
                                    '  <md-dialog-actions>' +
                                    '    <md-button ng-click="closeDialog()" class="md-primary">' +
                                    '      Close' +
                                    '    </md-button>' +
                                    '  </md-dialog-actions>' +
                                    '</md-dialog>',
                                    locals: {
                                        info: $scope.info
                                    },
                                    controller: DialogController
                                });

                                function DialogController($scope, $mdDialog, info) {
                                    $scope.info = info;
                                    $scope.closeDialog = function () {
                                        $mdDialog.hide();
                                    }
                                }
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#loadComposition
                             * @public
                             * @param {object} record Composition to be loaded
                             * @description Load selected composition in map, if current composition was edited display Ovewrite dialog
                             */
                            $scope.loadComposition = function (record) {
                                Composition.loadCompositionParser(record);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#overwrite
                             * @public
                             * @description Load new composition without saving old composition
                             */
                            $scope.overwrite = function () {
                                Composition.loadComposition($scope.compositionToLoad, true);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#add
                             * @public
                             * @description Load new composition (with service_parser Load function) and merge it with old composition
                             */
                            $scope.add = function () {
                                Composition.loadComposition($scope.compositionToLoad, false);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#save
                             * @public
                             * @description Open Status creator panel for saving old composition
                             */
                            $scope.save = function () {
                                Core.openStatusCreator();
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#setSortAttribute
                             * @public
                             * @param {String} attribute Attribute by which compositions should be sorted (expected values: bbox, title, date)
                             * @description Set sort attribute for sorting composition list and reload compositions
                             */
                            $scope.setSortAttribute = function (attribute) {
                                $scope.sortBy = attribute;
                                $scope.loadCompositions();
                            }
                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#toggleKeywords
                             * @public
                             * @description Toogle keywords panel on compositions panel
                             */
                            $scope.toggleKeywords = function () {
                                $(".keywords-panel").slideToggle();
                            }

                            $scope.$on('CompositionLoaded', function () {
                                $('.tooltip').remove();
                                $('[data-toggle="tooltip"]').tooltip();
                            });

                            $scope.$on('compositions.composition_deleted', function () {
                                $("#hs-dialog-area #composition-delete-dialog").remove();
                            });

                            $scope.$on('loadComposition.notSaved', function (event, data) {
                                $scope.compositionToLoad = data.link;
                                if(config.design == 'md')
                                    loadUnsavedDialogMD();
                                else
                                    loadUnsavedDialogBootstrap();
                            });

                            function loadUnsavedDialogBootstrap(){
                                var dialog_id = '#composition-overwrite-dialog';
                                $scope.composition_name_to_be_loaded = data.title;
                                if ($("#hs-dialog-area " + dialog_id).length == 0) {
                                    var el = angular.element('
');
                                    $("#hs-dialog-area").append(el);
                                    $compile(el)($scope);
                                } else {
                                    $(dialog_id).modal('show');
                                }
                            }

                            function loadUnsavedDialogMD() {
                                $mdDialog.show({
                                    parent: angular.element('#hsContainer'),
                                    clickOutsideToClose: true,
                                    escapeToClose: true,
                                    scope: $scope,
                                    preserveScope: true,
                                    templateUrl: 'materialComponents/panelContents/compositionLoadUnsavedDialog.html',
                                    controller: function DialogController($scope, $mdDialog) {
                                        $scope.closeDialog = function () {
                                            $mdDialog.hide();
                                        }
                                    }
                                });
                            }

                            $scope.$on('core.mainpanel_changed', function (event) {
                                if (Core.mainpanel === 'composition_browser' || Core.mainpanel === 'composition') {
                                    $scope.loadCompositions();
                                }
                            });

                            $scope.getPageSize();
                            angular.element($window).resize(function () {
                                $scope.getPageSize();
                            });
                            $scope.$on("Core_sizeChanged", function () {
                                $scope.getPageSize();
                            });

                            $scope.$emit('scope_loaded', "Compositions");
                        }
                    ])
            }
        }

    })<commit_msg>Frong deleteDialog function called in compositions<commit_after>/**
 * @ngdoc module
 * @module hs.compositions
 * @name hs.compositions
 * @description Composition module
 */

define(['angular', 'ol', 'SparqlJson', 'angularjs-socialshare', 'map', 'ows.nonwms', 'config_parsers'],

    function (angular, ol, SparqlJson, social) {
        return {
            init() {
                angular.module('hs.compositions')
                    /**
                     * @module hs.compositions
                     * @name hs.compositions.controller
                     * @ngdoc controller
                     * @description Main controller of composition module
                     */
                    .controller('hs.compositions.controller', ['$scope', 'Core', 'hs.compositions.service', '$window', '$mdDialog', '$mdMedia', 'config', '$compile',
                        function ($scope, Core, Composition, $window, $mdDialog, $mdMedia, config, $compile) {
                            $scope.CS = Composition;
                            $scope.data = Composition.data;
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#page_size
                            * @public
                            * @type {number} 15
                            * @description Number of compositions displayed on one panel page
                            */
                            $scope.pageSize = 15;
                            $scope.compStart = 0;
                            $scope.compNext = $scope.pageSize;
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#panel_name
                            * @deprecated
                            * @type {string} composition_browser
                            * @description
                            */
                            $scope.panel_name = 'composition_browser';
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#keywords
                            * @public
                            * @type {Object}
                            * @description List of keywords (currently hard-coded selection), with their selection status (Boolean value) which sets if keyword will be applied in compositions lookup
                            */
                            $scope.keywords = {
                                "Basemap": false,
                                "Borders": false,
                                "PhysicalGeography": false,
                                "Demographics": false,
                                "Economics": false,
                                "SocioPoliticalConditions": false,
                                "Culture": false,
                                "Transport": false,
                                "LandUse": false,
                                "Environment": false,
                                "Water": false,
                                "Hazards": false,
                                "Cadastre": false,
                                "Infrastructure": false,
                                "RealEstate": false,
                                "Planning": false,
                                "ComplexInformation": false
                            };
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#sortBy
                            * @public
                            * @type {string} bbox
                            * @description Store current rule for sorting compositions in composition list (supported values: bbox, title, date)
                            */
                            $scope.sortBy = 'bbox';
                            /**
                            * @ngdoc property
                            * @name hs.compositions.controller#filterByExtent
                            * @public
                            * @type {Boolean} true
                            * @description Store whether filter compositions by current window extent during composition search
                            */
                            $scope.filterByExtent = true;
                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#getPreviousCompositions
                             * @public
                             * @description Load previous list of compositions to display on pager (number per page set by {@link hs.compositions.controller#page_size hs.compositions.controller#page_size})
                             */
                            $scope.getPreviousCompositions = function () {
                                if ($scope.compStart - $scope.pageSize < 0) {
                                    $scope.compStart = 0;
                                    $scope.compNext = $scope.pageSize;
                                } else {
                                    $scope.compStart -= $scope.pageSize;
                                    $scope.compNext = $scope.compStart + $scope.pageSize;
                                }
                                $scope.loadCompositions();
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#getNextCompositions
                             * @public
                             * @description Load next list of compositions to display on pager (number per page set by {@link hs.compositions.controller#page_size hs.compositions.controller#page_size})
                             */
                            $scope.getNextCompositions = function () {
                                if ($scope.compNext != 0) {
                                    $scope.compStart = Math.floor($scope.compNext / $scope.pageSize) * $scope.pageSize;

                                    if ($scope.compNext + $scope.pageSize > $scope.compositionsCount) {
                                        $scope.compNext = $scope.compositionsCount;
                                    } else {
                                        $scope.compNext += $scope.pageSize;
                                    }
                                    $scope.loadCompositions();
                                }
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#loadCompositions
                             * @public
                             * @description Load list of compositions according to current filter values and pager position (filter, keywords, current extent, start composition, compositions number per page). Display compositions extent in map
                             */
                            $scope.loadCompositions = function () {
                                Composition.loadCompositions({
                                    query: $scope.query,
                                    sortBy: $scope.sortBy,
                                    filterExtent: $scope.filterByExtent,
                                    keywords: $scope.keywords,
                                    start: $scope.compStart,
                                    limit: $scope.pageSize
                                });
                            }

                            $scope.$watch('data.next', function () {
                                $scope.compNext = $scope.data.next;
                            })

                            /**
                             * Handler of "Only mine" filter change, delete editable variable if needed
                             * @module hs.compositions.controller
                             * @function miniFilterChanged
                             * DEPRECATED?
                             */
                            $scope.mineFilterChanged = function () {
                                if (angular.isDefined($scope.query.editable) && $scope.query.editable == false) delete $scope.query.editable;
                            }

                            $scope.getPageSize = function () {
                                let listHeight = screen.height;
                                if ($mdMedia("gt-sm")) {
                                    let panel = angular.element('#sidenav-right');
                                    listHeight = panel.height();
                                }
                                $scope.pageSize = Math.round((listHeight - 180) / 60);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#filterChanged
                             * @public
                             * @description Reloads compositions from start, used as callback when filters are changed in view
                             */
                            $scope.filterChanged = function () {
                                Composition.resetCompositionCounter();
                                $scope.compStart = 0;
                                $scope.compNext = $scope.pageSize;
                                $scope.loadCompositions();
                            }

                             /**
                             * @ngdoc method
                             * @name hs.compositions.controller#confirmDelete
                             * @public
                             * @param {object} composition Composition selected for deletion
                             * @param {object} ev
                             * @description Display delete dialog of composition
                             */
                            $scope.confirmDelete = function (composition, ev) {
                                $scope.compositionToDelete = composition;
                                if(config.design == 'md')
                                    deleteDialogMd();
                                else
                                    deleteDialogBootstrap()
                            }

                            function deleteDialogBootstrap(ev) {
                                if (!$scope.$$phase) $scope.$digest();
                                $("#hs-dialog-area #composition-delete-dialog").remove();
                                var el = angular.element('
');
                                $("#hs-dialog-area").append(el)
                                $compile(el)($scope);
                            }

                            function deleteDialogMd(ev) {
                                $mdDialog.show({
                                    parent: angular.element('#hsContainer'),
                                    targetEvent: ev,
                                    clickOutsideToClose: true,
                                    escapeToClose: true,
                                    scope: $scope,
                                    preserveScope: true,
                                    templateUrl: 'materialComponents/panelContents/compositionLoadUnsavedDialog.html',
                                    controller: function DialogController($scope, $mdDialog) {
                                        $scope.closeDialog = function () {
                                            $mdDialog.hide();
                                        }
                                    }
                                });
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#delete
                             * @public
                             * @param {object} composition Composition selected for deletion
                             * @description Delete selected composition from project (including deletion from composition server, useful for user created compositions)
                             */
                            $scope.delete = function (composition) {
                                Composition.deleteComposition(composition);
                            }

                            /**
                             * Load selected composition for editing
                             * @module hs.compositions.controller
                             * @function edit
                             * @param {object} composition Selected composition
                             */
                            $scope.edit = function (composition) {
                                $scope.data.useCallbackForEdit = true;
                                Composition.loadComposition(composition);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#highlightComposition
                             * @public
                             * @param {Object} composition Composition to highlight
                             * @param {Boolean} state Target state of composition ( True - highlighted, False - normal)
                             * @description Highlight (or dim) composition, toogle visual state of composition extent on map
                             */
                            $scope.highlightComposition = function (composition, state) {
                                Composition.highlightComposition(composition, state);
                            }

                            $scope.$on('map.extent_changed', function (event, data, b) {
                                if (Core.mainpanel != 'composition_browser' && Core.mainpanel != 'composition') return;
                                if ($scope.filterByExtent) $scope.loadCompositions();
                            });

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#shareComposition
                             * @public
                             * @param {object} record Composition to share
                             * @description Prepare share object on server and display share dialog to share composition
                             */
                            $scope.shareComposition = function (record, $event) {
                                Composition.shareComposition(record);
                                if(config.design == 'md')
                                    shareDialogMd($event);
                                else
                                    shareDialogBootstrap()
                            }

                            function shareDialogBootstrap($event) {
                                $("#hs-dialog-area #composition-share-dialog").remove();
                                var el = angular.element('

');
                                $("#hs-dialog-area").append(el)
                                $compile(el)($scope);
                            }

                            function shareDialogMd($event) {
                                $mdDialog.show({
                                    parent: angular.element('#hsContainer'),
                                    targetEvent: $event,
                                    clickOutsideToClose: true,
                                    escapeToClose: true,
                                    scope: $scope,
                                    preserveScope: true,
                                    templateUrl: 'components/compositions/partials/dialog_sharemd.html',
                                    controller: function DialogController($scope, $mdDialog) {
                                        $scope.closeDialog = function () {
                                            $mdDialog.hide();
                                        }
                                    }
                                });
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#detailComposition
                             * @public
                             * @param {object} record Composition to show details
                             * @description Load info about composition through service and display composition info dialog
                             */
                            $scope.detailComposition = function (record, $event) {
                                $scope.info = Composition.getCompositionInfo(record);
                                if(config.design == 'md')
                                    infoDialogMD($event);
                                else
                                    infoDialogBootstrap();
                            }

                            function infoDialogBootstrap() {
                                if (!$scope.$$phase) $scope.$digest();
                                $("#hs-dialog-area #composition-info-dialog").remove();
                                var el = angular.element('
');
                                $("#hs-dialog-area").append(el)
                                $compile(el)($scope);
                            }

                            function infoDialogMD($event) {
                                var parentEl = angular.element('#hsContainer');
                                $mdDialog.show({
                                    parent: parentEl,
                                    targetEvent: $event,
                                    clickOutsideToClose: true,
                                    escapeToClose: true,
                                    template:
                                    '<md-dialog aria-label="List dialog">' +
                                    '  <md-dialog-content layout="column" layout-padding>' +
                                    '    <md-list>' +
                                    '
' +
                                    '       Abstract{{info.abstract}}' +
                                    '
' +
                                    '
' +
                                    '       Thumbnail{{info.thumbnail}}' +
                                    '
' +
                                    '
' +
                                    '       Extent{{info.extent}}' +
                                    '
' +
                                    '
' +
                                    '       Layer{{layer.title}}' +
                                    '
' +
                                    '    </md-list>' +
                                    '  </md-dialog-content>' +
                                    '  <md-dialog-actions>' +
                                    '    <md-button ng-click="closeDialog()" class="md-primary">' +
                                    '      Close' +
                                    '    </md-button>' +
                                    '  </md-dialog-actions>' +
                                    '</md-dialog>',
                                    locals: {
                                        info: $scope.info
                                    },
                                    controller: DialogController
                                });

                                function DialogController($scope, $mdDialog, info) {
                                    $scope.info = info;
                                    $scope.closeDialog = function () {
                                        $mdDialog.hide();
                                    }
                                }
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#loadComposition
                             * @public
                             * @param {object} record Composition to be loaded
                             * @description Load selected composition in map, if current composition was edited display Ovewrite dialog
                             */
                            $scope.loadComposition = function (record) {
                                Composition.loadCompositionParser(record);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#overwrite
                             * @public
                             * @description Load new composition without saving old composition
                             */
                            $scope.overwrite = function () {
                                Composition.loadComposition($scope.compositionToLoad, true);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#add
                             * @public
                             * @description Load new composition (with service_parser Load function) and merge it with old composition
                             */
                            $scope.add = function () {
                                Composition.loadComposition($scope.compositionToLoad, false);
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#save
                             * @public
                             * @description Open Status creator panel for saving old composition
                             */
                            $scope.save = function () {
                                Core.openStatusCreator();
                            }

                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#setSortAttribute
                             * @public
                             * @param {String} attribute Attribute by which compositions should be sorted (expected values: bbox, title, date)
                             * @description Set sort attribute for sorting composition list and reload compositions
                             */
                            $scope.setSortAttribute = function (attribute) {
                                $scope.sortBy = attribute;
                                $scope.loadCompositions();
                            }
                            /**
                             * @ngdoc method
                             * @name hs.compositions.controller#toggleKeywords
                             * @public
                             * @description Toogle keywords panel on compositions panel
                             */
                            $scope.toggleKeywords = function () {
                                $(".keywords-panel").slideToggle();
                            }

                            $scope.$on('CompositionLoaded', function () {
                                $('.tooltip').remove();
                                $('[data-toggle="tooltip"]').tooltip();
                            });

                            $scope.$on('compositions.composition_deleted', function () {
                                $("#hs-dialog-area #composition-delete-dialog").remove();
                            });

                            $scope.$on('loadComposition.notSaved', function (event, data) {
                                $scope.compositionToLoad = data.link;
                                if(config.design == 'md')
                                    loadUnsavedDialogMD();
                                else
                                    loadUnsavedDialogBootstrap();
                            });

                            function loadUnsavedDialogBootstrap(){
                                var dialog_id = '#composition-overwrite-dialog';
                                $scope.composition_name_to_be_loaded = data.title;
                                if ($("#hs-dialog-area " + dialog_id).length == 0) {
                                    var el = angular.element('
');
                                    $("#hs-dialog-area").append(el);
                                    $compile(el)($scope);
                                } else {
                                    $(dialog_id).modal('show');
                                }
                            }

                            function loadUnsavedDialogMD() {
                                $mdDialog.show({
                                    parent: angular.element('#hsContainer'),
                                    clickOutsideToClose: true,
                                    escapeToClose: true,
                                    scope: $scope,
                                    preserveScope: true,
                                    templateUrl: 'materialComponents/panelContents/compositionLoadUnsavedDialog.html',
                                    controller: function DialogController($scope, $mdDialog) {
                                        $scope.closeDialog = function () {
                                            $mdDialog.hide();
                                        }
                                    }
                                });
                            }

                            $scope.$on('core.mainpanel_changed', function (event) {
                                if (Core.mainpanel === 'composition_browser' || Core.mainpanel === 'composition') {
                                    $scope.loadCompositions();
                                }
                            });

                            $scope.getPageSize();
                            angular.element($window).resize(function () {
                                $scope.getPageSize();
                            });
                            $scope.$on("Core_sizeChanged", function () {
                                $scope.getPageSize();
                            });

                            $scope.$emit('scope_loaded', "Compositions");
                        }
                    ])
            }
        }

    })<|endoftext|>


<commit_before>{% load rosetta %}

google.setOnLoadCallback(function() {
    $('.location a').show().toggle(function() {
        $('.hide', $(this).parent()).show();
    }, function() {
        $('.hide', $(this).parent()).hide();
    });

{% if rosetta_settings.ENABLE_TRANSLATION_SUGGESTIONS %}
   {% if rosetta_settings.AZURE_CLIENT_SECRET %}
    $('a.suggest').click(function(e){
        e.preventDefault();
        var a = $(this);
        var str = a.html();
        var orig = $('.original .message', a.parents('tr')).html();
        var trans=$('textarea',a.parent());
        var sourceLang = '{{ rosetta_settings.MESSAGES_SOURCE_LANGUAGE_CODE }}';
        var destLang = '{{ rosetta_i18n_lang_code_normalized }}';

        orig = unescape(orig).replace(/
/g,'\n').replace(//,'').replace(/<\/code>/g,'').replace(/>/g,'>').replace(/</g,'<');
        a.attr('class','suggesting').html('...');

        $.getJSON("{% url 'rosetta.translate_text' %}", {
                from: sourceLang,
                to: destLang,
                text: orig
            },
            function(data) {
                if (data.success){
                    trans.val(unescape(data.translation).replace(/'/g,'\'').replace(/"/g,'"').replace(/%\s+(\([^\)]+\))\s*s/g,' %$1s '));
                    a.hide();
                } else {
                    a.text(data.error);
                }
            }
        );
    });
   {% elif rosetta_settings.YANDEX_TRANSLATE_KEY %}
    $('a.suggest').click(function(e){
        e.preventDefault();
        var a = $(this);
        var str = a.html();
        var orig = $('.original .message', a.parents('tr')).html();
        var trans=$('textarea',a.parent());
        var apiUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate";
        var destLangRoot = '{{ rosetta_i18n_lang_code }}'.split('-')[0];
        var lang = '{{ rosetta_settings.MESSAGES_SOURCE_LANGUAGE_CODE }}-' + destLangRoot;

        a.attr('class','suggesting').html('...');

        var apiData = {
            error: 'onTranslationError',
            success: 'onTranslationComplete',
            lang: lang,
            key: '{{ rosetta_settings.YANDEX_TRANSLATE_KEY }}',
            format: 'html',
            text: orig
        };

        $.ajax({
            url: apiUrl,
            data: apiData,
            dataType: 'jsonp',
            success: function(response) {
                if (response.code == 200) {
                    trans.val(response.text[0].replace(/
/g, '\n').replace(/<\/?code>/g, '').replace(/</g, '<').replace(/>/g, '>'));
                    a.hide();
                } else {
                    a.text(response);
                }
            },
            error: function(response) {
                a.text(response);
            }
        });
    });
   {% endif %}
{% endif %}

    $('td.plural').each(function(i) {
        var td = $(this), trY = parseInt(td.closest('tr').offset().top);
        $('textarea', $(this).closest('tr')).each(function(j) {
            var textareaY=  parseInt($(this).offset().top) - trY;
            $($('.part',td).get(j)).css('top',textareaY + 'px');
        });
    });

    $('.translation textarea').blur(function() {
        if($(this).val()) {
            $('.alert', $(this).parents('tr')).remove();
            var RX = /%(?:\([^\s\)]*\))?[sdf]|\{[\w\d_]+?\}/g,
                origs=$('.original', $(this).parents('tr')).html().match(RX),
                trads=$(this).val().match(RX),
                error = $('Unmatched variables');
            if (origs && trads) {
                for (var i = trads.length; i--;){
                    var key = trads[i];
                    if (-1 == $.inArray(key, origs)) {
                        $(this).before(error)
                        return false;
                    }
                }
                return true;
            } else {
                if (!(origs === null && trads === null)) {
                    $(this).before(error);
                    return false;
                }
            }
            return true;
        }
    });

    $('.translation textarea').eq(0).focus();

    $('#action-toggle').change(function(){
        jQuery('tbody td.c input[type="checkbox"]').each(function(i, e) {
            if($('#action-toggle').is(':checked')) {
                $(e).attr('checked', 'checked');
            } else {
                $(e).removeAttr('checked');
            }
        });
    });
    $('tbody .translation textarea').change(function () {
        var fuzzy = $(this).closest('tr').find('input[type="checkbox"]');
        if(fuzzy[0].checked){
            fuzzy[0].checked = false;
            fuzzy.removeAttr( 'checked')
        }

    })

});
<commit_msg>Ignore translator context hints checking unmatched variables.<commit_after>{% load rosetta %}

google.setOnLoadCallback(function() {
    $('.location a').show().toggle(function() {
        $('.hide', $(this).parent()).show();
    }, function() {
        $('.hide', $(this).parent()).hide();
    });

{% if rosetta_settings.ENABLE_TRANSLATION_SUGGESTIONS %}
   {% if rosetta_settings.AZURE_CLIENT_SECRET %}
    $('a.suggest').click(function(e){
        e.preventDefault();
        var a = $(this);
        var str = a.html();
        var orig = $('.original .message', a.parents('tr')).html();
        var trans=$('textarea',a.parent());
        var sourceLang = '{{ rosetta_settings.MESSAGES_SOURCE_LANGUAGE_CODE }}';
        var destLang = '{{ rosetta_i18n_lang_code_normalized }}';

        orig = unescape(orig).replace(/
/g,'\n').replace(//,'').replace(/<\/code>/g,'').replace(/>/g,'>').replace(/</g,'<');
        a.attr('class','suggesting').html('...');

        $.getJSON("{% url 'rosetta.translate_text' %}", {
                from: sourceLang,
                to: destLang,
                text: orig
            },
            function(data) {
                if (data.success){
                    trans.val(unescape(data.translation).replace(/'/g,'\'').replace(/"/g,'"').replace(/%\s+(\([^\)]+\))\s*s/g,' %$1s '));
                    a.hide();
                } else {
                    a.text(data.error);
                }
            }
        );
    });
   {% elif rosetta_settings.YANDEX_TRANSLATE_KEY %}
    $('a.suggest').click(function(e){
        e.preventDefault();
        var a = $(this);
        var str = a.html();
        var orig = $('.original .message', a.parents('tr')).html();
        var trans=$('textarea',a.parent());
        var apiUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate";
        var destLangRoot = '{{ rosetta_i18n_lang_code }}'.split('-')[0];
        var lang = '{{ rosetta_settings.MESSAGES_SOURCE_LANGUAGE_CODE }}-' + destLangRoot;

        a.attr('class','suggesting').html('...');

        var apiData = {
            error: 'onTranslationError',
            success: 'onTranslationComplete',
            lang: lang,
            key: '{{ rosetta_settings.YANDEX_TRANSLATE_KEY }}',
            format: 'html',
            text: orig
        };

        $.ajax({
            url: apiUrl,
            data: apiData,
            dataType: 'jsonp',
            success: function(response) {
                if (response.code == 200) {
                    trans.val(response.text[0].replace(/
/g, '\n').replace(/<\/?code>/g, '').replace(/</g, '<').replace(/>/g, '>'));
                    a.hide();
                } else {
                    a.text(response);
                }
            },
            error: function(response) {
                a.text(response);
            }
        });
    });
   {% endif %}
{% endif %}

    $('td.plural').each(function(i) {
        var td = $(this), trY = parseInt(td.closest('tr').offset().top);
        $('textarea', $(this).closest('tr')).each(function(j) {
            var textareaY=  parseInt($(this).offset().top) - trY;
            $($('.part',td).get(j)).css('top',textareaY + 'px');
        });
    });

    $('.translation textarea').blur(function() {
        if($(this).val()) {
            $('.alert', $(this).parents('tr')).remove();
            var RX = /%(?:\([^\s\)]*\))?[sdf]|\{[\w\d_]+?\}/g,
                origs=$(this).parents('tr').find('.original>.message').html().match(RX),
                trads=$(this).val().match(RX),
                error = $('Unmatched variables');
            if (origs && trads) {
                for (var i = trads.length; i--;){
                    var key = trads[i];
                    if (-1 == $.inArray(key, origs)) {
                        $(this).before(error)
                        return false;
                    }
                }
                return true;
            } else {
                if (!(origs === null && trads === null)) {
                    $(this).before(error);
                    return false;
                }
            }
            return true;
        }
    });

    $('.translation textarea').eq(0).focus();

    $('#action-toggle').change(function(){
        jQuery('tbody td.c input[type="checkbox"]').each(function(i, e) {
            if($('#action-toggle').is(':checked')) {
                $(e).attr('checked', 'checked');
            } else {
                $(e).removeAttr('checked');
            }
        });
    });
    $('tbody .translation textarea').change(function () {
        var fuzzy = $(this).closest('tr').find('input[type="checkbox"]');
        if(fuzzy[0].checked){
            fuzzy[0].checked = false;
            fuzzy.removeAttr( 'checked')
        }

    })

});
<|endoftext|>


<commit_before>const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(process.env.PORT || 3000);
<commit_msg>Serve static assets, refactor port<commit_after>const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(`${__dirname}/public`));

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server listening at ${PORT}..`);
});
<|endoftext|>


<commit_before>_commands =
{
	exec:function()
	{
		parent.addBufferString ( 'Executing...' );

		if ( $.trim (code) == '' )
		{
			parent.addBufferString ( 'Error: No Taktee code given.' );
			return true;
		}

		if ( typeof ( parent.sendCallback ) === 'function' )
		{
			parent.sendCallback.call ( this, code, parent );
		}

		parent.focusCommand();
		return true;
	},

	clr:function()
	{
		buffer.text ( bufferStr );
		parent.addBufferString ( 'type "-console help" for help, press ctrl+space for -console keyword.' );
		return true;
	},

	clrall:function()
	{
		_commands.clr();
		_commands.clrcode();
		return true;
	},

	clrcode:function()
	{
		code = '';
		currentline = 1;
		return true;
	},

	about:function()
	{
		parent.addBufferString ( "ABOUT\n"+_console['name']+" version: "+_console['ver']);
		parent.addBufferString ('copyright 2014 Junaid Atari (mj.atari@gmail.com)' );
		parent.addBufferString ('Licence: http://www.apache.org/licenses/LICENSE-2.0.html' );
		parent.addBufferString ('Github: Taktee Project' );
		return true;
	},

	showcode:function()
	{
		_code = $.trim(code);

		if (_code == '')
		{
			parent.addBufferString ( 'Error: Code is empty.' );
			return true;
		}

		codestr = '';

		$.each(_code.split("\n"),function(i,v){
			codestr+=(i+1)+'. ' + v + "\n";
		});

		parent.addBufferString ( '===================================================================' );
		parent.addBufferString ( $.trim(codestr) );
		parent.addBufferString ( '===================================================================' );
		return true;
	},

	help: function (){
		parent.addBufferString ( "HELP" );
		parent.addBufferString ( "Note: Only a subset of Console's commands are provided here." );
		parent.addBufferString ( "Given commands only work if following by '-console' and seperated by space" );
		parent.addBufferString ( "Example 1: -console about" );
		parent.addBufferString ( "Example 2: -console clr about" );
		parent.addBufferString ( "------------------------------------------------------------" );
		parent.addBufferString ( "about : About Console" );
		parent.addBufferString ( 'exec : Execute the Taktee code' );
		parent.addBufferString ( 'clr : Clear buffer output' );
		parent.addBufferString ( 'clrall : Clear buffer output and all the Taktee code' );
		parent.addBufferString ( 'clrcode : Clear all the Taktee code' );
		parent.addBufferString ( 'showcode : Print all the written code' );
		parent.addBufferString ( 'help : Show console help' );
		return true;
	}
};<commit_msg>Commands updated for v1.0.1<commit_after>_commands =
{
	exec:function()
	{
		parent.addBufferString ( 'Executing...' );

		if ( $.trim (code) == '' )
		{
			parent.addCodeBufferErrorString ( 'Error: No Taktee code given.' );
			return true;
		}

		if ( typeof ( parent.sendCallback ) === 'function' )
			parent.sendCallback.call ( this, code, parent );

		parent.focusCommand();
		return true;
	},

	clr:function()
	{
		parent.addIcmdBufferString ( 'Clearing buffer...' );
		setTimeout(function(){
			buffer.text ( bufferStr );
			parent.addCodeBufferStrNative ( 'type "-console help" for help, press ctrl+space for -console keyword.' );
		}, 200);
		return true;
	},

	clrall:function()
	{
		_commands.clr();
		_commands.clrcode();
		return true;
	},

	clrcode:function()
	{
		code = '';
		currentline = 1;
		return true;
	},

	about:function()
	{
		parent.addBufferString ( "ABOUT\n"+_console['name']+" version: "+_console['ver']);
		parent.addBufferString ('copyright 2014 Junaid Atari (mj.atari@gmail.com)' );
		parent.addBufferString ('Licence: http://www.apache.org/licenses/LICENSE-2.0.html' );
		parent.addBufferString ('View on Github: Taktee Project' );
		return true;
	},

	showcode:function()
	{
		_code = $.trim(code);

		if (_code == '')
		{
			parent.addCodeBufferErrorString ( 'Error: Code is empty.' );
			return true;
		}

		codestr = '';
		var _lins = 1;
		$.each(_code.split("\n"),function(i,v){
			_lins +=1;
			codestr += '' +(i+2)+'.    ' + v + "\n";
		});

		parent.addBufferString ( '===================================================================' );
		parent.addBufferString ( '1.  @{' );
		parent.addBufferString ( $.trim(codestr) );
		parent.addBufferString ( ''+(_lins+1)+'.  }' );
		parent.addBufferString ( '===================================================================' );
		return true;
	},

	help: function (){
		parent.addBufferString ( "HELP" );
		parent.addBufferString ( "Note: Only a subset of Console's commands are provided here." );
		parent.addBufferString ( "Given commands only work if following by '-console' and seperated by space" );
		parent.addBufferString ( "Example 1: -console about" );
		parent.addBufferString ( "Example 2: -console clr about" );
		parent.addBufferString ( "------------------------------------------------------------" );
		parent.addBufferString ( "about : About Console" );
		parent.addBufferString ( 'exec : Execute the Taktee code' );
		parent.addBufferString ( 'clr : Clear buffer output' );
		parent.addBufferString ( 'clrall : Clear buffer output and all the Taktee code' );
		parent.addBufferString ( 'clrcode : Clear all the Taktee code' );
		parent.addBufferString ( 'showcode : Print all the written code' );
		parent.addBufferString ( 'help : Show console help' );
		return true;
	}
};<|endoftext|>


<commit_before>(function() {
  var fs = require('fs');
  var arg = process.argv.slice(2);
  var compile = require('tumblr-theme-parser').compile;

  var themeHtml, data;

  switch (arg[0]) {
    case 'page':
      themeHtml = fs.readFileSync('./theme.html', 'utf8').toString();
      data = fs.readFileSync('./data-page.json', 'utf8').toString();
      break;
    case 'permalink':
      themeHtml = fs.readFileSync('./theme.html', 'utf8').toString();
      data = fs.readFileSync('./data-permalink.json', 'utf8').toString();
      break;
    default:
      console.log('Invalid argument specified.');
      process.exit(-1);
  }

  var compiledHtml = compile(themeHtml, JSON.parse(data));

  fs.writeFile('./compiled-theme.html', compiledHtml, function(err) {
    if (err) {
      return console.log(err);
    }
  });
})();
<commit_msg>Use `__dirname`<commit_after>(function() {
  var fs = require('fs');
  var arg = process.argv.slice(2);
  var compile = require('tumblr-theme-parser').compile;

  var themeHtml, data;

  switch (arg[0]) {
    case 'page':
      themeHtml = fs.readFileSync(__dirname + '/../theme.html', 'utf8').toString();
      data = fs.readFileSync(__dirname + '/../data-page.json', 'utf8').toString();
      break;
    case 'permalink':
      themeHtml = fs.readFileSync(__dirname + '/../theme.html', 'utf8').toString();
      data = fs.readFileSync(__dirname + '/../data-permalink.json', 'utf8').toString();
      break;
    default:
      console.log('Invalid argument specified.');
      process.exit(-1);
  }

  var compiledHtml = compile(themeHtml, JSON.parse(data));

  fs.writeFile(__dirname + '/../compiled-theme.html', compiledHtml, function(err) {
    if (err) {
      return console.log(err);
    }
  });
})();
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Nicolas Froidure
 *
 * This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 3. It is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * This object is NodeJs independent
 *
 * Important warning ! Should evaluate the right member first in case of backward referencing with * or + in the two sides
 *
 */

// AMD + global + NodeJS : You can use this object by inserting a script
// or using an AMD loader (like RequireJS) or using NodeJS
(function(root,define){ define([], function() {
// START: Module logic start

	// Constructor
	function VarStreamReader (scope, prop, strictMode) {
		// Keep a ref to the root scope
		this.rootScope={root:scope,prop:prop};
		// Save the strictMode param
		this.strictMode=(strictMode?strictMode:false);
		// Store current scopes for backward references
		this.previousNodes=new Array();
		// The current readed var
		this.currentVar=new Array();
		// The parse state
		this.state=PARSE_NEWLINE; // Marker to know if the next chunk begins by a multine value
		// The current values
		this.leftValue='';
		this.rightValue='';
		this.operator='';
		this.escaped=false;
	}

	// Constants
		// Chars
	var CHR_ENDL = '\n'
		, CHR_CR = '\r'
		, CHR_SEP = '.'
		, CHR_BCK = '^'
		, CHR_EQ = '='
		, CHR_ESC = '\\'
		, CHR_PLU = '+'
		, CHR_MIN = '-'
		, CHR_MUL = '*'
		, CHR_DIV = '/'
		, CHR_MOD = '%'
		, CHR_REF = '&'
		, CHR_NEW = '!'
		, CHR_COM = '#'
		// Chars sets
		, EQ_OPS = [CHR_PLU,CHR_MIN,CHR_MUL,CHR_DIV,CHR_MOD,CHR_REF]
		, ARRAY_OPS = [CHR_PLU,CHR_MUL,CHR_NEW]
		, ARRAY_NODE_CHARS = /^[0-9]+$/
		, PROP_NODE_CHARS = /^[a-zA-Z0-9]+$/
		, BCK_CHARS = /^\^[0-9]*$/
		// Parsing status
		, PARSE_NEWLINE = 1
		, PARSE_LVAL = 2
		, PARSE_OPERATOR = 3
		, PARSE_RVAL = 4
		, PARSE_MLSTRING = 5
		, PARSE_COMMENT = 6
		, PARSE_SILENT = 7
		;

	VarStreamReader.prototype.resolveScope = function (val) {
		var nodes=val.split(CHR_SEP), scope=this.rootScope, n;
		// Looking for backward refs in the first node
		if(nodes[0]&&nodes[0][0]==CHR_BCK) {
			// if no previous nodes
			if(0===this.previousNodes.length) {
				if(this.strictMode) {
					throw Error('Backward reference given while no previous nodes.');
				}
				if(1===nodes.length||1===nodes[i].length) {
					return null;
				} else {
					nodes.shift();
				}
			}
			// if no numbers adding every previous nodes
			if(nodes[0]==CHR_BCK) {
				n=this.previousNodes.length-1;
			// if numbers
			} else {
				// check it
				if(BCK_CHARS.test(nodes[0])) {
					if(this.strictMode) {
						throw Error('Malformed backward reference.');
					}
					return null;
				}
				var n=parseInt(nodes[0].substring(1),10);
			}
			if(n>this.previousNodes.length) {
				if(this.strictMode) {
					throw Error('Backward reference index is greater than the previous'
						+' node max index.');
				}
				return null;
			}
			this.previousNodes.length=n+1;
			nodes.unshift.apply(nodes,this.previousNodes);
		}
		// Looping throught each nodes
		for(var i=0, j=nodes.length; i<j; i++) {
			// Checking if the node is not empty
			if(''===nodes[i]) {
				if(this.strictMode) {
					throw Error('The leftValue can\'t have empty nodes.');
				}
				return null;
			}
			// Array operators
			if(ARRAY_OPS.indexOf(nodes[i])||ARRAY_NODE_CHARS.test(nodes[i])) {
				// Ensure the scope is an array
				if('undefined'=== typeof scope.root[scope.prop]
					||!(scope.root[scope.prop] instanceof Array)) {
						scope.root[scope.prop]=new Array();
				}
				if(nodes[i]===CHR_PLU) {
						nodes[i]=scope.root[scope.prop].length;
				}
				if(nodes[i]===CHR_MUL) {
					nodes[i]=scope.root[scope.prop].length-1;
				}
				if(nodes[i]===CHR_NEW) {
					nodes[i]=scope.root[scope.prop].length=0;
				}
			} else {
				// Checking node chars
				if(!PROP_NODE_CHARS.test(nodes[i])) {
					if(this.strictMode) {
						throw Error('Illegal chars found in a the node "'+nodes[i]+'".');
					}
					return null;
				}
				// Ensure the scope is an object
				if('undefined'=== typeof scope.root[scope.prop]
					||!(scope.root[scope.prop] instanceof Object)) {
						scope.root[scope.prop]=new Object();
				}
			}
			// Resolving the node scope
			scope={
				root : scope.root[scope.prop],
				prop : nodes[i]
			};
		}
		this.previousNodes=nodes.slice(0);
		return scope;
	};

	VarStreamReader.prototype.read = function (chunk) {
		// Looping throught chunk chars
		for(var i=0, j=chunk.length; i<j; i++) {
			// detect escaped chars
			if(chunk[i]===CHR_ESC
				&&(
					this.state===PARSE_RVAL
					||this.state===PARSE_SILENT
					||this.state===PARSE_MLSTRING
					)
				) {
				if(this.escaped) {
					this.escaped=false;
				} else {
					this.escaped=true;
					continue;
				}
			}
			// parsing chars according to the current state
			switch(this.state) {
				// Continue while newlines
				case PARSE_NEWLINE:
					this.escaped=false;
					this.operator='';
					this.leftValue='';
					this.rightValue='';
					if(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						continue;
					}
				// Read left value content
				case PARSE_LVAL:
					// Detect comments
					if(chunk[i]===CHR_COM) {
						this.state=PARSE_COMMENT;
						continue;
					}
					// Detect special operators
					if(-1!==EQ_OPS.indexOf(chunk[i])) {
						this.state=PARSE_OPERATOR;
						this.operator=chunk[i];
						continue;
					}
					// Detect the = operator
					if(CHR_EQ===chunk[i]) {
						this.state=PARSE_RVAL;
						this.operator=chunk[i];
						continue;
					}
					// Fail if a new line is found
					if(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						if(this.strictMode) {
							throw Error('Unexpected new line found while parsing '
							+' a leftValue.');
						}
						this.state=PARSE_NEWLINE;
						continue;
					}
					// Store LVAL chars
					this.state=PARSE_LVAL;
					this.leftValue+=chunk[i];
					continue;
				// Read right value content
				case PARSE_RVAL:
					// Left value should not be empty
					if(''===this.leftValue) {
						if(this.strictMode) {
							throw Error('Found an empty leftValue.');
						}
						this.state=PARSE_SILENT;
					}
					// Stop if a new line is found
					if(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						// rightValue can be empty only with the = operator
						if(this.operator!=CHR_EQ&&''===this.rightValue) {
							if(this.strictMode) {
								throw Error('Found an empty rightValue.');
							}
							this.state=PARSE_NEWLINE;
							continue;
						}
						// Compute rval
						// if it's a ref
						if(this.operator===CHR_REF) {
							this.rightValue=this.resolveScope(this.rightValue);
						// Booleans
						} else if('true'===this.rightValue) {
							this.rightValue=true;
						} else if('false'===this.rightValue) {
							this.rightValue=false;
						// Numbers
						} else if('NaN'===this.rightValue) {
							this.rightValue=NaN;
						} else if(/^\-?([0-9]+(\.[0-9]+)?|Infinity)$/
							.test(this.rightValue)) {
							this.rightValue=Number(this.rightValue);
						}
						// Compute lval
						this.leftValue=this.resolveScope(this.leftValue);
						// set rval in lval (with operators)
						switch(this.operator) {
							case CHR_REF:
								this.leftValue.root[this.leftValue.prop]=
									this.rightValue.root[this.rightValue.prop];
							break;
							case CHR_EQ:
								this.leftValue.root[this.leftValue.prop]=this.rightValue;
							break;
							case CHR_PLU:
								this.leftValue.root[this.leftValue.prop]+=this.rightValue;
							break;
							case CHR_MIN:
								this.leftValue.root[this.leftValue.prop]-=this.rightValue;
							break;
							case CHR_MUL:
								this.leftValue.root[this.leftValue.prop]*=this.rightValue;
							break;
							case CHR_DIV:
								this.leftValue.root[this.leftValue.prop]/=this.rightValue;
							break;
							case CHR_MOD:
								this.leftValue.root[this.leftValue.prop]%=this.rightValue;
							break;
						}
						this.currentVar=this.rightValue;
						// if the newline was escaped, continue to read the string
						if(this.escaped) {
							this.escaped=false;
							this.state=PARSE_MLSTRING;
							this.leftValue.root[this.leftValue.prop]+=chunk[i];
						} else {
							this.state=PARSE_NEWLINE;
						}
						continue;
					}
					// Store RVAL chars
					this.rightValue+=chunk[i];
					continue;
				// Parse the content of a multiline value
				case PARSE_MLSTRING:
					if((!this.escaped)&&(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR)) {
						this.state=PARSE_NEWLINE;
					} else {
						if(this.escaped) {
							this.escaped=false;
						}
						this.leftValue.root[this.leftValue.prop]+=chunk[i];
					}
					continue;
				// Finding the = char after an operator
				case PARSE_OPERATOR:
					if(chunk[i]===CHR_EQ) {
						this.state=PARSE_RVAL;
						continue;
					}
					if(this.strictMode) {
						throw Error('Unexpected char after the "'+this.operator+'"'+
						' operator. Expected =, found '+chunk[i]+'.');
					}
					if(chunk[i]===CHR_EQ||chunk[i]===CHR_CR) {
						this.state=PARSE_NEWLINE;
					} else {
						this.state=PARSE_SILENT;
					}
					continue;
				// Parsing a comment content
				case PARSE_COMMENT:
					if(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						this.state=PARSE_NEWLINE;
					}
					continue;
				// Something was wrong, waiting for a newline to continue parsing
				case PARSE_SILENT:
					if(true!==this.escaped&&chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						this.state=PARSE_NEWLINE;
					}
					this.escaped=false;
					continue;
			}
		}
	};

// END: Module logic end

	return VarStreamReader;

});})(this,typeof define === 'function' && define.amd ?
	// AMD
	define :
	// NodeJS
	(typeof exports === 'object'?function (name, deps, factory) {
		var root=this;
		if(typeof name === 'object') {
			factory=deps; deps=name;
		}
		module.exports=factory.apply(this, deps.map(function(dep){
			return require(dep);
		}));
	}:
	// Global
	function (name, deps, factory) {
		var root=this;
		if(typeof name === 'object') {
			factory=deps; deps=name;
		}
		this.VarStreamReader=factory.apply(this, deps.map(function(dep){
			return root[dep.substring(dep.lastIndexOf('/')+1)];
		}));
	}.bind(this)
	)
);
<commit_msg>Fix for null values<commit_after>/*
 * Copyright (C) 2012 Nicolas Froidure
 *
 * This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 3. It is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * This object is NodeJs independent
 *
 * Important warning ! Should evaluate the right member first in case of backward referencing with * or + in the two sides
 *
 */

// AMD + global + NodeJS : You can use this object by inserting a script
// or using an AMD loader (like RequireJS) or using NodeJS
(function(root,define){ define([], function() {
// START: Module logic start

	// Constructor
	function VarStreamReader (scope, prop, strictMode) {
		// Keep a ref to the root scope
		this.rootScope={root:scope,prop:prop};
		// Save the strictMode param
		this.strictMode=(strictMode?strictMode:false);
		// Store current scopes for backward references
		this.previousNodes=new Array();
		// The current readed var
		this.currentVar=new Array();
		// The parse state
		this.state=PARSE_NEWLINE; // Marker to know if the next chunk begins by a multine value
		// The current values
		this.leftValue='';
		this.rightValue='';
		this.operator='';
		this.escaped=false;
	}

	// Constants
		// Chars
	var CHR_ENDL = '\n'
		, CHR_CR = '\r'
		, CHR_SEP = '.'
		, CHR_BCK = '^'
		, CHR_EQ = '='
		, CHR_ESC = '\\'
		, CHR_PLU = '+'
		, CHR_MIN = '-'
		, CHR_MUL = '*'
		, CHR_DIV = '/'
		, CHR_MOD = '%'
		, CHR_REF = '&'
		, CHR_NEW = '!'
		, CHR_COM = '#'
		// Chars sets
		, EQ_OPS = [CHR_PLU,CHR_MIN,CHR_MUL,CHR_DIV,CHR_MOD,CHR_REF]
		, ARRAY_OPS = [CHR_PLU,CHR_MUL,CHR_NEW]
		, ARRAY_NODE_CHARS = /^[0-9]+$/
		, PROP_NODE_CHARS = /^[a-zA-Z0-9]+$/
		, BCK_CHARS = /^\^[0-9]*$/
		// Parsing status
		, PARSE_NEWLINE = 1
		, PARSE_LVAL = 2
		, PARSE_OPERATOR = 3
		, PARSE_RVAL = 4
		, PARSE_MLSTRING = 5
		, PARSE_COMMENT = 6
		, PARSE_SILENT = 7
		;

	VarStreamReader.prototype.resolveScope = function (val) {
		var nodes=val.split(CHR_SEP), scope=this.rootScope, n;
		// Looking for backward refs in the first node
		if(nodes[0]&&nodes[0][0]==CHR_BCK) {
			// if no previous nodes
			if(0===this.previousNodes.length) {
				if(this.strictMode) {
					throw Error('Backward reference given while no previous nodes.');
				}
				if(1===nodes.length||1===nodes[i].length) {
					return null;
				} else {
					nodes.shift();
				}
			}
			// if no numbers adding every previous nodes
			if(nodes[0]==CHR_BCK) {
				n=this.previousNodes.length-1;
			// if numbers
			} else {
				// check it
				if(BCK_CHARS.test(nodes[0])) {
					if(this.strictMode) {
						throw Error('Malformed backward reference.');
					}
					return null;
				}
				var n=parseInt(nodes[0].substring(1),10);
			}
			if(n>this.previousNodes.length) {
				if(this.strictMode) {
					throw Error('Backward reference index is greater than the previous'
						+' node max index.');
				}
				return null;
			}
			this.previousNodes.length=n+1;
			nodes.unshift.apply(nodes,this.previousNodes);
		}
		// Looping throught each nodes
		for(var i=0, j=nodes.length; i<j; i++) {
			// Checking if the node is not empty
			if(''===nodes[i]) {
				if(this.strictMode) {
					throw Error('The leftValue can\'t have empty nodes.');
				}
				return null;
			}
			// Array operators
			if(ARRAY_OPS.indexOf(nodes[i])||ARRAY_NODE_CHARS.test(nodes[i])) {
				// Ensure the scope is an array
				if('undefined'=== typeof scope.root[scope.prop]
					||!(scope.root[scope.prop] instanceof Array)) {
						scope.root[scope.prop]=new Array();
				}
				if(nodes[i]===CHR_PLU) {
						nodes[i]=scope.root[scope.prop].length;
				}
				if(nodes[i]===CHR_MUL) {
					nodes[i]=scope.root[scope.prop].length-1;
				}
				if(nodes[i]===CHR_NEW) {
					nodes[i]=scope.root[scope.prop].length=0;
				}
			} else {
				// Checking node chars
				if(!PROP_NODE_CHARS.test(nodes[i])) {
					if(this.strictMode) {
						throw Error('Illegal chars found in a the node "'+nodes[i]+'".');
					}
					return null;
				}
				// Ensure the scope is an object
				if('undefined'=== typeof scope.root[scope.prop]
					||!(scope.root[scope.prop] instanceof Object)) {
						scope.root[scope.prop]=new Object();
				}
			}
			// Resolving the node scope
			scope={
				root : scope.root[scope.prop],
				prop : nodes[i]
			};
		}
		this.previousNodes=nodes.slice(0);
		return scope;
	};

	VarStreamReader.prototype.read = function (chunk) {
		// Looping throught chunk chars
		for(var i=0, j=chunk.length; i<j; i++) {
			// detect escaped chars
			if(chunk[i]===CHR_ESC
				&&(
					this.state===PARSE_RVAL
					||this.state===PARSE_SILENT
					||this.state===PARSE_MLSTRING
					)
				) {
				if(this.escaped) {
					this.escaped=false;
				} else {
					this.escaped=true;
					continue;
				}
			}
			// parsing chars according to the current state
			switch(this.state) {
				// Continue while newlines
				case PARSE_NEWLINE:
					this.escaped=false;
					this.operator='';
					this.leftValue='';
					this.rightValue='';
					if(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						continue;
					}
				// Read left value content
				case PARSE_LVAL:
					// Detect comments
					if(chunk[i]===CHR_COM) {
						this.state=PARSE_COMMENT;
						continue;
					}
					// Detect special operators
					if(-1!==EQ_OPS.indexOf(chunk[i])) {
						this.state=PARSE_OPERATOR;
						this.operator=chunk[i];
						continue;
					}
					// Detect the = operator
					if(CHR_EQ===chunk[i]) {
						this.state=PARSE_RVAL;
						this.operator=chunk[i];
						continue;
					}
					// Fail if a new line is found
					if(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						if(this.strictMode) {
							throw Error('Unexpected new line found while parsing '
							+' a leftValue.');
						}
						this.state=PARSE_NEWLINE;
						continue;
					}
					// Store LVAL chars
					this.state=PARSE_LVAL;
					this.leftValue+=chunk[i];
					continue;
				// Read right value content
				case PARSE_RVAL:
					// Left value should not be empty
					if(''===this.leftValue) {
						if(this.strictMode) {
							throw Error('Found an empty leftValue.');
						}
						this.state=PARSE_SILENT;
					}
					// Stop if a new line is found
					if(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						// rightValue can be empty only with the = operator
						if(this.operator!=CHR_EQ&&''===this.rightValue) {
							if(this.strictMode) {
								throw Error('Found an empty rightValue.');
							}
							this.state=PARSE_NEWLINE;
							continue;
						}
						// Compute rval
						// if it's a ref
						if(this.operator===CHR_REF) {
							this.rightValue=this.resolveScope(this.rightValue);
						// null
						} else if('null'===this.rightValue) {
							this.rightValue=null;
						// Booleans
						} else if('true'===this.rightValue) {
							this.rightValue=true;
						} else if('false'===this.rightValue) {
							this.rightValue=false;
						// Numbers
						} else if('NaN'===this.rightValue) {
							this.rightValue=NaN;
						} else if(/^\-?([0-9]+(\.[0-9]+)?|Infinity)$/
							.test(this.rightValue)) {
							this.rightValue=Number(this.rightValue);
						}
						// Compute lval
						this.leftValue=this.resolveScope(this.leftValue);
						// set rval in lval (with operators)
						switch(this.operator) {
							case CHR_REF:
								this.leftValue.root[this.leftValue.prop]=
									this.rightValue.root[this.rightValue.prop];
							break;
							case CHR_EQ:
								this.leftValue.root[this.leftValue.prop]=this.rightValue;
							break;
							case CHR_PLU:
								this.leftValue.root[this.leftValue.prop]+=this.rightValue;
							break;
							case CHR_MIN:
								this.leftValue.root[this.leftValue.prop]-=this.rightValue;
							break;
							case CHR_MUL:
								this.leftValue.root[this.leftValue.prop]*=this.rightValue;
							break;
							case CHR_DIV:
								this.leftValue.root[this.leftValue.prop]/=this.rightValue;
							break;
							case CHR_MOD:
								this.leftValue.root[this.leftValue.prop]%=this.rightValue;
							break;
						}
						this.currentVar=this.rightValue;
						// if the newline was escaped, continue to read the string
						if(this.escaped) {
							this.escaped=false;
							this.state=PARSE_MLSTRING;
							this.leftValue.root[this.leftValue.prop]+=chunk[i];
						} else {
							this.state=PARSE_NEWLINE;
						}
						continue;
					}
					// Store RVAL chars
					this.rightValue+=chunk[i];
					continue;
				// Parse the content of a multiline value
				case PARSE_MLSTRING:
					if((!this.escaped)&&(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR)) {
						this.state=PARSE_NEWLINE;
					} else {
						if(this.escaped) {
							this.escaped=false;
						}
						this.leftValue.root[this.leftValue.prop]+=chunk[i];
					}
					continue;
				// Finding the = char after an operator
				case PARSE_OPERATOR:
					if(chunk[i]===CHR_EQ) {
						this.state=PARSE_RVAL;
						continue;
					}
					if(this.strictMode) {
						throw Error('Unexpected char after the "'+this.operator+'"'+
						' operator. Expected =, found '+chunk[i]+'.');
					}
					if(chunk[i]===CHR_EQ||chunk[i]===CHR_CR) {
						this.state=PARSE_NEWLINE;
					} else {
						this.state=PARSE_SILENT;
					}
					continue;
				// Parsing a comment content
				case PARSE_COMMENT:
					if(chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						this.state=PARSE_NEWLINE;
					}
					continue;
				// Something was wrong, waiting for a newline to continue parsing
				case PARSE_SILENT:
					if(true!==this.escaped&&chunk[i]===CHR_ENDL||chunk[i]===CHR_CR) {
						this.state=PARSE_NEWLINE;
					}
					this.escaped=false;
					continue;
			}
		}
	};

// END: Module logic end

	return VarStreamReader;

});})(this,typeof define === 'function' && define.amd ?
	// AMD
	define :
	// NodeJS
	(typeof exports === 'object'?function (name, deps, factory) {
		var root=this;
		if(typeof name === 'object') {
			factory=deps; deps=name;
		}
		module.exports=factory.apply(this, deps.map(function(dep){
			return require(dep);
		}));
	}:
	// Global
	function (name, deps, factory) {
		var root=this;
		if(typeof name === 'object') {
			factory=deps; deps=name;
		}
		this.VarStreamReader=factory.apply(this, deps.map(function(dep){
			return root[dep.substring(dep.lastIndexOf('/')+1)];
		}));
	}.bind(this)
	)
);
<|endoftext|>


<commit_before>console.log('Welcome to Moustacheminer Server Services');

//	const config = require('config');
//	const express = require('express');
const path = require('path');
const i18n = require('i18n');
require('./discord');

i18n.configure({
	directory: path.join(__dirname, '..', 'locales'),
	cookie: 'lang',
	defaultLocale: 'en-gb',
	autoReload: true,
	updateFiles: false
});
//
//	const app = express();
//
//	app.enable('trust proxy')
//		.set('views', path.join(__dirname, 'dynamic'))
//		.set('view engine', 'pug')
//		.get('/', (req, res) => {
//			res.render('index');
//		})
//		.use(express.static(path.join(__dirname, 'static')))
//		.use('*', (req, res) => res.status(404).render('error'));
//
//	console.log('Listening on', config.get('webserver').port);
//	app.listen(config.get('webserver').port);

process.on('unhandledRejection', (reason) => {
	console.dir(reason);
});
<commit_msg>ECONNRESET is not gud, but we catch<commit_after>console.log('Welcome to Moustacheminer Server Services');

//	const config = require('config');
//	const express = require('express');
const path = require('path');
const i18n = require('i18n');
require('./discord');

i18n.configure({
	directory: path.join(__dirname, '..', 'locales'),
	cookie: 'lang',
	defaultLocale: 'en-gb',
	autoReload: true,
	updateFiles: false
});
//
//	const app = express();
//
//	app.enable('trust proxy')
//		.set('views', path.join(__dirname, 'dynamic'))
//		.set('view engine', 'pug')
//		.get('/', (req, res) => {
//			res.render('index');
//		})
//		.use(express.static(path.join(__dirname, 'static')))
//		.use('*', (req, res) => res.status(404).render('error'));
//
//	console.log('Listening on', config.get('webserver').port);
//	app.listen(config.get('webserver').port);

process.on('unhandledRejection', (reason) => {
	console.dir(reason);
});

process.on('uncaughtException', (err) => {
	if (err.code === 'ECONNRESET') {
		console.log('ECONNREST occured, stream broke');
	} else {
		console.log('Moustacheminer Server Services has crashed!'.red);
		console.log(err.stack);
		process.exit(1);
	}
});
<|endoftext|>