<commit_before>/* eslint-env node */
'use strict';

var webpack = require('webpack');

module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    eslint: {
      target: ['./src/javascripts/**/*.js']
    },
    sass: {
      options: {
        sourceMap: true
      },
      dist: {
        files: {
          './dist/assets/main.css': './src/stylesheets/**/*.scss'
        }
      }
    },
    webpack: {
      build: {
        progress: true,
        entry: {
          app: './src/javascripts/index.js'
        },
        output: {
          path: './dist/assets',
          filename: 'bundle.js',
          sourceMapFilename: '[file].map'
        },
        module: {
          loaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
              presets: ['es2015']
            }
          }]
        },
        resolve: {
          extensions: ['', '.js']
        },
        devtool: '#source-map',
        plugins: [
          new webpack.optimize.UglifyJsPlugin({
            compress: {
              warnings: false
            }
          })
        ]
      }
    },
    handlebars: {
      compile: {
        files: {
          'dist/assets/templates.js': 'src/templates/**/*.hbs'
        },
        options: {
          namespace: 'Templates',
          partialsUseNamespace: true
        }
      }
    },
    watch: {
      css: {
        files: [
          './src/stylesheets/**/*.scss'
        ],
        tasks: ['sass']
      },
      js: {
        files: [
          './src/javascripts/**/*.js'
        ],
        tasks: ['eslint', 'webpack']
      },
      hbs: {
        files: [
          './src/templates/**/*.hbs'
        ],
        tasks: ['handlebars']
      }
    }
  });

  grunt.registerTask('build', ['sass', 'handlebars', 'eslint', 'webpack']);
  grunt.registerTask('default', ['build']);
};
<commit_msg>Add extra handlebars extensions<commit_after>/* eslint-env node */
'use strict';

var webpack = require('webpack');

module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    eslint: {
      target: ['./src/javascripts/**/*.js']
    },
    sass: {
      options: {
        sourceMap: true
      },
      dist: {
        files: {
          './dist/assets/main.css': './src/stylesheets/**/*.scss'
        }
      }
    },
    webpack: {
      build: {
        progress: true,
        entry: {
          app: './src/javascripts/index.js'
        },
        output: {
          path: './dist/assets',
          filename: 'bundle.js',
          sourceMapFilename: '[file].map'
        },
        module: {
          loaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
              presets: ['es2015']
            }
          }]
        },
        resolve: {
          extensions: ['', '.js']
        },
        devtool: '#source-map',
        plugins: [
          new webpack.optimize.UglifyJsPlugin({
            compress: {
              warnings: false
            }
          })
        ]
      }
    },
    handlebars: {
      compile: {
        files: {
          'dist/assets/templates.js': 'src/templates/**/*.hbs'
        },
        options: {
          namespace: 'Templates',
          partialsUseNamespace: true
        }
      }
    },
    watch: {
      css: {
        files: [
          './src/stylesheets/**/*.scss'
        ],
        tasks: ['sass']
      },
      js: {
        files: [
          './src/javascripts/**/*.js'
        ],
        tasks: ['eslint', 'webpack']
      },
      hbs: {
        files: [
          './src/templates/**/*.hbs',
          './src/templates/**/*.hdbs',
          './src/templates/**/*.handlebars'
        ],
        tasks: ['handlebars']
      }
    }
  });

  grunt.registerTask('build', ['sass', 'handlebars', 'eslint', 'webpack']);
  grunt.registerTask('default', ['build']);
};
<|endoftext|>


<commit_before>module.exports = {
  stripPrefix: 'build/',
  staticFileGlobs: [
    'build/*.html',
    'build/manifext.json',
    'build/static/**/!(*map*)'
  ],
  navigateFallback: 'index.html',
  dontCacheBustUrlsMatching: /\.\w{8}\./,
  swFilePath: 'build/service-worker.js'
};
<commit_msg>cache busting<commit_after>module.exports = {
  stripPrefix: 'build/',
  staticFileGlobs: [
    'build/*.html',
    'build/manifext.json',
    'build/static/**/!(*map*)'
  ],
  navigateFallback: 'index.html',
  swFilePath: 'build/service-worker.js'
};
<|endoftext|>


<commit_before> 뢮   ࠭ (ECHO) 祭.
<commit_msg>Delete everything from .js file<commit_after><|endoftext|>


<commit_before>// flavors for cookie module
flavor = [
"tasty",
"delectable",
"delicious",
"yummy",
"scrumptious",
"luscious",
"awesome",
"succulent",
"savory",
"sweet",
"spicy", // lol
"mouthwatering"
];
<commit_msg>remove spicy thing<commit_after>// flavors for cookie module
flavor = [
"tasty",
"delectable",
"delicious",
"yummy",
"scrumptious",
"luscious",
"awesome",
"succulent",
"savory",
"sweet",
"mouthwatering"
];
<|endoftext|>


<commit_before>import _isFunction from 'lodash-es/isFunction';
import _map from 'lodash-es/map';
import _filter from 'lodash-es/filter';
import _flatten from 'lodash-es/flatten';
import _flattenDeep from 'lodash-es/flattenDeep';
import _uniq from 'lodash-es/uniq';
import _uniqWith from 'lodash-es/uniqWith';

import { dispatch as d3_dispatch } from 'd3-dispatch';

import { geoExtent } from '../geo';
import { osmEntity } from '../osm';
import { utilRebind } from '../util/rebind';
import * as Validations from '../validations/index';

export function coreValidator(context) {
    var dispatch = d3_dispatch('reload');
    var self = {};
    var _issues = [];
    var _issuesByEntityID = {};

    var validations = _filter(Validations, _isFunction).reduce(function(obj, validation) {
        var func = validation();
        obj[func.type] = func;
        return obj;
    }, {});

    var entityValidationIDs = [];
    var changesValidationIDs = [];

    for (var key in validations) {
        var validation = validations[key];
        if (validation.inputType && validation.inputType === 'changes') {
            changesValidationIDs.push(key);
        } else {
            entityValidationIDs.push(key);
        }
    }

    //self.featureApplicabilityOptions = ['edited', 'all'];

    /*var featureApplicability = context.storage('issue-features') || 'edited';

    self.getFeatureApplicability = function() {
        return featureApplicability;
    };

    self.setFeatureApplicability = function(applicability) {
        featureApplicability = applicability;
        context.storage('issue-features', applicability);
    };*/

    self.getIssues = function() {
        return _issues;
    };

    self.getWarnings = function() {
        return _issues.filter(function(d) { return d.severity === 'warning'; });
    };

    self.getErrors = function() {
        return _issues.filter(function(d) { return d.severity === 'error'; });
    };

    self.getIssuesForEntityWithID = function(entityID) {
        if (!context.hasEntity(entityID)) return [];
        var entity = context.entity(entityID);
        var key = osmEntity.key(entity);

        if (!_issuesByEntityID[key]) {
            _issuesByEntityID[key] = validateEntity(entity);
        }
        return _issuesByEntityID[key];
    };

    function validateEntity(entity) {
        var _issues = [];
        var ran = {};

        // runs validation and appends resulting issues, returning true if validation passed
        function runValidation(which) {
            if (ran[which]) return true;

            var fn = validations[which];
            var typeIssues = fn(entity, context);
            _issues = _issues.concat(typeIssues);
            ran[which] = true;   // mark this validation as having run
            return !typeIssues.length;
        }

        if (entity.type === 'relation') {
            if (!runValidation('old_multipolygon')) {
                // don't flag missing tags if they are on the outer way
                ran.missing_tag = true;
            }
        }

        // other validations require feature to be tagged
        if (!runValidation('missing_tag')) return _issues;

        if (entity.type === 'way') {
            runValidation('crossing_ways');

            // only check for disconnected way if no almost junctions
            if (runValidation('almost_junction')) {
                runValidation('disconnected_way');
            } else {
                ran.disconnected_way = true;
            }

            runValidation('tag_suggests_area');
        }

        // run all validations not yet run manually
        entityValidationIDs.forEach(runValidation);

        return _issues;
    }

    self.validate = function() {
        _issuesByEntityID = {};   // clear cached
        _issues = [];

        for (var validationIndex in validations) {
            if (validations[validationIndex].reset) {
                validations[validationIndex].reset();
            }
        }

        var history = context.history();
        var changes = history.changes();
        var entitiesToCheck = changes.created.concat(changes.modified);
        var graph = history.graph();

        _issues = _flatten(_map(changesValidationIDs, function(ruleID) {
            var validation = validations[ruleID];
            return validation(changes, context);
        }));

        entitiesToCheck = _uniq(_flattenDeep(_map(entitiesToCheck, function(entity) {
            var entities = [entity];
            if (entity.type === 'node') {  // validate ways if their nodes have changed
                entities = entities.concat(graph.parentWays(entity));
            }
            entities = _map(entities, function(entity) {
                if (entity.type !== 'relation') {  // validate relations if their geometries have changed
                    return [entity].concat(graph.parentRelations(entity));
                }
                return entity;
            });
            return entities;
        })));

        for (var entityIndex in entitiesToCheck) {
            var entity = entitiesToCheck[entityIndex];
            var entityIssues = validateEntity(entity);
            _issuesByEntityID[entity.id] = entityIssues;
            _issues = _issues.concat(entityIssues);
        }

        _issues = _uniqWith(_issues, function(issue1, issue2) {
            return issue1.id() === issue2.id();
        });

        dispatch.call('reload', self, _issues);
    };

    return utilRebind(self, dispatch, 'on');
}

export function validationIssue(attrs) {
    this.type = attrs.type;                // required
    this.severity = attrs.severity;        // required - 'warning' or 'error'
    this.message = attrs.message;          // required - localized string
    this.tooltip = attrs.tooltip;          // required - localized string
    this.entities = attrs.entities;        // optional - array of entities
    this.loc = attrs.loc;                  // optional - expect a [lon, lat] array
    this.info = attrs.info;                // optional - object containing arbitrary extra information
    this.fixes = attrs.fixes;              // optional - array of validationIssueFix objects
    this.hash = attrs.hash;                // optional - string to further differentiate the issue

    var _id;

    // A unique, deterministic string hash.
    // Issues with identical id values are considered identical.
    this.id = function() {
        if (_id) {
            return _id;
        }

        _id = this.type;

        if (this.hash) {   // subclasses can pass in their own differentiator
            _id += this.hash;
        }

        // factor in the entities this issue is for
        // (sort them so the id is deterministic)
        var entityKeys = this.entities.map(osmEntity.key);
        _id += entityKeys.sort().join();

        // factor in loc since two separate issues can have an
        // idential type and entities, e.g. in crossing_ways
        if (this.loc) {
            _id += this.loc.join();
        }
        return _id;
    };

    this.extent = function(resolver) {
        if (this.loc) {
            return geoExtent(this.loc);
        }
        if (this.entities && this.entities.length) {
            return this.entities.reduce(function(extent, entity) {
                return extent.extend(entity.extent(resolver));
            }, geoExtent());
        }
        return null;
    };

    if (this.fixes) {   // add a reference in the fixes to the issue for use in fix actions
        for (var i = 0; i < this.fixes.length; i++) {
            this.fixes[i].issue = this;
        }
    }
}

export function validationIssueFix(attrs) {
    this.icon = attrs.icon;
    this.title = attrs.title;
    this.onClick = attrs.onClick;
    this.entityIds = attrs.entityIds || [];  // Used for hover-higlighting.
    this.issue = null;    // the issue this fix is for
}
<commit_msg>Improve validation performance by avoiding uniqueWith lodash function Replace map lodash function with JavaScript array map in validator.js<commit_after>import _isFunction from 'lodash-es/isFunction';
import _filter from 'lodash-es/filter';
import _flatten from 'lodash-es/flatten';
import _flattenDeep from 'lodash-es/flattenDeep';
import _uniq from 'lodash-es/uniq';

import { dispatch as d3_dispatch } from 'd3-dispatch';

import { geoExtent } from '../geo';
import { osmEntity } from '../osm';
import { utilRebind } from '../util/rebind';
import * as Validations from '../validations/index';

export function coreValidator(context) {
    var dispatch = d3_dispatch('reload');
    var self = {};
    var _issues = [];
    var _issuesByEntityID = {};

    var validations = _filter(Validations, _isFunction).reduce(function(obj, validation) {
        var func = validation();
        obj[func.type] = func;
        return obj;
    }, {});

    var entityValidationIDs = [];
    var changesValidationIDs = [];

    for (var key in validations) {
        var validation = validations[key];
        if (validation.inputType && validation.inputType === 'changes') {
            changesValidationIDs.push(key);
        } else {
            entityValidationIDs.push(key);
        }
    }

    //self.featureApplicabilityOptions = ['edited', 'all'];

    /*var featureApplicability = context.storage('issue-features') || 'edited';

    self.getFeatureApplicability = function() {
        return featureApplicability;
    };

    self.setFeatureApplicability = function(applicability) {
        featureApplicability = applicability;
        context.storage('issue-features', applicability);
    };*/

    self.getIssues = function() {
        return _issues;
    };

    self.getWarnings = function() {
        return _issues.filter(function(d) { return d.severity === 'warning'; });
    };

    self.getErrors = function() {
        return _issues.filter(function(d) { return d.severity === 'error'; });
    };

    self.getIssuesForEntityWithID = function(entityID) {
        if (!context.hasEntity(entityID)) return [];
        var entity = context.entity(entityID);
        var key = osmEntity.key(entity);

        if (!_issuesByEntityID[key]) {
            _issuesByEntityID[key] = validateEntity(entity);
        }
        return _issuesByEntityID[key];
    };

    function validateEntity(entity) {
        var _issues = [];
        var ran = {};

        // runs validation and appends resulting issues, returning true if validation passed
        function runValidation(which) {
            if (ran[which]) return true;

            var fn = validations[which];
            var typeIssues = fn(entity, context);
            _issues = _issues.concat(typeIssues);
            ran[which] = true;   // mark this validation as having run
            return !typeIssues.length;
        }

        if (entity.type === 'relation') {
            if (!runValidation('old_multipolygon')) {
                // don't flag missing tags if they are on the outer way
                ran.missing_tag = true;
            }
        }

        // other validations require feature to be tagged
        if (!runValidation('missing_tag')) return _issues;

        if (entity.type === 'way') {
            runValidation('crossing_ways');

            // only check for disconnected way if no almost junctions
            if (runValidation('almost_junction')) {
                runValidation('disconnected_way');
            } else {
                ran.disconnected_way = true;
            }

            runValidation('tag_suggests_area');
        }

        // run all validations not yet run manually
        entityValidationIDs.forEach(runValidation);

        return _issues;
    }

    self.validate = function() {
        _issuesByEntityID = {};   // clear cached
        _issues = [];

        for (var validationIndex in validations) {
            if (validations[validationIndex].reset) {
                validations[validationIndex].reset();
            }
        }

        var history = context.history();
        var changes = history.changes();
        var entitiesToCheck = changes.created.concat(changes.modified);
        var graph = history.graph();

        _issues = _flatten(changesValidationIDs.map(function(ruleID) {
            var validation = validations[ruleID];
            return validation(changes, context);
        }));

        entitiesToCheck = _uniq(_flattenDeep(entitiesToCheck.map(function(entity) {
            var entities = [entity];
            if (entity.type === 'node') {  // validate ways if their nodes have changed
                entities = entities.concat(graph.parentWays(entity));
            }
            entities = entities.map(function(entity) {
                if (entity.type !== 'relation') {  // validate relations if their geometries have changed
                    return [entity].concat(graph.parentRelations(entity));
                }
                return entity;
            });
            return entities;
        })));

        var issuesByID = {};

        for (var entityIndex in entitiesToCheck) {
            var entity = entitiesToCheck[entityIndex];
            var entityIssues = validateEntity(entity);
            _issuesByEntityID[entity.id] = entityIssues;
            entityIssues.forEach(function(issue) {
                // Different entities can produce the same issue so store them by
                // the ID to ensure that there are no duplicate issues.
                issuesByID[issue.id()] = issue;
            });
        }

        for (var issueID in issuesByID) {
            _issues.push(issuesByID[issueID]);
        }

        dispatch.call('reload', self, _issues);
    };

    return utilRebind(self, dispatch, 'on');
}

export function validationIssue(attrs) {
    this.type = attrs.type;                // required
    this.severity = attrs.severity;        // required - 'warning' or 'error'
    this.message = attrs.message;          // required - localized string
    this.tooltip = attrs.tooltip;          // required - localized string
    this.entities = attrs.entities;        // optional - array of entities
    this.loc = attrs.loc;                  // optional - expect a [lon, lat] array
    this.info = attrs.info;                // optional - object containing arbitrary extra information
    this.fixes = attrs.fixes;              // optional - array of validationIssueFix objects
    this.hash = attrs.hash;                // optional - string to further differentiate the issue

    var _id;

    // A unique, deterministic string hash.
    // Issues with identical id values are considered identical.
    this.id = function() {
        if (_id) {
            return _id;
        }

        _id = this.type;

        if (this.hash) {   // subclasses can pass in their own differentiator
            _id += this.hash;
        }

        // factor in the entities this issue is for
        // (sort them so the id is deterministic)
        var entityKeys = this.entities.map(osmEntity.key);
        _id += entityKeys.sort().join();

        // factor in loc since two separate issues can have an
        // idential type and entities, e.g. in crossing_ways
        if (this.loc) {
            _id += this.loc.join();
        }
        return _id;
    };

    this.extent = function(resolver) {
        if (this.loc) {
            return geoExtent(this.loc);
        }
        if (this.entities && this.entities.length) {
            return this.entities.reduce(function(extent, entity) {
                return extent.extend(entity.extent(resolver));
            }, geoExtent());
        }
        return null;
    };

    if (this.fixes) {   // add a reference in the fixes to the issue for use in fix actions
        for (var i = 0; i < this.fixes.length; i++) {
            this.fixes[i].issue = this;
        }
    }
}

export function validationIssueFix(attrs) {
    this.icon = attrs.icon;
    this.title = attrs.title;
    this.onClick = attrs.onClick;
    this.entityIds = attrs.entityIds || [];  // Used for hover-higlighting.
    this.issue = null;    // the issue this fix is for
}
<|endoftext|>


<commit_before>const db = require('./clients/postgrest')
const pick = require('lodash/pick')
const mapValues = require('lodash/mapValues')

module.exports = function store (state, emitter) {
  state.store = {
    sheets: [],
    activeSheet: {
      fields: null,
      rows: null,
      name: null
    }
  }

  emitter.on('pushState', function (location) {
    const sheet = location.split('/').pop()
    emitter.emit('store:selectSheet', sheet)
  })

  emitter.on('store:getList', async function () {
    try {
      state.store.sheets = await db.getTables()
      const activeSheetName = getActiveSheet()
      if (activeSheetName) emitter.emit('store:selectSheet', activeSheetName)
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error fetching list of sheets' })
    }
  })

  emitter.on('store:selectSheet', async function (table) {
    try {
      const fields = await db.getSchema(table)
      const fieldsWithEditable = fields.map(addEditable)
      const firstFieldName = fields.length ? fields[0].name : ''
      const rows = await db.getRows(table, firstFieldName)
      const structuredRows = rows.map(structureRow)

      state.store.activeSheet = {
        rows: structuredRows,
        fields: fieldsWithEditable,
        name: table
      }
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: `Error selecting sheet ${table}` })
    }
  })

  emitter.on('store:setNewValue', function (data) {
    const { rowIndex, columnIndex, newValue } = data
    const isHeader = (rowIndex === -1)
    const { rows, fields } = state.store.activeSheet

    if (isHeader) {
      state.store.activeSheet.fields[columnIndex].newName = newValue
    } else {
      const fieldName = fields[columnIndex].name
      rows[rowIndex][fieldName] = rows[rowIndex][fieldName] || {}
      rows[rowIndex][fieldName].newValue = newValue
    }
  })

  emitter.on('store:updateRow', async function (data) {
    try {
      const { rowIndex, updates } = data
      const activeSheet = state.store.activeSheet
      const table = activeSheet.name
      const row = activeSheet.rows[rowIndex]
      const primaryKeys = getPrimaryKeys(activeSheet.fields)
      const conditions = destructureRow(pick(row, primaryKeys))
      const newRow = await db.update(table, updates, conditions)
      state.store.activeSheet.rows[rowIndex] = structureRow(newRow)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error saving row' })
    }
  })

  emitter.on('store:insertRow', async function (data) {
    try {
      const { rowIndex, updates } = data
      const activeSheet = state.store.activeSheet
      const table = activeSheet.name
      const newRow = await db.insert(table, updates)
      state.store.activeSheet.rows[rowIndex] = structureRow(newRow)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error adding row' })
    }
  })

  emitter.on('store:deleteRow', async function (data) {
    try {
      const { rowIndex } = data
      const activeSheet = state.store.activeSheet
      const table = activeSheet.name
      const row = activeSheet.rows[rowIndex]
      const primaryKeys = getPrimaryKeys(activeSheet.fields)
      const conditions = destructureRow(pick(row, primaryKeys))
      await db.deleteRow(table, conditions)
      state.store.activeSheet.rows.splice(rowIndex, 1)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error removing row' })
    }
  })

  emitter.on('store:insertField', async function () {
    try {
      const table = state.store.activeSheet.name
      const currentFieldCount = state.store.activeSheet.fields.length
      const newFieldName = `field_${currentFieldCount + 1}`
      const newField = await db.insertField(table, newFieldName)
      state.store.activeSheet.fields.push(newField)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error adding column' })
    }
  })

  emitter.on('store:renameField', async function (data) {
    try {
      const { columnIndex, oldValue, value } = data
      const table = state.store.activeSheet.name
      await db.renameField(table, oldValue, value)
      state.store.activeSheet.fields[columnIndex].name = value
      state.store.activeSheet.rows.map((row) => {
        row[value] = row[oldValue]
        delete row[oldValue]
        return row
      })
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error renaming column' })
    }
  })

  emitter.on('store:deleteField', async function (data) {
    try {
      const columnIndex = data.columnIndex
      const table = state.store.activeSheet.name
      const fieldName = state.store.activeSheet.fields[columnIndex].name
      await db.deleteField(table, fieldName)
      state.store.activeSheet.fields.splice(columnIndex, 1)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error removing column' })
    }
  })

  emitter.on('store:insertSheet', async function () {
    try {
      const currentSheetCount = state.store.sheets.length
      const name = `sheet_${currentSheetCount + 1}`
      await db.insertTable(name)
      state.store.sheets.push({ name })
      state.store.activeSheet.name = name
      emitter.emit('pushState', `/${name}`)
      emitter.emit('store:insertField') // add a sample field
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error adding sheet' })
    }
  })

  emitter.on('store:renameSheet', async function (data) {
    try {
      const { oldName, name } = data
      await db.renameTable(oldName, name)
      state.store.activeSheet.name = name
      const sheet = state.store.sheets.find((item) => item.name === oldName)
      sheet.name = name
      emitter.emit('pushState', `/${name}`)
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error renaming sheet' })
    }
  })

  emitter.on('store:deleteSheet', async function (name) {
    try {
      await db.deleteTable(name)
      const sheetIndex = state.store.sheets.findIndex((item) => item.name === name)
      state.store.sheets.splice(sheetIndex, 1)

      const newMaxIndex = state.store.sheets.length - 1
      const newActiveSheetIndex = Math.min(sheetIndex, newMaxIndex)
      const newActiveSheet = state.store.sheets[newActiveSheetIndex]
      state.store.activeSheet.name = newActiveSheet.name
      emitter.emit('pushState', `/${newActiveSheet.name}`)
      // TODO: what if you delete the last sheet?
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error removing sheet' })
    }
  })

  function getActiveSheet () {
    // Use param if exists, otherwise use first table in list
    if (state.params.sheet) {
      return state.params.sheet
    } else if (state.store.sheets.length > 0) {
      return state.store.sheets[0].name
    } else {
      return ''
    }
  }
}

function getPrimaryKeys (fields) {
  return fields.filter((field) => field.constraint === 'PRIMARY KEY')
    .map((field) => field.name)
}

function addEditable (field) {
  field.editable = !(field.default && field.default.startsWith('nextval'))
  return field
}

function structureRow (row) {
  return mapValues(row, (value) => ({ value }))
}

function destructureRow (row) {
  return mapValues(row, 'value')
}
<commit_msg>deleting last sheet goes to index. closes #54<commit_after>const db = require('./clients/postgrest')
const pick = require('lodash/pick')
const mapValues = require('lodash/mapValues')

module.exports = function store (state, emitter) {
  state.store = {
    sheets: [],
    activeSheet: {
      fields: null,
      rows: null,
      name: null
    }
  }

  emitter.on('pushState', function (location) {
    const sheet = location.split('/').pop()
    if (sheet) emitter.emit('store:selectSheet', sheet)
  })

  emitter.on('store:getList', async function () {
    try {
      state.store.sheets = await db.getTables()
      const activeSheetName = getActiveSheet()
      if (activeSheetName) emitter.emit('store:selectSheet', activeSheetName)
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error fetching list of sheets' })
    }
  })

  emitter.on('store:selectSheet', async function (table) {
    try {
      const fields = await db.getSchema(table)
      const fieldsWithEditable = fields.map(addEditable)
      const firstFieldName = fields.length ? fields[0].name : ''
      const rows = await db.getRows(table, firstFieldName)
      const structuredRows = rows.map(structureRow)

      state.store.activeSheet = {
        rows: structuredRows,
        fields: fieldsWithEditable,
        name: table
      }
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: `Error selecting sheet ${table}` })
    }
  })

  emitter.on('store:setNewValue', function (data) {
    const { rowIndex, columnIndex, newValue } = data
    const isHeader = (rowIndex === -1)
    const { rows, fields } = state.store.activeSheet

    if (isHeader) {
      state.store.activeSheet.fields[columnIndex].newName = newValue
    } else {
      const fieldName = fields[columnIndex].name
      rows[rowIndex][fieldName] = rows[rowIndex][fieldName] || {}
      rows[rowIndex][fieldName].newValue = newValue
    }
  })

  emitter.on('store:updateRow', async function (data) {
    try {
      const { rowIndex, updates } = data
      const activeSheet = state.store.activeSheet
      const table = activeSheet.name
      const row = activeSheet.rows[rowIndex]
      const primaryKeys = getPrimaryKeys(activeSheet.fields)
      const conditions = destructureRow(pick(row, primaryKeys))
      const newRow = await db.update(table, updates, conditions)
      state.store.activeSheet.rows[rowIndex] = structureRow(newRow)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error saving row' })
    }
  })

  emitter.on('store:insertRow', async function (data) {
    try {
      const { rowIndex, updates } = data
      const activeSheet = state.store.activeSheet
      const table = activeSheet.name
      const newRow = await db.insert(table, updates)
      state.store.activeSheet.rows[rowIndex] = structureRow(newRow)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error adding row' })
    }
  })

  emitter.on('store:deleteRow', async function (data) {
    try {
      const { rowIndex } = data
      const activeSheet = state.store.activeSheet
      const table = activeSheet.name
      const row = activeSheet.rows[rowIndex]
      const primaryKeys = getPrimaryKeys(activeSheet.fields)
      const conditions = destructureRow(pick(row, primaryKeys))
      await db.deleteRow(table, conditions)
      state.store.activeSheet.rows.splice(rowIndex, 1)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error removing row' })
    }
  })

  emitter.on('store:insertField', async function () {
    try {
      const table = state.store.activeSheet.name
      const currentFieldCount = state.store.activeSheet.fields.length
      const newFieldName = `field_${currentFieldCount + 1}`
      const newField = await db.insertField(table, newFieldName)
      state.store.activeSheet.fields.push(newField)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error adding column' })
    }
  })

  emitter.on('store:renameField', async function (data) {
    try {
      const { columnIndex, oldValue, value } = data
      const table = state.store.activeSheet.name
      await db.renameField(table, oldValue, value)
      state.store.activeSheet.fields[columnIndex].name = value
      state.store.activeSheet.rows.map((row) => {
        row[value] = row[oldValue]
        delete row[oldValue]
        return row
      })
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error renaming column' })
    }
  })

  emitter.on('store:deleteField', async function (data) {
    try {
      const columnIndex = data.columnIndex
      const table = state.store.activeSheet.name
      const fieldName = state.store.activeSheet.fields[columnIndex].name
      await db.deleteField(table, fieldName)
      state.store.activeSheet.fields.splice(columnIndex, 1)
      emitter.emit('render')
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error removing column' })
    }
  })

  emitter.on('store:insertSheet', async function () {
    try {
      const currentSheetCount = state.store.sheets.length
      const name = `sheet_${currentSheetCount + 1}`
      await db.insertTable(name)
      state.store.sheets.push({ name })
      state.store.activeSheet.name = name
      state.store.activeSheet.rows = []
      state.store.activeSheet.fields = await db.getSchema(name)
      emitter.emit('pushState', `/${name}`)
      emitter.emit('store:insertField') // add a sample field
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error adding sheet' })
    }
  })

  emitter.on('store:renameSheet', async function (data) {
    try {
      const { oldName, name } = data
      await db.renameTable(oldName, name)
      state.store.activeSheet.name = name
      const sheet = state.store.sheets.find((item) => item.name === oldName)
      sheet.name = name
      emitter.emit('pushState', `/${name}`)
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error renaming sheet' })
    }
  })

  emitter.on('store:deleteSheet', async function (name) {
    try {
      await db.deleteTable(name)
      const sheetIndex = state.store.sheets.findIndex((item) => item.name === name)
      state.store.sheets.splice(sheetIndex, 1)

      const newMaxIndex = state.store.sheets.length - 1
      const newActiveSheetIndex = Math.min(sheetIndex, newMaxIndex)
      const newActiveSheet = state.store.sheets[newActiveSheetIndex]
      const newActiveSheetName = newActiveSheet ? newActiveSheet.name : ''
      state.store.activeSheet = {
        name: null,
        fields: null,
        rows: null
      }
      emitter.emit('pushState', `/${newActiveSheetName}`)
    } catch (err) {
      console.error(err)
      emitter.emit('ui:notify', { msg: 'Error removing sheet' })
    }
  })

  function getActiveSheet () {
    // Use param if exists, otherwise use first table in list
    if (state.params.sheet) {
      return state.params.sheet
    } else if (state.store.sheets.length > 0) {
      return state.store.sheets[0].name
    } else {
      return ''
    }
  }
}

function getPrimaryKeys (fields) {
  return fields.filter((field) => field.constraint === 'PRIMARY KEY')
    .map((field) => field.name)
}

function addEditable (field) {
  field.editable = !(field.default && field.default.startsWith('nextval'))
  return field
}

function structureRow (row) {
  return mapValues(row, (value) => ({ value }))
}

function destructureRow (row) {
  return mapValues(row, 'value')
}
<|endoftext|>


<commit_before>'use strict';

// Imports
const fs = require('fs');

// Get branch and project name from command line arguments.
const [, , limitFile, project, branch, commit] = process.argv;

// Load sizes.
const currentSizes = JSON.parse(fs.readFileSync('/tmp/current.log', 'utf8'));
const allLimitSizes = JSON.parse(fs.readFileSync(limitFile, 'utf8'));
const limitSizes = allLimitSizes[project][branch] || allLimitSizes[project]['master'];

// Check current sizes against limits.
let failed = false;
for (const compressionType in limitSizes) {
  if (typeof limitSizes[compressionType] === 'object') {
    const limitPerFile = limitSizes[compressionType];

    for (const filename in limitPerFile) {
      const expectedSize = limitPerFile[filename];
      const actualSize = currentSizes[`${compressionType}/${filename}`];

      if (Math.abs(actualSize - expectedSize) > expectedSize / 100) {
        failed = true;
        console.log(
            `Commit ${commit} ${compressionType} ${filename} exceeded expected size by >1% ` +
            `(expected: ${expectedSize}, actual: ${actualSize}).`);
      }
    }
  }
}

if (failed) {
  console.log(`If this is a desired change, please update the size limits in file '${limitFile}'.`);
  process.exit(1);
} else {
  console.log('Payload size <1% change check passed.');
}
<commit_msg>build(core): improve payload size failure message (#21346)<commit_after>'use strict';

// Imports
const fs = require('fs');

// Get branch and project name from command line arguments.
const [, , limitFile, project, branch, commit] = process.argv;

// Load sizes.
const currentSizes = JSON.parse(fs.readFileSync('/tmp/current.log', 'utf8'));
const allLimitSizes = JSON.parse(fs.readFileSync(limitFile, 'utf8'));
const limitSizes = allLimitSizes[project][branch] || allLimitSizes[project]['master'];

// Check current sizes against limits.
let failed = false;
for (const compressionType in limitSizes) {
  if (typeof limitSizes[compressionType] === 'object') {
    const limitPerFile = limitSizes[compressionType];

    for (const filename in limitPerFile) {
      const expectedSize = limitPerFile[filename];
      const actualSize = currentSizes[`${compressionType}/${filename}`];

      if (Math.abs(actualSize - expectedSize) > expectedSize / 100) {
        failed = true;
        // We must also catch when the size is significantly lower than the payload limit, so
        // we are forced to update the expected payload number when the payload size reduces.
        // Otherwise, we won't be able to catch future regressions that happen to be below
        // the artificially inflated limit.
        const operator = actualSize > expectedSize ? 'exceeded' : 'fell below';
        console.log(
            `Commit ${commit} ${compressionType} ${filename} ${operator} expected size by >1% ` +
            `(expected: ${expectedSize}, actual: ${actualSize}).`);
      }
    }
  }
}

if (failed) {
  console.log(`If this is a desired change, please update the size limits in file '${limitFile}'.`);
  process.exit(1);
} else {
  console.log('Payload size <1% change check passed.');
}
<|endoftext|>


<commit_before>$(document).ready( function () {
	// initializing side nav
	// $(".button-collapse").sideNav();
	$('.button-collapse').sideNav({
      menuWidth: 300,
      edge: 'left',
      closeOnClick: true,
      draggable: true
    });
    $(".drag-target").on("swipeleft", function () {
      $("#sidenav-overlay").trigger("click");
    });

	$(".scrollspy").scrollSpy({
		scrollOffset:60
	});

	$('select').material_select();

	$('.collapsible-header').click(function(){

		$(".rotating-span").removeClass('open');
		$(".rotating-span").removeClass('open');
		if (!($(this).hasClass("active")))
			$(".rotating-span", this).toggleClass('open');
		else
			$(".rotating-span", this).removeClass('open');

	});
	$('.modal').modal();

	// autocomplete for college names
	$('input.autocomplete').autocomplete({
		data: {
			"Amity University Mumbai - Mumbai Pune Express Way": null,
			"Dr. D. Y. Patil Dental College & Hospital - Nerul": null,
			"Mahatma Gandhi Mission Dental College - Kalamboli": null,
			"Nair Dental College - Byculla, Mumbai Central": null,
			"Government Dental College and Hospital - Fort area": null,
			"St. George Dental College & Hospital, Chhatrapati Shivaji Terminus": null,
			"Terna Dental College and Hospital - Nerul, Navi Mumbai": null,
			"Yerala Medical Trust Dental College & Hospital - Kharghar": null,
			"Bharati Vidyapeeth College of Dental, Navi Mumbai": null,
			"Alamuri ratnamala institute of engineering and technology, Sapgaon,Thane": null,
			"Atharva College Of Engineering, Malad (West)": null,
			"Bharati Vidyapeeth College of Engineering, Belapur, Navi Mumbai": null,
			"Datta Meghe College of Engineering, Airoli, Navi Mumbai": null,
			"Dilkap Research Institute of Engineering and Management Studies": null,
			"Don Bosco Institute of Technology, Kurla (West)": null,
			"Dwarkadas J. Sanghvi College of Engineering, Vile Parle (West)": null,
			"Fr. Conceicao Rodrigues College of Engineering, Bandra": null,
			"Fr. Conceicao Rodrigues Institute of Technology, Vashi": null,
			"Hope Foundation's Finolex Academy of Management & Technology (FAMT), Ratnagiri": null,
			"Gharda Foundation's Gharda Institute of Technology (GIT), Lavel, Khed, Ratnagiri": null,
			"Institute of Chemical Technology (formerly UDCT), Matunga (Autonomous)": null,
			"Indian Institute of Technology Bombay, Powai": null,
			"KC College of Engineering, Thane (East)": null,
			"K.J. Somaiya College of Engineering, Vidyavihar": null,
			"K. J. Somaiya Institute of Engineering and Information Technology, Sion": null,
			"Konkan Gyanpeeth College of Engineering, Karjat": null,
			"Lokmanya Tilak College of Engineering - Kopar Khairane, Navi Mumbai": null,
			"M. H. Saboo Siddik College of Engineering - Byculla": null,
			"Mahatma Gandhi Mission's College of Engineering and Technology, Kamothe": null,
			"Mandar Education Society's Rajaram Shinde College of Engineering, Pedhambe": null,
			"Metropolitan Institute of Technology & Management (MITM) Sindhudurg(Konkan Region)": null,
			"NMIMS Mukesh Patel School of Technology Management and Engineering (NMU), Juhu": null,
			"Padmabhushan Vasantdada Patil Pratishthan's College of Engineering, Sion": null,
			"Pillai College of Engineering, Panvel": null,
			"Rajiv Gandhi Institute of Technology, Mumbai": null,
			"Ramrao Adik Institute of Technology, Nerul": null,
			"Rajendra Mane College of Engineering & Technology (RMCET) Ambav,Devrukh": null,
			"Rizvi College of Engineering, Bandra (West)": null,
			"Saraswati College of Engineering, Kharghar, Navi Mumbai": null,
			"Sardar Patel College of Engineering - Andheri (West)": null,
			"Sardar Patel Institute of Technology - Andheri (West)": null,
			"Shah and Anchor Kutchhi Engineering College, Chembur": null,
			"Shivajirao S. Jondhale College of Engineering, Dombivali": null,
			"Shee L. R. Tiwari College of Engineering(SLRTCE), Mira Road": null,
			"Sindhudurg Shikshan Prasarak Mandal's College of Engineering (SSPMCOE), Kankavli(Konkan Region)": null,
			"SIES Graduate School of Technology, Nerul": null,
			"Smt. Indira Gandhi College of Engineering, Koparkhairane, Navi Mumbai": null,
			"St. Francis Institute of Technology, Borivali": null,
			"St. John College of Engineering and Technology, Palghar": null,
			"Terna Engineering College, Nerul, Navi Mumbai": null,
			"Thakur College of Engineering and Technology, Kandivali": null,
			"Thadomal Shahani Engineering College Mumbai, Bandra (W)": null,
			"Vidyalankar Institute of Technology, Wadala (E),Mumbai": null,
			"Vidyavardhini College of Engineering and Technology,Vasai Road (W)": null,
			"Viva Institute of Technology, Virar (E)": null,
			"Usha Mittal Institute of Technology, Santacruz (W), Mumbai": null,
			"Veermata Jijabai Technological Institute, Matunga, Mumbai": null,
			"Vivekanand Education Society's Institute of Technology Mumbai, Chembur(E)": null,
			"Watumull Institute of Electronics Engineering and Computer Technology Worli": null,
			"Xavier Institute of Engineering Mahim (West)": null,
			"Yadavrao Tasgaonkar Institute of Engineering & Technology (YTIET), Bhivpuri": null
		},
		minLength: 0,
	});

	// logging dino-say
	print_dino_say();

	setInterval(countDownTimer, 1000);

})

function countDownTimer(){

	var event_date = new Date(2017, 09, 07, 9, 00, 00);
	var curr_date = new Date();
	var t1 = event_date.getTime();
	var t2 = curr_date.getTime();
	var day = Math.floor((t1-t2)/(24*60*60*1000));
	t1 = t1 - day*24*60*60*1000;
	var hour = Math.floor((t1-t2)/(60*60*1000));
	t1 = t1 - hour*60*60*1000;
	var min = Math.floor((t1-t2)/(60*1000));
	t1 = t1 - min*60*1000;
	var sec = Math.floor((t1-t2)/(1000));

	document.getElementById('day').innerHTML = day;
	document.getElementById('hour').innerHTML = hour;
	document.getElementById('min').innerHTML = min;
	document.getElementById('sec').innerHTML = sec;

	// console.log(event_date + "\n" + curr_date + "\n" + diff);
	// console.log(day + "\n" + hour + "\n" + min + "\n" + sec);
}

function print_dino_say(){
	// printing a dino-say kinda dialogue to the console (if you modify it, please review the placements of slashes before pushing)
	dinoSay = "\n\
	    __________________________________________________________________________\n\
	   /																		   \\ \n\
	  /   Hello there random stranger!                                              \\ \n\
	 /    I think you are interested in this website's guts.                         \\ \n\
	/     I'm the guardian of it's source code. RAAWR!                                \\ \n\
	\\     Luckily, I believe in sharing with the community.                           /\n\
	 \\    So here's the code : https://github.com/TheProgrammersClub/err_404         /\n\
	  \\   Make wise use of it.                                                      /\n\
	   \\ 																		   /\n\
	    ---------------------------------------------------------------------------\n\
				███████████       /\n\
			  ████▄███████████   /\n\
			  ████████████████  /\n\
			  ████████████████ /\n\
			  ████████\n\
			  ████████████\n\
█ 			  ██████\n\
█ 			 ███████\n\
███ 	   ████████████\n\
█████   ████████████  █\n\
 ███████████████████\n\
  ██████████████████\n\
	 █████████████\n\
	 ███████████\n\
	  ████████\n\
	  ████  ██\n\
	  ███    █\n\
	  █      █\n\
	  ███    ███"
	console.log(dinoSay);
}

function loadProgress() {

	document.getElementById('loader').style.display = "none";
	document.getElementById('main').style.display = "block";

	// enable scroll when page loaded
	document.getElementsByTagName("body")[0].style["overflow-y"] = "scroll";

	// animate the logo after loader is removed load
	main_pop_up_options = {
		duration: 800,
		distance: '20px',
		scale: 1,
	};
	sr.reveal(".main-logo", main_pop_up_options);
}<commit_msg>Delete scripts.js<commit_after><|endoftext|>


<commit_before>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var uglify = require('gulp-uglifyjs');
var webpack = require('gulp-webpack');
var usemin = require('gulp-usemin');
var minifyCss = require('gulp-minify-css');
var git = require('gulp-git');
var clean = require('gulp-clean');
var runSequence = require('run-sequence');
var rename = require('gulp-rename');
var exec = require('child_process').exec;
var Q = require('q');

var paths = {
    src: [
        './src/core.js',
        './src/input.js',
        './src/graphics.js',
        './src/sound.js'
    ],

    editor: ['editor/**/*.jsx', 'editor/**/*.js']
};

gulp.task('default', ['test']);
gulp.task('test', ['jscs', 'jshint']);
gulp.task('build', ['compress', 'build-editor']);

gulp.task('build-editor', function () {
    return runSequence(
        'browserify',
        'usemin',
        'copy-glyphicons'
    );
});

gulp.task('publish-docs', function () {
    return runSequence(
        'clean-clone',
        'clone',
        'clean-clone-content',
        'mkdocs',
        'copy-doc',
        'build-editor',
        'copy-editor',
        'copy-build',
        'copy-demos',
        'commit'
    );
});
gulp.task('start', ['watch']);

gulp.task('jscs', function() {
    return gulp.src('./src/*.js')
        .pipe(jscs());
});

gulp.task('jshint', function() {
    return gulp.src('./src/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default', { verbose: true }))
        .pipe(jshint.reporter('fail'));
});

gulp.task('compress', function() {
    gulp.src(paths.src)
        .pipe(uglify('micron.js', {
            output: {
                beautify: true
            },
            compress: false,
            mangle: false
        }))
        .pipe(gulp.dest('build'))
        .pipe(uglify('micron.min.js', {
            outSourceMap: true
        }))
        .pipe(gulp.dest('build'));

});

gulp.task('watch', function() {
    gulp.watch(paths.src, ['compress']);
    gulp.watch(paths.editor, ['build-editor']);
});

gulp.task('browserify', function() {
    return gulp.src('./editor/app/bootstrap.jsx')
        .pipe(webpack({
            module: {
                loaders: [
                    {
                        test: /\.jsx$/,
                        loader: 'jsx-loader?insertPragma=React.DOM&harmony'
                    }
                ]
            },
            output: {
                filename: 'app-bundled.js'
            }
        }))
        .pipe(gulp.dest('./editor'));
});

gulp.task('usemin', function () {
    return gulp.src('./editor/index_dev.html')
        .pipe(rename('index.html'))
        .pipe(usemin({
            css: [minifyCss(), 'concat']
        }))
        .pipe(gulp.dest('./editor'));
});

gulp.task('mkdocs', function (cb) {
    exec('mkdocs build --clean', function (err, stdout, stderr) {
        cb(err);
    })
});

gulp.task('clean-clone-content', function () {
    return gulp.src('micronjs.github.io/*', {read: false})
        .pipe(clean());
});

gulp.task('clean-clone', function () {
    return gulp.src('micronjs.github.io', {read: false})
        .pipe(clean());
});

gulp.task('clone', function () {
    var deferred = Q.defer(),
        baseUrl = 'https://github.com/micronjs';

    if (process.env.GH_TOKEN) {
        baseUrl = 'https://' + process.env.GH_TOKEN + '@github.com/micronjs';
    }

    git.clone(baseUrl + '/micronjs.github.io.git', function (err) {
        if (err) {
            return deferred.reject(err);
        }

        return deferred.resolve();
    });

    return deferred.promise;
});

gulp.task('commit', function () {
    function push () {
        var deferred = Q.defer();

        git.push('origin', 'master', { cwd: 'micronjs.github.io' }, function(err) {
            if (err) {
                return deferred.reject(err);
            }

            deferred.resolve();
        });

        return deferred.promise;
    }

    return gulp.src('micronjs.github.io/')
        .pipe(git.add({ cwd: 'micronjs.github.io' }))
        .pipe(git.commit('Update ' + (new Date), { cwd: 'micronjs.github.io', args: '--allow-empty' }))
        .on('end', function () {
            push();
        });
});

gulp.task('copy-doc', function () {
    return gulp.src('site/**')
        .pipe(gulp.dest('micronjs.github.io'));
});

gulp.task('copy-build', function () {
    return gulp.src(['build/**'])
        .pipe(gulp.dest('micronjs.github.io/build'));
});

gulp.task('copy-demos', function () {
    return gulp.src(['demos/**'])
        .pipe(gulp.dest('micronjs.github.io/demos'));
});

gulp.task('copy-editor', function () {
    return gulp.src(['editor/**', '!editor/index_dev.html'])
        .pipe(gulp.dest('micronjs.github.io/editor'));
});

gulp.task('copy-glyphicons', function () {
    return gulp.src('node_modules/bootstrap/fonts/**')
        .pipe(gulp.dest('editor/fonts'));
});
<commit_msg>Amend commit when deploy<commit_after>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var uglify = require('gulp-uglifyjs');
var webpack = require('gulp-webpack');
var usemin = require('gulp-usemin');
var minifyCss = require('gulp-minify-css');
var git = require('gulp-git');
var clean = require('gulp-clean');
var runSequence = require('run-sequence');
var rename = require('gulp-rename');
var exec = require('child_process').exec;
var Q = require('q');

var paths = {
    src: [
        './src/core.js',
        './src/input.js',
        './src/graphics.js',
        './src/sound.js'
    ],

    editor: ['editor/**/*.jsx', 'editor/**/*.js']
};

gulp.task('default', ['test']);
gulp.task('test', ['jscs', 'jshint']);
gulp.task('build', ['compress', 'build-editor']);

gulp.task('build-editor', function () {
    return runSequence(
        'browserify',
        'usemin',
        'copy-glyphicons'
    );
});

gulp.task('publish-docs', function () {
    return runSequence(
        'clean-clone',
        'clone',
        'clean-clone-content',
        'mkdocs',
        'copy-doc',
        'build-editor',
        'copy-editor',
        'copy-build',
        'copy-demos',
        'commit'
    );
});
gulp.task('start', ['watch']);

gulp.task('jscs', function() {
    return gulp.src('./src/*.js')
        .pipe(jscs());
});

gulp.task('jshint', function() {
    return gulp.src('./src/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default', { verbose: true }))
        .pipe(jshint.reporter('fail'));
});

gulp.task('compress', function() {
    gulp.src(paths.src)
        .pipe(uglify('micron.js', {
            output: {
                beautify: true
            },
            compress: false,
            mangle: false
        }))
        .pipe(gulp.dest('build'))
        .pipe(uglify('micron.min.js', {
            outSourceMap: true
        }))
        .pipe(gulp.dest('build'));

});

gulp.task('watch', function() {
    gulp.watch(paths.src, ['compress']);
    gulp.watch(paths.editor, ['build-editor']);
});

gulp.task('browserify', function() {
    return gulp.src('./editor/app/bootstrap.jsx')
        .pipe(webpack({
            module: {
                loaders: [
                    {
                        test: /\.jsx$/,
                        loader: 'jsx-loader?insertPragma=React.DOM&harmony'
                    }
                ]
            },
            output: {
                filename: 'app-bundled.js'
            }
        }))
        .pipe(gulp.dest('./editor'));
});

gulp.task('usemin', function () {
    return gulp.src('./editor/index_dev.html')
        .pipe(rename('index.html'))
        .pipe(usemin({
            css: [minifyCss(), 'concat']
        }))
        .pipe(gulp.dest('./editor'));
});

gulp.task('mkdocs', function (cb) {
    exec('mkdocs build --clean', function (err, stdout, stderr) {
        cb(err);
    })
});

gulp.task('clean-clone-content', function () {
    return gulp.src('micronjs.github.io/*', {read: false})
        .pipe(clean());
});

gulp.task('clean-clone', function () {
    return gulp.src('micronjs.github.io', {read: false})
        .pipe(clean());
});

gulp.task('clone', function () {
    var deferred = Q.defer(),
        baseUrl = 'https://github.com/micronjs';

    if (process.env.GH_TOKEN) {
        baseUrl = 'https://' + process.env.GH_TOKEN + '@github.com/micronjs';
    }

    git.clone(baseUrl + '/micronjs.github.io.git', function (err) {
        if (err) {
            return deferred.reject(err);
        }

        return deferred.resolve();
    });

    return deferred.promise;
});

gulp.task('commit', function () {
    function push () {
        var deferred = Q.defer();

        git.push('origin', 'master', { cwd: 'micronjs.github.io' }, function(err) {
            if (err) {
                return deferred.reject(err);
            }

            deferred.resolve();
        });

        return deferred.promise;
    }

    return gulp.src('micronjs.github.io/')
        .pipe(git.add({ cwd: 'micronjs.github.io' }))
        .pipe(git.commit('Update ' + (new Date), { cwd: 'micronjs.github.io', args: '--allow-empty --amend' }))
        .on('end', function () {
            push();
        });
});

gulp.task('copy-doc', function () {
    return gulp.src('site/**')
        .pipe(gulp.dest('micronjs.github.io'));
});

gulp.task('copy-build', function () {
    return gulp.src(['build/**'])
        .pipe(gulp.dest('micronjs.github.io/build'));
});

gulp.task('copy-demos', function () {
    return gulp.src(['demos/**'])
        .pipe(gulp.dest('micronjs.github.io/demos'));
});

gulp.task('copy-editor', function () {
    return gulp.src(['editor/**', '!editor/index_dev.html'])
        .pipe(gulp.dest('micronjs.github.io/editor'));
});

gulp.task('copy-glyphicons', function () {
    return gulp.src('node_modules/bootstrap/fonts/**')
        .pipe(gulp.dest('editor/fonts'));
});
<|endoftext|>


<commit_before>export {
  default
} from 'https://www.lactame.com/lib/molecular-formula/0.3.5/molecular-formula.js';
<commit_msg>update molecular formula to v0.3.6<commit_after>export {
  default
} from 'https://www.lactame.com/lib/molecular-formula/0.3.6/molecular-formula.js';
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-angular-2-library:app', function () {

  before(function (done) {

    helpers.run(path.join(__dirname, '../generators/app'))
      .withOptions({})
      .withPrompts({libraryName: 'angular2-library-name'})
      .on('end', done);

  });

  it('should create package.json', function () {
    assert.file([
      'package.json'
    ]);
  });

  it('should create tsconfig.json', function () {
    assert.file([
      'tsconfig.json'
    ]);
  });

  it('should create .gitignore', function () {
    assert.file([
      '.gitignore'
    ]);
  });

  it('should create .npmignore', function () {
    assert.file([
      '.npmignore'
    ]);
  });

  it('should create README.MD', function () {
    assert.file([
      'README.MD'
    ]);
  });

  it('should create main library file', function () {
    assert.file([
      'src/index.ts'
    ]);
  });

  it('should create sample pipes', function () {
    assert.file([
      'src/pipes.ts',
      'src/pipes/sample.pipe.ts'
    ]);
  });

  it('should create sample services', function () {
    assert.file([
      'src/services.ts',
      'src/services/sample.service.ts'
    ]);
  });

  it('should create sample directives', function () {
    assert.file([
      'src/directives.ts',
      'src/directives/sample.directive.ts',
      'src/directives/sample.component.ts'
    ]);
  });

});
<commit_msg>test(generator): update unit tests<commit_after>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-angular-2-library:app', function () {

  before(function (done) {

    helpers.run(path.join(__dirname, '../generators/app'))
      .withOptions({})
      .withPrompts({libraryName: 'angular2-library-name'})
      .on('end', done);

  });

  it('should create package.json', function () {
    assert.file([
      'package.json'
    ]);
  });

  it('should create tsconfig.json', function () {
    assert.file([
      'tsconfig.json'
    ]);
  });

  it('should create .gitignore', function () {
    assert.file([
      '.gitignore'
    ]);
  });

  it('should create .npmignore', function () {
    assert.file([
      '.npmignore'
    ]);
  });

  it('should create README.MD', function () {
    assert.file([
      'README.MD'
    ]);
  });

  it('should create main library file', function () {
    assert.file([
      'index.ts'
    ]);
  });

  it('should create sample component', function () {
    assert.file([
      'src/sample.component.ts'
    ]);
  });

  it('should create sample directive', function () {
    assert.file([
      'src/sample.directive.ts'
    ]);
  });

  it('should create sample pipe', function () {
    assert.file([
      'src/sample.pipe.ts'
    ]);
  });

  it('should create sample service', function () {
    assert.file([
      'src/sample.service.ts'
    ]);
  });

});
<|endoftext|>


<commit_before>module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        banner: '/*!\n' +
                ' * <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n' +
                ' * Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
                ' */\n',
        uglify: {
            options: {
                banner: '<%= banner %>'
            },
            main: {
                src: 'js/<%= pkg.name %>.js',
                dest: 'js/<%= pkg.name %>.min.js'
            }
        },
        less: {
            expanded: {
                options: {
                    paths: ["css"]
                },
                files: {
                    "css/<%= pkg.name %>.css": "less/<%= pkg.name %>.less"
                }
            },
            minified: {
                options: {
                    paths: ["css"],
                    banner: '<%= banner %>',
                    compress: true
                },
                files: {
                    "css/<%= pkg.name %>.min.css": "less/<%= pkg.name %>.less"
                }
            }
        },
        htmlmin: {
            dist: {
                options: {
                    removeComments: true,
                    collapseWhitespace: true,
                    minifyJS: true,
                    minifyCSS: true
                },
                files: [{
                    expand: true,
                    src: ['_site/**/*.html']
                }]
            }
        },
        watch: {
            scripts: {
                files: ['js/<%= pkg.name %>.js'],
                tasks: ['uglify'],
                options: {
                    spawn: false,
                },
            },
            less: {
                files: ['less/*.less'],
                tasks: ['less'],
                options: {
                    spawn: false,
                }
            },
        }
    });

    // Load the plugins.
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-htmlmin');

    // Default task(s).
    grunt.registerTask('default', ['uglify', 'less']);

};
<commit_msg>Update config file.<commit_after>module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        banner: '/*!\n' +
                ' * <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n' +
                ' * Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
                ' */\n',
        uglify: {
            options: {
                banner: '<%= banner %>'
            },
            main: {
                src: 'js/<%= pkg.name %>.js',
                dest: 'js/<%= pkg.name %>.min.js'
            }
        },
        less: {
            expanded: {
                options: {
                    paths: ["css"]
                },
                files: {
                    "css/<%= pkg.name %>.css": "less/<%= pkg.name %>.less",
                    "css/tcupdate.css": "less/tcupdate.less"
                }
            },
            minified: {
                options: {
                    paths: ["css"],
                    banner: '<%= banner %>',
                    compress: true
                },
                files: {
                    "css/<%= pkg.name %>.min.css": "less/<%= pkg.name %>.less",
                    "css/tcupdate.min.css": "less/tcupdate.less"
                }
            }
        },
        htmlmin: {
            dist: {
                options: {
                    removeComments: true,
                    collapseWhitespace: true,
                    minifyJS: true,
                    minifyCSS: true
                },
                files: [{
                    expand: true,
                    src: ['_site/**/*.html']
                }]
            }
        },
        watch: {
            scripts: {
                files: ['js/<%= pkg.name %>.js'],
                tasks: ['uglify'],
                options: {
                    spawn: false,
                },
            },
            less: {
                files: ['less/*.less'],
                tasks: ['less'],
                options: {
                    spawn: false,
                }
            },
        }
    });

    // Load the plugins.
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-htmlmin');

    // Default task(s).
    grunt.registerTask('default', ['uglify', 'less']);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({

    'string-replace': {
      version: {
        files: {
          './': 'build/vistk.js',
        },
        options: {
          replacements: [{
            pattern: /{{ VERSION }}/g,
            replacement: '<%= pkg.version %>'
          }]
        }
      }
    },

    pkg: grunt.file.readJSON('package.json'),

    concat: {
      options: {
        separator: '\n',
      },
      build: {
        src: ['js/superformula.js', 'src/start.js', 'src/utils.js', 'src/vars.js', 'src/events.js', 'src/star_constructor.js', 'src/wrangler.js',
              'src/marks/svg_rect.js',
              'src/visualizations/sparkline.js', 'src/visualizations/dotplot.js',
              'src/visualizations/barchart.js', 'src/visualizations/linechart.js', 'src/visualizations/scatterplot.js', 'src/visualizations/geomap.js',
              'src/visualizations/grid.js', 'src/visualizations/stacked.js', 'src/visualizations/piechart.js', 'src/visualizations/slopegraph.js',
              'src/visualizations/treemap.js', 'src/visualizations/radial.js', 'src/visualizations/stackedbar.js', 'src/visualizations/rectmap.js',
              'src/visualizations/caterplot.js',
              'src/visualizations/productspace.js', 'src/visualizations/ordinal_vertical.js', 'src/visualizations/ordinal_horizontal.js', 'src/visualizations/matrix.js',
              'src/start_selection.js', 'src/visualizations/table.js',
              'src/visualizations/boxplot.js', 'src/visualizations/none.js',
              'src/visualizations/default.js', 'src/ui.js', 'src/getterssetters.js',
              'src/end_constructor.js', 'src/end.js'],
        dest: 'build/vistk.js',
      },
    },

    jshint: {
      files: ['Gruntfile.js', 'build/vistk.js'],

      beforeconcat: ['build/vistk.js'],
      afterconcat: ['build/vistk.js'],

      options: {
       jshintrc: true
      }
    },

    watch: {
      concat: {
        files: ['src/*.js', 'src/visualizations/*.js'],
        tasks: ['string-replace', 'concat']
      },
      tasks: ['string-replace']
    },

    jasmine : {
      src : ['js/d3.js', 'build/vistk.js'],
      specs : 'test/specs/*.js',
      helpers : 'test/specs/helpers/*.js'
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-string-replace');

  grunt.registerTask('default', ['concat', 'string-replace']);
};
<commit_msg>Watching marks folder<commit_after>module.exports = function(grunt) {
  grunt.initConfig({

    'string-replace': {
      version: {
        files: {
          './': 'build/vistk.js',
        },
        options: {
          replacements: [{
            pattern: /{{ VERSION }}/g,
            replacement: '<%= pkg.version %>'
          }]
        }
      }
    },

    pkg: grunt.file.readJSON('package.json'),

    concat: {
      options: {
        separator: '\n',
      },
      build: {
        src: ['js/superformula.js', 'src/start.js', 'src/utils.js', 'src/vars.js', 'src/events.js', 'src/star_constructor.js', 'src/wrangler.js',
              'src/marks/svg_rect.js',
              'src/visualizations/sparkline.js', 'src/visualizations/dotplot.js',
              'src/visualizations/barchart.js', 'src/visualizations/linechart.js', 'src/visualizations/scatterplot.js', 'src/visualizations/geomap.js',
              'src/visualizations/grid.js', 'src/visualizations/stacked.js', 'src/visualizations/piechart.js', 'src/visualizations/slopegraph.js',
              'src/visualizations/treemap.js', 'src/visualizations/radial.js', 'src/visualizations/stackedbar.js', 'src/visualizations/rectmap.js',
              'src/visualizations/caterplot.js',
              'src/visualizations/productspace.js', 'src/visualizations/ordinal_vertical.js', 'src/visualizations/ordinal_horizontal.js', 'src/visualizations/matrix.js',
              'src/start_selection.js', 'src/visualizations/table.js',
              'src/visualizations/boxplot.js', 'src/visualizations/none.js',
              'src/visualizations/default.js', 'src/ui.js', 'src/getterssetters.js',
              'src/end_constructor.js', 'src/end.js'],
        dest: 'build/vistk.js',
      },
    },

    jshint: {
      files: ['Gruntfile.js', 'build/vistk.js'],

      beforeconcat: ['build/vistk.js'],
      afterconcat: ['build/vistk.js'],

      options: {
       jshintrc: true
      }
    },

    watch: {
      concat: {
        files: ['src/*.js', 'src/visualizations/*.js', 'src/marks/*.js'],
        tasks: ['string-replace', 'concat']
      },
      tasks: ['string-replace']
    },

    jasmine : {
      src : ['js/d3.js', 'build/vistk.js'],
      specs : 'test/specs/*.js',
      helpers : 'test/specs/helpers/*.js'
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-string-replace');

  grunt.registerTask('default', ['concat', 'string-replace']);
};
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/dialogflow',
    theme: 'lumen',
    default: {
      "outputSourceFiles": false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<commit_msg>chore: match jsdoc with macro license (#549)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/dialogflow',
    theme: 'lumen',
    default: {
      "outputSourceFiles": false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<|endoftext|>


<commit_before>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		},
		'showdown':{
			deps: [],
			exports: 'Showdown'
		}
	}
});

var INFODESK_GLOBAL = {};

/* Pop error message */
function add_error(args, jquery) {
	//alert('error: '+ JSON.stringify(args));
	var data, dialog;
	if(args && (typeof args === 'object')) {
		if(args.error) {
			args.title = args.error;
			delete args.error;
		}
		if(args.title || args.desc) {
			data = args;
		} else {
			data = {'desc': JSON.stringify(args)};
		}
	} else {
		data = {'title':''+args};
	}
	if(!data.date) data.date = new Date();
	function do_jquery(jquery) {
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	}
	if(jquery) {
		do_jquery(jquery);
	} else {
		require(["jquery"], function(jquery) {
			do_jquery(jquery);
		}, function(err) {
			alert('Error: ' . err);
		});
	}
};

/* Post message to server */
function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if( (msg.length === 0) || (msg.length >= 1024) ) {
			return;
		}
		var jqxhr;
		require(["jquery"], function(jquery) {
			jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		}, function(err) { add_error(JSON.stringify(err)); });
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					require(["jquery"], function(jquery) {
						jquery("#control_form .msg_field").val('');
					}, function(err) { add_error(JSON.stringify(err)); });
					update_events();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	/*
	require(["jquery"], function(jquery) {
	}, function(err) {
		add_error({'title':'Connection failed', 'desc':JSON.stringify(err)});
	});
	*/
}

/* Post message to server */
function post_msg_form() {
	var msg;
	require(["jquery"], function(jquery) {
		msg = jquery('#control_form').find('.msg_field').val();
	}, function(err) {
		add_error({'title':'Clearing form failed', 'desc':JSON.stringify(err)});
	});
	//alert('Calling post_msg() with msg=' + msg);
	post_msg({'msg':msg});
	return false;
}

/* */
function change_search_string(q) {

	if(INFODESK_GLOBAL.updating === true) { return; }

	//alert(hashtag);
	INFODESK_GLOBAL.search_string = ''+q;
	require(["jquery"], function(jquery) {
		jquery('#events .events-header').empty();
		jquery('#events .events-body').empty();
		if(q !== '') {
			var header = jquery('
').html( 'Results for '+format_msg(jquery, ''+q) + ' ' );
			var link = jquery('').html("Close ×").click(function(){ change_search_string(''); });
			link.appendTo(header);
			header.appendTo('#events .events-header');
		}
		jquery('#search_field').val('');
	}, function(err) { add_error(JSON.stringify(err)); });
	INFODESK_GLOBAL.last_id = 0;
	update_events();
}

/* */
function format_msg(jquery, msg) {
	msg = jquery('
').text(msg).html();

	// Format hashtags
	msg = msg.replace(/#([a-zA-Z0-9\.]+)/g, function($0, $1) {
		var h = (''+$1).toLowerCase();
		var div = jquery('
');
		var a = jquery('').text('#'+$1);
		a.appendTo(div);
		return div.html();
	});

	return msg;
}

/* */
function update_events() {
	var next_id, hashtag;
	if(INFODESK_GLOBAL.updating === true) { return; }
	INFODESK_GLOBAL.updating = true;
	next_id = INFODESK_GLOBAL.last_id+1;
	require(["jquery", "moment"], function(jquery, moment) {
		var options = {'msgs':'1', 'start':''+next_id};
		if(INFODESK_GLOBAL.search_string && (INFODESK_GLOBAL.search_string !== '')) {
			options.q = INFODESK_GLOBAL.search_string;
		}
		var jqxhr = jquery.get('backend.php', options, function(data) {
			var response = JSON.parse(data),
			    events = response.events,
			    server_time = response.time;

			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				(function() {
					var event = events[i],
					    id = parseInt(event.log_id, 10),
					    seconds_since = server_time - event.updated,
					    updated = new Date();

					updated.setTime( event.updated*1000 );

					if(id > INFODESK_GLOBAL.last_id) {
						INFODESK_GLOBAL.last_id = id;
					}

					var div = jquery('#elements .event_container').clone();
					div.find('.log_id').text(''+event.log_id);
					div.find('.date').text( moment(updated).format("HH:mm:ss") );
					div.find('.msg').html( format_msg(jquery, event.msg) );

					if(seconds_since < 5*60) {
						//alert("seconds_since = " + seconds_since);
						div.find('.close').show();
						setTimeout(function() {
							div.find('.close').hide();
						}, (5*60 - seconds_since)*1000);
					} else {
						div.find('.close').hide();
					}

					div.prependTo('#events .events-body');
				}());
			}
			INFODESK_GLOBAL.updating = false;
		});
		jqxhr.complete(function(data, status) {
			if(status === "success") return;
			if(data && data.responseText) {
				try {
					var obj = JSON.parse(data.responseText);
					if(obj && obj.error) {
						add_error(obj.error, jquery);
						return;
					}
					add_error(obj);
				} catch(e) {
					add_error(data);
				}
			} else {
				add_error(status + ' with ' + data);
			}
		});
	}, function(err) { add_error(JSON.stringify(err)); });
}

/* */
function update_clock() {
	function f(d) { return ((''+d).length===1) ? '0'+d : ''+d; }
	require(["jquery"], function(jquery) {
		var now = new Date();
		jquery('#clock').val( f(now.getHours()) + ':' + f(now.getMinutes()) );
	});
}

/* */
INFODESK_GLOBAL.timer = undefined;
INFODESK_GLOBAL.updating = false;
INFODESK_GLOBAL.last_id = 0;
function update_events_timer() {
	update_events();
	//update_clock();
	setTimeout('update_events_timer()', 1000);
}

/* Init everything at onLoad event */
window.onload = function() {
	require(["bootstrap"], function(b) {});

	// TODO: Setup simple clock on control form

	// TODO: Setup previous event history
	// TODO: Start fetching new events
	//update_events();
	update_events_timer();

	//
	require(['jquery'], function(jquery) {

		// Setup ajax calls
		jquery.ajaxSetup({cache:false});

		// Setup search form
		jquery('.form-search').submit(function() {
			var q = jquery('#search_field').val();
			change_search_string(q);
			return false;
		});

		// Setup about modal's body
		require(['showdown'], function(Showdown) {
			jquery.get('README.md', function(data) {
				var converter = new Showdown.converter();
				jquery('#about .modal-body').html(converter.makeHtml(data));
			});
		});

		// Focus on message field
		jquery('#control_form .msg_field').focus();

		// Update form message size
		var form = jquery('#control_form');
		var field = form.find('.msg_field');
		var field_help = form.find('.msg_field_help');
		var field_max = parseInt(field.attr("maxlength"), 10);
		field.removeAttr("maxlength");
		function field_update() {
			var len = field.val().length;
			if(len < field_max) {
				// Success
				field_help.show();
				if(!form.hasClass('success')) form.toggleClass('success');
				if(form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			} else {
				// Error
				field_help.show();
				if(form.hasClass('success')) form.toggleClass('success');
				if(!form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			}
		}
		field.keydown(field_update);
		field.keyup(field_update);
		field.change(field_update);
	});
};

/* EOF */
<commit_msg>Updated<commit_after>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		},
		'showdown':{
			deps: [],
			exports: 'Showdown'
		}
	}
});

var INFODESK_GLOBAL = {};

/* Pop error message */
function add_error(args, jquery) {
	//alert('error: '+ JSON.stringify(args));
	var data, dialog;
	if(args && (typeof args === 'object')) {
		if(args.error) {
			args.title = args.error;
			delete args.error;
		}
		if(args.title || args.desc) {
			data = args;
		} else {
			data = {'desc': JSON.stringify(args)};
		}
	} else {
		data = {'title':''+args};
	}
	if(!data.date) data.date = new Date();
	function do_jquery(jquery) {
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	}
	if(jquery) {
		do_jquery(jquery);
	} else {
		require(["jquery"], function(jquery) {
			do_jquery(jquery);
		}, function(err) {
			alert('Error: ' . err);
		});
	}
};

/* Post message to server */
function remove_msg(log_id, success_fn) {
		var jqxhr;
		require(["jquery"], function(jquery) {
			jqxhr = jquery.post('backend.php', {'remove_msg':log_id});
		}, function(err) { add_error(JSON.stringify(err)); });
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					success_fn();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
}

/* Post message to server */
function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if( (msg.length === 0) || (msg.length >= 1024) ) {
			return;
		}
		var jqxhr;
		require(["jquery"], function(jquery) {
			jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		}, function(err) { add_error(JSON.stringify(err)); });
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					require(["jquery"], function(jquery) {
						jquery("#control_form .msg_field").val('');
					}, function(err) { add_error(JSON.stringify(err)); });
					update_events();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	/*
	require(["jquery"], function(jquery) {
	}, function(err) {
		add_error({'title':'Connection failed', 'desc':JSON.stringify(err)});
	});
	*/
}

/* Post message to server */
function post_msg_form() {
	var msg;
	require(["jquery"], function(jquery) {
		msg = jquery('#control_form').find('.msg_field').val();
	}, function(err) {
		add_error({'title':'Clearing form failed', 'desc':JSON.stringify(err)});
	});
	//alert('Calling post_msg() with msg=' + msg);
	post_msg({'msg':msg});
	return false;
}

/* */
function change_search_string(q) {

	if(INFODESK_GLOBAL.updating === true) { return; }

	//alert(hashtag);
	INFODESK_GLOBAL.search_string = ''+q;
	require(["jquery"], function(jquery) {
		jquery('#events .events-header').empty();
		jquery('#events .events-body').empty();
		if(q !== '') {
			var header = jquery('
').html( 'Results for '+format_msg(jquery, ''+q) + ' ' );
			var link = jquery('').html("Close ×").click(function(){ change_search_string(''); });
			link.appendTo(header);
			header.appendTo('#events .events-header');
		}
		jquery('#search_field').val('');
	}, function(err) { add_error(JSON.stringify(err)); });
	INFODESK_GLOBAL.last_id = 0;
	update_events();
}

/* */
function format_msg(jquery, msg) {
	msg = jquery('
').text(msg).html();

	// Format hashtags
	msg = msg.replace(/#([a-zA-Z0-9\.]+)/g, function($0, $1) {
		var h = (''+$1).toLowerCase();
		var div = jquery('
');
		var a = jquery('').text('#'+$1);
		a.appendTo(div);
		return div.html();
	});

	return msg;
}

/* */
function update_events() {
	var next_id, hashtag;
	if(INFODESK_GLOBAL.updating === true) { return; }
	INFODESK_GLOBAL.updating = true;
	next_id = INFODESK_GLOBAL.last_id+1;
	require(["jquery", "moment"], function(jquery, moment) {
		var options = {'msgs':'1', 'start':''+next_id};
		if(INFODESK_GLOBAL.search_string && (INFODESK_GLOBAL.search_string !== '')) {
			options.q = INFODESK_GLOBAL.search_string;
		}
		var jqxhr = jquery.get('backend.php', options, function(data) {
			var response = JSON.parse(data),
			    events = response.events,
			    server_time = response.time;

			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				(function() {
					var event = events[i],
					    id = parseInt(event.log_id, 10),
					    seconds_since = server_time - event.updated,
					    updated = new Date();

					updated.setTime( event.updated*1000 );

					if(id > INFODESK_GLOBAL.last_id) {
						INFODESK_GLOBAL.last_id = id;
					}

					var div = jquery('#elements .event_container').clone();
					div.find('.log_id').text(''+event.log_id);
					div.find('.date').text( moment(updated).format("HH:mm:ss") );
					div.find('.msg').html( format_msg(jquery, event.msg) );

					var close = div.find('.close');
					if(seconds_since < 5*60) {
						//alert("seconds_since = " + seconds_since);
						close.show();
						setTimeout(function() {
							close.hide();
						}, (5*60 - seconds_since)*1000);
					} else {
						close.hide();
					}

					close.click(function() {
						remove_msg(event.log_id, function() {
							div.remove();
						});
						return false;
					});

					div.prependTo('#events .events-body');
				}());
			}
			INFODESK_GLOBAL.updating = false;
		});
		jqxhr.complete(function(data, status) {
			if(status === "success") return;
			if(data && data.responseText) {
				try {
					var obj = JSON.parse(data.responseText);
					if(obj && obj.error) {
						add_error(obj.error, jquery);
						return;
					}
					add_error(obj);
				} catch(e) {
					add_error(data);
				}
			} else {
				add_error(status + ' with ' + data);
			}
		});
	}, function(err) { add_error(JSON.stringify(err)); });
}

/* */
function update_clock() {
	function f(d) { return ((''+d).length===1) ? '0'+d : ''+d; }
	require(["jquery"], function(jquery) {
		var now = new Date();
		jquery('#clock').val( f(now.getHours()) + ':' + f(now.getMinutes()) );
	});
}

/* */
INFODESK_GLOBAL.timer = undefined;
INFODESK_GLOBAL.updating = false;
INFODESK_GLOBAL.last_id = 0;
function update_events_timer() {
	update_events();
	//update_clock();
	setTimeout('update_events_timer()', 1000);
}

/* Init everything at onLoad event */
window.onload = function() {
	require(["bootstrap"], function(b) {});

	// TODO: Setup simple clock on control form

	// TODO: Setup previous event history
	// TODO: Start fetching new events
	//update_events();
	update_events_timer();

	//
	require(['jquery'], function(jquery) {

		// Setup ajax calls
		jquery.ajaxSetup({cache:false});

		// Setup search form
		jquery('.form-search').submit(function() {
			var q = jquery('#search_field').val();
			change_search_string(q);
			return false;
		});

		// Setup about modal's body
		require(['showdown'], function(Showdown) {
			jquery.get('README.md', function(data) {
				var converter = new Showdown.converter();
				jquery('#about .modal-body').html(converter.makeHtml(data));
			});
		});

		// Focus on message field
		jquery('#control_form .msg_field').focus();

		// Update form message size
		var form = jquery('#control_form');
		var field = form.find('.msg_field');
		var field_help = form.find('.msg_field_help');
		var field_max = parseInt(field.attr("maxlength"), 10);
		field.removeAttr("maxlength");
		function field_update() {
			var len = field.val().length;
			if(len < field_max) {
				// Success
				field_help.show();
				if(!form.hasClass('success')) form.toggleClass('success');
				if(form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			} else {
				// Error
				field_help.show();
				if(form.hasClass('success')) form.toggleClass('success');
				if(!form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			}
		}
		field.keydown(field_update);
		field.keyup(field_update);
		field.change(field_update);
	});
};

/* EOF */
<|endoftext|>