<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.element.dependencies");
pimcore.element.dependencies = Class.create({

    initialize: function(element, type) {
        this.element = element;
        this.type = type;
        this.requiresLoaded = false;
        this.requiredByLoaded = false;
    },

    getLayout: function() {

        this.requiresPanel = new Ext.Panel({
            flex: 1,
            layout: "fit"
        });

        this.requiredByPanel = new Ext.Panel({
            flex: 1,
            layout: "fit"
        });

        if (this.layout == null) {
            this.layout = new Ext.Panel({
                title: t('dependencies'),
                border: false,
                iconCls: "pimcore_icon_tab_dependencies",
                autoScroll: true,
                bodyStyle: "padding: 10px",
                listeners:{
                    activate: this.getData.bind(this)
                }
            });
        }
        return this.layout;
    },

    waitForLoaded: function() {
        if (this.requiredByLoaded && this.requiresLoaded) {
            this.completeLoad();
        } else {
            window.setTimeout(this.waitForLoaded.bind(this), 1000);
        }
    },

    completeLoad: function() {

        this.layout.add(this.requiresNote);
        this.layout.add(this.requiresGrid);

        this.layout.add(this.requiredByNote);
        this.layout.add(this.requiredByGrid);

        this.layout.doLayout();
    },

    getData: function() {

        // only load it once
        if(this.requiresLoaded && this.requiredByLoaded) {
            return;
        }

        Ext.Ajax.request({
            url: '/admin/' + this.type + '/get-requires-dependencies/',
            params: {
                id: this.element.id
            },
            success: this.getRequiresLayout.bind(this)
        });

        Ext.Ajax.request({
            url: '/admin/' + this.type + '/get-required-by-dependencies/',
            params: {
                id: this.element.id
            },
            success: this.getRequiredByLayout.bind(this)
        });

        this.waitForLoaded();
    },

    getRequiresLayout: function(response) {
        if (response != null) {
            this.requiresData = Ext.decode(response.responseText);
        }

        this.requiresStore = new Ext.data.JsonStore({
            autoDestroy: true,
            data: this.requiresData,
            fields: ['id', 'path', 'type', 'subtype'],
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                    rootProperty: 'requires'
                }
            }
        });

        this.requiresGrid = new Ext.grid.GridPanel({
            store: this.requiresStore,
            columns: [
                {header: "ID", sortable: true, dataIndex: 'id'},
                {header: t("path"), sortable: true, dataIndex: 'path', flex: 1},
                {header: t("type"), sortable: true, dataIndex: 'type'},
                {header: t("subtype"), sortable: true, dataIndex: 'subtype'}
            ],
            columnLines: true,
            stripeRows: true,
            autoHeight: true,
            title: t('requires'),
            viewConfig: {
                forceFit: true
            }
        });
        this.requiresGrid.on("rowclick", this.click.bind(this));

        this.requiresNote = new Ext.Panel({
            html:t('hidden_dependencies'),
            cls:'dependency-warning',
            border:false,
            hidden: !this.requiresData.hasHidden
        });

        this.requiresLoaded = true;
    },
    getRequiredByLayout: function(response) {
        if (response != null) {
            this.requiredByData = Ext.decode(response.responseText);
        }

        this.requiredByStore = new Ext.data.JsonStore({
            autoDestroy: true,
            data: this.requiredByData,
            //rootProperty: 'requiredBy',
            fields: ['id', 'path', 'type', 'subtype'],
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                    rootProperty: 'requiredBy'
                }
            }
        });

        this.requiredByGrid = Ext.create('Ext.grid.Panel', {
            store: this.requiredByStore,
            columns: [
                {header: "ID", sortable: true, dataIndex: 'id'},
                {header: t("path"), sortable: true, dataIndex: 'path', },
                {header: t("type"), sortable: true, dataIndex: 'type'},
                {header: t("subtype"), sortable: true, dataIndex: 'subtype'}
            ],
            autoExpandColumn: "path",
            columnLines: true,
            stripeRows: true,
            autoHeight: true,
            title: t('required_by'),
            viewConfig: {
                forceFit: true
            }
        });
        this.requiredByGrid.on("rowclick", this.click.bind(this));

        this.requiredByNote = new Ext.Panel({
            html:t('hidden_dependencies'),
            cls:'dependency-warning',
            border:false,
            hidden: !this.requiredByData.hasHidden
        });

        this.requiredByLoaded = true;
    },

    click: function ( grid, index) {

        var d = grid.getStore().getAt(index).data;

        if (d.type == "object") {
            pimcore.helpers.openObject(d.id, d.subtype);
        }
        else if (d.type == "asset") {
            pimcore.helpers.openAsset(d.id, d.subtype);
        }
        else if (d.type == "document") {
            pimcore.helpers.openDocument(d.id, d.subtype);
        }
    }

});<commit_msg>fixed dependencies layout<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.element.dependencies");
pimcore.element.dependencies = Class.create({

    initialize: function(element, type) {
        this.element = element;
        this.type = type;
        this.requiresLoaded = false;
        this.requiredByLoaded = false;
    },

    getLayout: function() {

        this.requiresPanel = new Ext.Panel({
            flex: 1,
            layout: "fit"
        });

        this.requiredByPanel = new Ext.Panel({
            flex: 1,
            layout: "fit"
        });

        if (this.layout == null) {
            this.layout = new Ext.Panel({
                title: t('dependencies'),
                border: false,
                iconCls: "pimcore_icon_tab_dependencies",
                autoScroll: true,
                bodyStyle: "padding: 10px",
                listeners:{
                    activate: this.getData.bind(this)
                }
            });
        }
        return this.layout;
    },

    waitForLoaded: function() {
        if (this.requiredByLoaded && this.requiresLoaded) {
            this.completeLoad();
        } else {
            window.setTimeout(this.waitForLoaded.bind(this), 1000);
        }
    },

    completeLoad: function() {

        this.layout.add(this.requiresNote);
        this.layout.add(this.requiresGrid);

        this.layout.add(this.requiredByNote);
        this.layout.add(this.requiredByGrid);

        this.layout.doLayout();
    },

    getData: function() {

        // only load it once
        if(this.requiresLoaded && this.requiredByLoaded) {
            return;
        }

        Ext.Ajax.request({
            url: '/admin/' + this.type + '/get-requires-dependencies/',
            params: {
                id: this.element.id
            },
            success: this.getRequiresLayout.bind(this)
        });

        Ext.Ajax.request({
            url: '/admin/' + this.type + '/get-required-by-dependencies/',
            params: {
                id: this.element.id
            },
            success: this.getRequiredByLayout.bind(this)
        });

        this.waitForLoaded();
    },

    getRequiresLayout: function(response) {
        if (response != null) {
            this.requiresData = Ext.decode(response.responseText);
        }

        this.requiresStore = new Ext.data.JsonStore({
            autoDestroy: true,
            data: this.requiresData,
            fields: ['id', 'path', 'type', 'subtype'],
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                    rootProperty: 'requires'
                }
            }
        });

        this.requiresGrid = new Ext.grid.GridPanel({
            store: this.requiresStore,
            columns: [
                {header: "ID", sortable: true, dataIndex: 'id'},
                {header: t("path"), sortable: true, dataIndex: 'path', flex: 1},
                {header: t("type"), sortable: true, dataIndex: 'type'},
                {header: t("subtype"), sortable: true, dataIndex: 'subtype'}
            ],
            columnLines: true,
            stripeRows: true,
            autoHeight: true,
            title: t('requires'),
            viewConfig: {
                forceFit: true
            }
        });
        this.requiresGrid.on("rowclick", this.click.bind(this));

        this.requiresNote = new Ext.Panel({
            html:t('hidden_dependencies'),
            cls:'dependency-warning',
            border:false,
            hidden: !this.requiresData.hasHidden
        });

        this.requiresLoaded = true;
    },
    getRequiredByLayout: function(response) {
        if (response != null) {
            this.requiredByData = Ext.decode(response.responseText);
        }

        this.requiredByStore = new Ext.data.JsonStore({
            autoDestroy: true,
            data: this.requiredByData,
            //rootProperty: 'requiredBy',
            fields: ['id', 'path', 'type', 'subtype'],
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                    rootProperty: 'requiredBy'
                }
            }
        });

        this.requiredByGrid = Ext.create('Ext.grid.Panel', {
            store: this.requiredByStore,
            columns: [
                {header: "ID", sortable: true, dataIndex: 'id'},
                {header: t("path"), sortable: true, dataIndex: 'path', flex: 1},
                {header: t("type"), sortable: true, dataIndex: 'type'},
                {header: t("subtype"), sortable: true, dataIndex: 'subtype'}
            ],
            autoExpandColumn: "path",
            columnLines: true,
            stripeRows: true,
            autoHeight: true,
            title: t('required_by'),
            viewConfig: {
                forceFit: true
            }
        });
        this.requiredByGrid.on("rowclick", this.click.bind(this));

        this.requiredByNote = new Ext.Panel({
            html:t('hidden_dependencies'),
            cls:'dependency-warning',
            border:false,
            hidden: !this.requiredByData.hasHidden
        });

        this.requiredByLoaded = true;
    },

    click: function ( grid, index) {

        var d = grid.getStore().getAt(index).data;

        if (d.type == "object") {
            pimcore.helpers.openObject(d.id, d.subtype);
        }
        else if (d.type == "asset") {
            pimcore.helpers.openAsset(d.id, d.subtype);
        }
        else if (d.type == "document") {
            pimcore.helpers.openDocument(d.id, d.subtype);
        }
    }

});<|endoftext|>


<commit_before>var mongoose, RatSchema, Schema;

mongoose = require( 'mongoose' );
Schema = mongoose.Schema;

RatSchema = new Schema({
  'archive': {
    default: false,
    type: Boolean
  },
  'CMDRname': {
    type: String
  },
  'createdAt': {
    type: Date
  },
  'drilled': {
    default: false,
    type: Boolean
  },
  'gamertag': {
    type: String
  },
  'lastModified': {
    type: Date
  },
  'joined': {
    default: Date.now(),
    type: Date
  },
  'netlog': {
    type: {
      'commanderId': {
        type: String
      },
      'data': {
        type: Schema.Types.Mixed
      },
      'userId': {
        type: String
      }
    }
  },
  'nickname': {
    type: [String]
  }
});

RatSchema.index({
  'CMDRname': 'text',
  'gamertag': 'text',
  'nickname': 'text'
});

RatSchema.pre( 'save', function ( next ) {
  var timestamp;

  timestamp = Date.now();

  this.createdAt = this.createdAt || timestamp;
  this.lastModified = timestamp;

  next();
});

RatSchema.set( 'toJSON', {
  virtuals: true,
  transform: function ( document, ret, options ) {
    ret.id = ret._id;
    delete ret._id;
  }
});

module.exports = mongoose.model( 'Rat', RatSchema );
<commit_msg>Use Unix timestamps<commit_after>var mongoose, RatSchema, Schema;

mongoose = require( 'mongoose' );
Schema = mongoose.Schema;

RatSchema = new Schema({
  'archive': {
    default: false,
    type: Boolean
  },
  'CMDRname': {
    type: String
  },
  'createdAt': {
    type: Date
  },
  'drilled': {
    default: false,
    type: Boolean
  },
  'gamertag': {
    type: String
  },
  'lastModified': {
    type: Date
  },
  'joined': {
    default: Date.now(),
    type: Date
  },
  'netlog': {
    type: {
      'commanderId': {
        type: String
      },
      'data': {
        type: Schema.Types.Mixed
      },
      'userId': {
        type: String
      }
    }
  },
  'nickname': {
    type: [String]
  }
});

RatSchema.index({
  'CMDRname': 'text',
  'gamertag': 'text',
  'nickname': 'text'
});

RatSchema.pre( 'save', function ( next ) {
  var timestamp;

  timestamp = new Date().getTime() / 1000;

  this.createdAt = this.createdAt || timestamp;
  this.lastModified = timestamp;

  next();
});

RatSchema.set( 'toJSON', {
  virtuals: true,
  transform: function ( document, ret, options ) {
    ret.id = ret._id;
    delete ret._id;
  }
});

module.exports = mongoose.model( 'Rat', RatSchema );
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var BazingaApp = BazingaApp || {};

  BazingaApp.sayHello = function() {
    return 'This is awesome!!';
  };

  /**
   * @description Retrieve all the info about developers
   */
  BazingaApp.getDevsInfo = function() {
    ajax('http://localhost:3000/data.json', function(data) {
      console.log(data);
    });
  };

  /**
   * @description VanillaJS implementation for Ajax request
   * @param {String} url         Url for the ajax request
   * @param {Function} callback  Callback function
   */
  function ajax(url, callback) {
    var response,
      httpRequest = new XMLHttpRequest();

    if ( !httpRequest ) {
      throw new Error('There was an error');
    }

    httpRequest.onreadystatechange = function() {
      try {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          if (httpRequest.status === 200) {
            response = JSON.parse(httpRequest.responseText);
            callback(response);
          }
        }
      } catch (err) {
        throw new Error('There was a problem with the request.' + err);
      }
    };
    httpRequest.open('GET', url);
    httpRequest.send();
  }

  if ( typeof(window.BazingaApp) === 'undefined') {
    window.BazingaApp = BazingaApp;
  }

  return BazingaApp;
})();
<commit_msg>Formating comments<commit_after>(function() {
  'use strict';

  var BazingaApp = BazingaApp || {};

  BazingaApp.sayHello = function() {
    return 'This is awesome!!';
  };

  /**
   * @description Retrieve all the info about developers
   */
  BazingaApp.getDevsInfo = function() {
    ajax('http://localhost:3000/data.json', function(data) {
      console.log(data);
    });
  };

  /**
   * @description VanillaJS implementation for Ajax request
   * @param {String} url - Url for the ajax request
   * @param {Function} callback - Callback function
   */
  function ajax(url, callback) {
    var response,
      httpRequest = new XMLHttpRequest();

    if ( !httpRequest ) {
      throw new Error('There was an error');
    }

    httpRequest.onreadystatechange = function() {
      try {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          if (httpRequest.status === 200) {
            response = JSON.parse(httpRequest.responseText);
            callback(response);
          }
        }
      } catch (err) {
        throw new Error('There was a problem with the request.' + err);
      }
    };
    httpRequest.open('GET', url);
    httpRequest.send();
  }

  if ( typeof(window.BazingaApp) === 'undefined') {
    window.BazingaApp = BazingaApp;
  }

  return BazingaApp;
})();
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const chalk = require('chalk');
const slash = require('slash');
const browserSync = require('browser-sync');
const beeper = require('beeper');
const cwd = process.cwd();
const arrow = {
  error: chalk.red('>>'),
  warning: chalk.yellow('>>')
};

let wiredepStatus = 0;

/**
 * Handler to ignore files when synchronizing directories
 *
 * @param {String} dir
 * @param {String} file
 */
module.exports.syncIgnore = (dir, file) => {
  const filepath = slash(path.join(dir, file));
  const ignore = [
    // Images
    'app/images/icons',
    'build/images/sprite.svg',
    // Styles
    'app/styles/less',
    'build/styles/styles.css',
    'build/styles/styles.css.map',
    // Scripts
    'app/scripts',
    'build/scripts/scripts.bundle.js',
    'build/scripts/scripts.bundle.js.map',
    // templates
    'app/templates'
  ];

  return ignore.some((item) => {
    // Ignore HTML files in build directory
    var isBuildDir = filepath.indexOf('build/') + 1;
    var isHtmlFile = filepath.indexOf('.html') + 1;
    if (isBuildDir && isHtmlFile) {
      return true;
    }

    return filepath.indexOf(item) + 1;
  });
};

/**
 * Error handler for Xo plugin
 *
 * @param {object} err - The error object from Xo plugin
 */
module.exports.xoError = function() {
  if (!browserSync.active) {
    process.exit(1);
  }

  beeper(1);
  this.emit('end');
};

/**
 * Error handler for Jade plugin
 *
 * @param {object} err - The error object from Jade plugin
 */
module.exports.jadeError = function(err) {
  let msg = slash(err.message.replace(cwd + '\\', '')).split('\n');
  msg[0] = `${err.name}: ${msg[0]}`;
  msg.forEach((line) => {
    console.log(`${arrow.error} ${line}`);
  });

  beeper(1);

  if (!browserSync.active) {
    process.exit(1);
  }

  this.emit('end');
};

/**
 * Error handler for Wiredep plugin
 *
 * @param {object} err - The error object from Wiredep plugin
 */
module.exports.wiredepError = function(err) {
  if (wiredepStatus) {
    return;
  }

  if (err.code === 'BOWER_COMPONENTS_MISSING') {
    err = 'Warning: Cannot find where you keep your Bower packages.';
  } else if (err.code === 'ENOENT') {
    err = 'Warning: Cannot find \'bower.json\' file.';
  }

  wiredepStatus = 1;
  console.log(`${arrow.warning} ${err}`);
};

/**
 * Error handler for Less plugin
 *
 * @param {object} err - The error object from Less plugin
 */
module.exports.lessError = function(err) {
  const msg = slash(err.message.replace(cwd + '\\', ''));
  console.log(`${arrow.error} ${err.type}Error: ${msg}`);

  err.extract.forEach((line, index) => {
    index = index + err.line - 1;
    if (index === err.line) {
      line = `${arrow.error}   > ${index}| ${line}`;
    } else {
      line = `${arrow.error}     ${index}| ${line}`;
    }

    console.log(line);
  });

  beeper(1);

  if (!browserSync.active) {
    process.exit(1);
  }

  this.emit('end');
};
<commit_msg>XO is XO<commit_after>'use strict';

const path = require('path');
const chalk = require('chalk');
const slash = require('slash');
const browserSync = require('browser-sync');
const beeper = require('beeper');
const cwd = process.cwd();
const arrow = {
  error: chalk.red('>>'),
  warning: chalk.yellow('>>')
};

let wiredepStatus = 0;

/**
 * Handler to ignore files when synchronizing directories
 *
 * @param {String} dir
 * @param {String} file
 */
module.exports.syncIgnore = (dir, file) => {
  const filepath = slash(path.join(dir, file));
  const ignore = [
    // Images
    'app/images/icons',
    'build/images/sprite.svg',
    // Styles
    'app/styles/less',
    'build/styles/styles.css',
    'build/styles/styles.css.map',
    // Scripts
    'app/scripts',
    'build/scripts/scripts.bundle.js',
    'build/scripts/scripts.bundle.js.map',
    // templates
    'app/templates'
  ];

  return ignore.some((item) => {
    // Ignore HTML files in build directory
    var isBuildDir = filepath.indexOf('build/') + 1;
    var isHtmlFile = filepath.indexOf('.html') + 1;
    if (isBuildDir && isHtmlFile) {
      return true;
    }

    return filepath.indexOf(item) + 1;
  });
};

/**
 * Error handler for XO plugin
 *
 * @param {object} err - The error object from XO plugin
 */
module.exports.xoError = function() {
  if (!browserSync.active) {
    process.exit(1);
  }

  beeper(1);
  this.emit('end');
};

/**
 * Error handler for Jade plugin
 *
 * @param {object} err - The error object from Jade plugin
 */
module.exports.jadeError = function(err) {
  let msg = slash(err.message.replace(cwd + '\\', '')).split('\n');
  msg[0] = `${err.name}: ${msg[0]}`;
  msg.forEach((line) => {
    console.log(`${arrow.error} ${line}`);
  });

  beeper(1);

  if (!browserSync.active) {
    process.exit(1);
  }

  this.emit('end');
};

/**
 * Error handler for Wiredep plugin
 *
 * @param {object} err - The error object from Wiredep plugin
 */
module.exports.wiredepError = function(err) {
  if (wiredepStatus) {
    return;
  }

  if (err.code === 'BOWER_COMPONENTS_MISSING') {
    err = 'Warning: Cannot find where you keep your Bower packages.';
  } else if (err.code === 'ENOENT') {
    err = 'Warning: Cannot find \'bower.json\' file.';
  }

  wiredepStatus = 1;
  console.log(`${arrow.warning} ${err}`);
};

/**
 * Error handler for Less plugin
 *
 * @param {object} err - The error object from Less plugin
 */
module.exports.lessError = function(err) {
  const msg = slash(err.message.replace(cwd + '\\', ''));
  console.log(`${arrow.error} ${err.type}Error: ${msg}`);

  err.extract.forEach((line, index) => {
    index = index + err.line - 1;
    if (index === err.line) {
      line = `${arrow.error}   > ${index}| ${line}`;
    } else {
      line = `${arrow.error}     ${index}| ${line}`;
    }

    console.log(line);
  });

  beeper(1);

  if (!browserSync.active) {
    process.exit(1);
  }

  this.emit('end');
};
<|endoftext|>


<commit_before>const express = require('express')
const router = express.Router()
const ms = require('ms')
const apn = require('apn')
const joi = require('joi')
const { validate } = require('../helpers')
const Wc = require('../schemas/wc')
const moment = require('moment');
const ObjectId = require('mongoose').Types.ObjectId;
const Report = require('../schemas/report');

import {Counter} from '../generator/counter';
let counter = new Counter();
counter.notificationFunction = (wcId, count) => {}; // @todo here register call function

router.get('/', (req, res) => {
    const params = req.query
    if ('category' in params) {
        try {
            let objId = new ObjectId(params.category);
            Wc.find({ categoryId: objId }, (err, item) => {
                if (err) {
                    console.error(err);
                }
                res.json({
                    status: 'success',
                    data: item
                });
            });
        } catch (e) {
            res.status(400).json({
                status: 'error',
                message: 'Invalid category'
            });
        }
    } else {
        Wc.find((err, items) => {
            if (err) {
                console.error(err)
            }
            res.json({
                status: 'success',
                data: items
            })
        })
    }
})

router.get('/:wcId', (req, res) => {
  const { wcId } = req.params
  Wc.findById(wcId) //, 'id categoryId status banner active')
    .then(item => {
      if(!item) {
        return res.status(404).end()
      }
      return res.json({
        status: 'success',
        data: item
      })
    })
    .catch(() => {
      console.error(err)
    })
})

const apnProvider = new apn.Provider({
    token: {
        key: process.env.IOS_PATH_TO_P8_FILE,
        keyId: process.env.IOS_KEY_ID,
        teamId: process.env.IOS_TEAM_ID
    },
    production: false
})

const sendNotification = deviceToken => {
    const notification = new apn.Notification()
    notification.topic = process.env.IOS_BUNDLE_ID
    notification.expiry = ms('1h')
    notification.badge = 1
    notification.sound = 'ping.aiff'
    notification.alert = 'Hello World \u270C'
    notification.payload = { id: 123 }
    return apnProvider.send(notification, deviceToken)
}

router.get('/:wcId/notify', (req, res) => {
  const { wcId } = req.params
  Wc.findById(wcId)
  .then(wc => {
    return Promise.all(wc.deviceTokens.map(sendNotification))
  })
  .then((results) => {
    console.log(results)
    return res.status(200).json(results).end()
  })
  .catch(err => console.log(err))
})

router.post('/:wcId/notify', (req, res) => {
    if ('status' in req.body) {
        counter.dbWrite(req.params.wcId, req.body.status);
    }

    res.json({
        status: 'success'
    });
});

router.get('/:wcId/last', (req, res) => {
    if ('from' in req.query) {
        Report.find({wcId: new ObjectId(req.params.wcId), date: {
            $gte: moment(req.query.from).toDate()
        }})
            .then((items) => {
                res.json({
                    status: 'success',
                    reports: items || []
                });
            });
    } else {
        res.json({
            status: 'success',
            reports: []
        });
    }
});

const expSchema = joi.object({
    deviceToken: joi.string().required()
}).required()

router.post('/:wcId/subscribe', validate('body', expSchema), (req, res) => {
  const { deviceToken } = req.body
  const { wcId } = req.params
  if (req.headers['X-Auth-token']) {
    const adminWcId = req.headers['X-Auth-token']
    Wc.find({ token: adminWcId })
    .then(() => {
      if(!wc) {
        return res.sendStatus(404).end()
      }
      wc.adminDeviceTokens.push(deviceToken)
    })
    .then(() => {
      res.sendStatus(201).end()
    })
    .catch(err => console.log(err))
  } else {
    Wc.findById(wcId)
    .then(wc => {
      if(!wc) {
        return res.sendStatus(404).end()
      }
      wc.deviceTokens.push(deviceToken)
      return wc.save()
    })
    .then(() => {
      return res.sendStatus(204).end()
    })
    .catch(err => {
      console.log(err)
      res.sendStatus(500)
    })
  }
})

router.post('/:wcId/unsubscribe', validate('body', expSchema), (req, res) => {
  const { deviceToken } = req.body
  const { wcId } = req.params
  if (req.headers['X-Auth-token']) {
    const adminWcId = req.headers['X-Auth-token']
    Wc.find({ token: adminWcId })
    .then(wc => {
      if(!wc) {
        return res.sendStatus(404).end()
      }
      const deviceTokenIndex = wc.adminDeviceTokens.findIndex(deviceToken)
      if (deviceTokenIndex === -1) {
        return res.sendStatus(404).end()
      }
      wc.adminDeviceTokens = [
        ...wc.adminDeviceTokens.slice(0, deviceTokenIndex),
        ...wc.adminDeviceTokens.slice(deviceTokenIndex + 1)
      ]
      return wc.save()
    })
    .then(() => res.sendStatus(201).end())
    .catch(err => {
      console.log(err)
      res.sendStatus(500)
    })
  } else {
    Wc.findById(wcId)
    .then(wc => {
      const deviceTokenIndex = wc.deviceTokens.indexOf(deviceToken)
      if (deviceTokenIndex === -1) {
        return res.sendStatus(404).end()
      }
      wc.deviceTokens = [
        ...wc.deviceTokens.slice(0, deviceTokenIndex),
        ...wc.deviceTokens.slice(deviceTokenIndex + 1)
      ]
      return wc.save()
    })
    .then(() => res.sendStatus(204).end())
    .catch(err => {
      console.log(err)
      res.sendStatus(500)
    })
  }
})

/**
 * Report generator
 */
// const data = require('./data');
// const moment = require('moment');
// router.get('/gen', (req, res) => {
//     for (let item of data) {
//         if (item.status === 'occupied' || item.status === 'vacant') {
//             let report = new Report();
//             report.date = moment(item.date);
//             report.status = item.status === 'occupied' ? true : false;
//             report.wcId = new ObjectId('589e3bf575d52d722a3d2c08');
//             report.save();

//             let report2 = new Report();
//             report2.date = moment(item.date);
//             report2.status = item.status === 'occupied' ? false : true;
//             report2.wcId = new ObjectId('589e3cda75d52d722a3d2cda');
//             report2.save();
//         }
//     }
//     res.json({});
// });

router.put('/:token', (req, res) => {
    Wc.findOne({ token: req.params.token }, (err, item) => {
        if(!item) {
            res.status(404);
            return res.json({
                status: 'error',
                message: 'Wc not found'
            });
        }
        if ('banner' in req.body) {
            item.banner = req.body.banner;
        }
        if ('usageCount' in req.body) {
            item.usageCount = req.body.usageCount; // @todo validate in notifications
        }
        if ('inactivity' in req.body) {
            item.inactivity = req.body.inactivity; // @todo validate in notifications
        }

        item.save();

        res.json({
            status: 'success',
            data: item
        });
    });
});

router.get('/:token', (req, res) => {
    Wc.findOne({ token: req.params.token }, (err, item) => {
        if (!item) {
            res.status(404);
            return res.json({
                status: 'error',
                message: 'Wc not found'
            });
        }
        if (err) {
            console.error(err);
        }
        res.json({
            status: 'success',
            data: item
        });
    });
});

module.exports = router;
<commit_msg>notify by generator route<commit_after>const express = require('express')
const router = express.Router()
const ms = require('ms')
const apn = require('apn')
const joi = require('joi')
const { validate } = require('../helpers')
const Wc = require('../schemas/wc')
const moment = require('moment');
const ObjectId = require('mongoose').Types.ObjectId;
const Report = require('../schemas/report');

import {Counter} from '../generator/counter';
let counter = new Counter();
counter.notificationFunction = (wcId, count) => {}; // @todo here register call function

router.get('/', (req, res) => {
    const params = req.query
    if ('category' in params) {
        try {
            let objId = new ObjectId(params.category);
            Wc.find({ categoryId: objId }, (err, item) => {
                if (err) {
                    console.error(err);
                }
                res.json({
                    status: 'success',
                    data: item
                });
            });
        } catch (e) {
            res.status(400).json({
                status: 'error',
                message: 'Invalid category'
            });
        }
    } else {
        Wc.find((err, items) => {
            if (err) {
                console.error(err)
            }
            res.json({
                status: 'success',
                data: items
            })
        })
    }
})

router.get('/:wcId', (req, res) => {
  const { wcId } = req.params
  Wc.findById(wcId) //, 'id categoryId status banner active')
    .then(item => {
      if(!item) {
        return res.status(404).end()
      }
      return res.json({
        status: 'success',
        data: item
      })
    })
    .catch(() => {
      console.error(err)
    })
})

const apnProvider = new apn.Provider({
    token: {
        key: process.env.IOS_PATH_TO_P8_FILE,
        keyId: process.env.IOS_KEY_ID,
        teamId: process.env.IOS_TEAM_ID
    },
    production: false
})

const sendNotification = deviceToken => {
    const notification = new apn.Notification()
    notification.topic = process.env.IOS_BUNDLE_ID
    notification.expiry = ms('1h')
    notification.badge = 1
    notification.sound = 'ping.aiff'
    notification.alert = 'Hello World \u270C'
    notification.payload = { id: 123 }
    return apnProvider.send(notification, deviceToken)
}

const notifyDevices = wcId => {
  return Wc.findById(wcId)
  .then(wc => {
    return Promise.all(wc.deviceTokens.map(sendNotification))
  })
}

router.get('/:wcId/notify', (req, res) => {
  const { wcId } = req.params
  notifyDevices(wcId)
  .then((results) => {
    console.log(results)
    return res.status(200).json(results).end()
  })
  .catch(err => console.log(err))
})

router.post('/:wcId/notify', (req, res) => {
  if ('status' in req.body) {
    counter.dbWrite(req.params.wcId, req.body.status);
  }
  notifyDevices(wcId)
  .then((results) => {
    console.log(results)
    return res.status(200).json({
      status: 'success',
      data: results
    }).end()
  })
  .catch(err => console.log(err))
})

router.get('/:wcId/last', (req, res) => {
    if ('from' in req.query) {
        Report.find({wcId: new ObjectId(req.params.wcId), date: {
            $gte: moment(req.query.from).toDate()
        }})
            .then((items) => {
                res.json({
                    status: 'success',
                    reports: items || []
                });
            });
    } else {
        res.json({
            status: 'success',
            reports: []
        });
    }
});

const expSchema = joi.object({
    deviceToken: joi.string().required()
}).required()

router.post('/:wcId/subscribe', validate('body', expSchema), (req, res) => {
  const { deviceToken } = req.body
  const { wcId } = req.params
  if (req.headers['X-Auth-token']) {
    const adminWcId = req.headers['X-Auth-token']
    Wc.find({ token: adminWcId })
    .then(() => {
      if(!wc) {
        return res.sendStatus(404).end()
      }
      wc.adminDeviceTokens.push(deviceToken)
    })
    .then(() => {
      res.sendStatus(201).end()
    })
    .catch(err => console.log(err))
  } else {
    Wc.findById(wcId)
    .then(wc => {
      if(!wc) {
        return res.sendStatus(404).end()
      }
      wc.deviceTokens.push(deviceToken)
      return wc.save()
    })
    .then(() => {
      return res.sendStatus(204).end()
    })
    .catch(err => {
      console.log(err)
      res.sendStatus(500)
    })
  }
})

router.post('/:wcId/unsubscribe', validate('body', expSchema), (req, res) => {
  const { deviceToken } = req.body
  const { wcId } = req.params
  if (req.headers['X-Auth-token']) {
    const adminWcId = req.headers['X-Auth-token']
    Wc.find({ token: adminWcId })
    .then(wc => {
      if(!wc) {
        return res.sendStatus(404).end()
      }
      const deviceTokenIndex = wc.adminDeviceTokens.findIndex(deviceToken)
      if (deviceTokenIndex === -1) {
        return res.sendStatus(404).end()
      }
      wc.adminDeviceTokens = [
        ...wc.adminDeviceTokens.slice(0, deviceTokenIndex),
        ...wc.adminDeviceTokens.slice(deviceTokenIndex + 1)
      ]
      return wc.save()
    })
    .then(() => res.sendStatus(201).end())
    .catch(err => {
      console.log(err)
      res.sendStatus(500)
    })
  } else {
    Wc.findById(wcId)
    .then(wc => {
      const deviceTokenIndex = wc.deviceTokens.indexOf(deviceToken)
      if (deviceTokenIndex === -1) {
        return res.sendStatus(404).end()
      }
      wc.deviceTokens = [
        ...wc.deviceTokens.slice(0, deviceTokenIndex),
        ...wc.deviceTokens.slice(deviceTokenIndex + 1)
      ]
      return wc.save()
    })
    .then(() => res.sendStatus(204).end())
    .catch(err => {
      console.log(err)
      res.sendStatus(500)
    })
  }
})

/**
 * Report generator
 */
// const data = require('./data');
// const moment = require('moment');
// router.get('/gen', (req, res) => {
//     for (let item of data) {
//         if (item.status === 'occupied' || item.status === 'vacant') {
//             let report = new Report();
//             report.date = moment(item.date);
//             report.status = item.status === 'occupied' ? true : false;
//             report.wcId = new ObjectId('589e3bf575d52d722a3d2c08');
//             report.save();

//             let report2 = new Report();
//             report2.date = moment(item.date);
//             report2.status = item.status === 'occupied' ? false : true;
//             report2.wcId = new ObjectId('589e3cda75d52d722a3d2cda');
//             report2.save();
//         }
//     }
//     res.json({});
// });

router.put('/:token', (req, res) => {
    Wc.findOne({ token: req.params.token }, (err, item) => {
        if(!item) {
            res.status(404);
            return res.json({
                status: 'error',
                message: 'Wc not found'
            });
        }
        if ('banner' in req.body) {
            item.banner = req.body.banner;
        }
        if ('usageCount' in req.body) {
            item.usageCount = req.body.usageCount; // @todo validate in notifications
        }
        if ('inactivity' in req.body) {
            item.inactivity = req.body.inactivity; // @todo validate in notifications
        }

        item.save();

        res.json({
            status: 'success',
            data: item
        });
    });
});

router.get('/:token', (req, res) => {
    Wc.findOne({ token: req.params.token }, (err, item) => {
        if (!item) {
            res.status(404);
            return res.json({
                status: 'error',
                message: 'Wc not found'
            });
        }
        if (err) {
            console.error(err);
        }
        res.json({
            status: 'success',
            data: item
        });
    });
});

module.exports = router;
<|endoftext|>


<commit_before>import { floatMatrices } from '../arithmetic/types';

const ops = floatMatrices;
const eps = Math.pow(2, -50);

const trim = x => Math.abs(x) < eps ? 0 : x;
const lift = op => (...args) => args.reduce((a, b) => op(a, b));
const sum  = lift(ops.plus);

const gaussReduced = (u, v, dot = ops.times) => {
  const vs   = [u, v];
  const norm = v => dot(v, v);

  while (true) {
    const [i, j] = ops.lt(norm(vs[0]), norm(vs[1])) ? [0, 1] : [1, 0];
    const t = ops.round(ops.div(dot(vs[0], vs[1]), norm(vs[i])));
    vs[j] = ops.minus(vs[j], ops.times(t, vs[i]));
    if (ops.ge(norm(vs[j]), ops.times(norm(vs[i]), 1-eps)))
      break;
  }

  if (ops.gt(dot(vs[0], vs[1]), 0))
    vs[1] = ops.negative(vs[1]);

  return vs;
};

const sellingReduced = (u, v, w, dot = ops.times) => {
  const vs   = [u, v, w, ops.negative(sum(u, v, w))];
  let changed;

  do {
    changed = false;

    for (let i = 0; i < 3; ++i) {
      for (let j = i+1; j < 4; ++j) {
	if (ops.gt(dot(vs[i], vs[j]), eps)) {
	  for (let k = 0; k < 4; ++k) {
	    if (k != i && k != j) {
	      vs[k] = sum(vs[k], vs[i]);
	    }
	  }
	  vs[i] = ops.negative(vs[i]);
	  changed = true;
	}
      }
    }
  } while (changed);

  return vs.slice(0, 3);
};

const dirichletVectors = (basis, dot = ops.times) => {
  switch (basis.length) {
  case 0:
  case 1:
    return basis;
  case 2: {
    const vs = gaussReduced(...basis, dot);
    return [vs[0], vs[1], sum(vs[0], vs[1])];
  }
  case 3: {
    const vs = sellingReduced(...basis, dot);
    return [
      vs[0], vs[1], vs[2],
      sum(vs[0], vs[1]), sum(vs[0], vs[2]), sum(vs[1], vs[2]),
      sum(vs[0], vs[1], vs[2])
    ]
  }
  }
};

const compareVectors = dot => (v, w) => {
  const abs = v => v.map(x => Math.abs(x));
  const cmp = (v, w) => (v > w) - (v < w);

  return ops.minus(dot(v, v), dot(w, w)) || cmp(abs(w), abs(v));
};

const reducedLatticeBasis = (vs, dot = ops.times) => {
  const dim = vs[0].length;
  const tmp = dirichletVectors(vs, dot).sort(compareVectors(dot));
  const A = [];

  const _normalized = v => {
    let t = v.map(trim);
    if (t < ops.times(0, t))
      t = ops.negative(t);
    if (A.length > 0 && ops.gt(dot(A[0], t), 0))
      t = ops.negative(t);
    return t;
  };

  for (let k = 0, i = 0; k < tmp.length && i < dim; ++k) {
    A[i] = _normalized(tmp[k]);
    if (ops.rank(A) > i)
      ++i;
  }

  return A;
};

const shiftedIntoDirichletDomain = (pos, dirichletVecs, dot = ops.times) => {
  let p = pos;
  let changed;

  do {
    changed = false;

    for (const v of dirichletVecs) {
      const t = ops.div(dot(p, v), dot(v, v));
      if (t <= -0.5 || t > 0.5+eps) {
        p = ops.minus(p, ops.times(ops.round(t), v));
        changed = true;
      }
    }
  } while (changed);

  return p;
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
  };

  console.log(reducedLatticeBasis([[16,3], [5,1]]));
  console.log(reducedLatticeBasis([[1,0,0], [1,1,0], [1,1,1]]));

  console.log(shiftedIntoDirichletDomain([3.2, -1.4], [[1,0],[0,1],[1,1]]));
}
<commit_msg>better test output formatting<commit_after>import { floatMatrices } from '../arithmetic/types';

const ops = floatMatrices;
const eps = Math.pow(2, -50);

const trim = x => Math.abs(x) < eps ? 0 : x;
const lift = op => (...args) => args.reduce((a, b) => op(a, b));
const sum  = lift(ops.plus);

const gaussReduced = (u, v, dot = ops.times) => {
  const vs   = [u, v];
  const norm = v => dot(v, v);

  while (true) {
    const [i, j] = ops.lt(norm(vs[0]), norm(vs[1])) ? [0, 1] : [1, 0];
    const t = ops.round(ops.div(dot(vs[0], vs[1]), norm(vs[i])));
    vs[j] = ops.minus(vs[j], ops.times(t, vs[i]));
    if (ops.ge(norm(vs[j]), ops.times(norm(vs[i]), 1-eps)))
      break;
  }

  if (ops.gt(dot(vs[0], vs[1]), 0))
    vs[1] = ops.negative(vs[1]);

  return vs;
};

const sellingReduced = (u, v, w, dot = ops.times) => {
  const vs   = [u, v, w, ops.negative(sum(u, v, w))];
  let changed;

  do {
    changed = false;

    for (let i = 0; i < 3; ++i) {
      for (let j = i+1; j < 4; ++j) {
	if (ops.gt(dot(vs[i], vs[j]), eps)) {
	  for (let k = 0; k < 4; ++k) {
	    if (k != i && k != j) {
	      vs[k] = sum(vs[k], vs[i]);
	    }
	  }
	  vs[i] = ops.negative(vs[i]);
	  changed = true;
	}
      }
    }
  } while (changed);

  return vs.slice(0, 3);
};

const dirichletVectors = (basis, dot = ops.times) => {
  switch (basis.length) {
  case 0:
  case 1:
    return basis;
  case 2: {
    const vs = gaussReduced(...basis, dot);
    return [vs[0], vs[1], sum(vs[0], vs[1])];
  }
  case 3: {
    const vs = sellingReduced(...basis, dot);
    return [
      vs[0], vs[1], vs[2],
      sum(vs[0], vs[1]), sum(vs[0], vs[2]), sum(vs[1], vs[2]),
      sum(vs[0], vs[1], vs[2])
    ]
  }
  }
};

const compareVectors = dot => (v, w) => {
  const abs = v => v.map(x => Math.abs(x));
  const cmp = (v, w) => (v > w) - (v < w);

  return ops.minus(dot(v, v), dot(w, w)) || cmp(abs(w), abs(v));
};

const reducedLatticeBasis = (vs, dot = ops.times) => {
  const dim = vs[0].length;
  const tmp = dirichletVectors(vs, dot).sort(compareVectors(dot));
  const A = [];

  const _normalized = v => {
    let t = v.map(trim);
    if (t < ops.times(0, t))
      t = ops.negative(t);
    if (A.length > 0 && ops.gt(dot(A[0], t), 0))
      t = ops.negative(t);
    return t;
  };

  for (let k = 0, i = 0; k < tmp.length && i < dim; ++k) {
    A[i] = _normalized(tmp[k]);
    if (ops.rank(A) > i)
      ++i;
  }

  return A;
};

const shiftedIntoDirichletDomain = (pos, dirichletVecs, dot = ops.times) => {
  let p = pos;
  let changed;

  do {
    changed = false;

    for (const v of dirichletVecs) {
      const t = ops.div(dot(p, v), dot(v, v));
      if (t <= -0.5 || t > 0.5+eps) {
        p = ops.minus(p, ops.times(ops.round(t), v));
        changed = true;
      }
    }
  } while (changed);

  return p;
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
  };

  console.log(`${reducedLatticeBasis([[16,3], [5,1]])}`);
  console.log(`${reducedLatticeBasis([[1,0,0], [1,1,0], [1,1,1]])}`);

  console.log(shiftedIntoDirichletDomain([3.2, -1.4], [[1,0],[0,1],[1,1]]));
}
<|endoftext|>


<commit_before>var request = require('request')
var Endpoint = require('./Endpoint')
var HttpErrors = require('http-errors')

/******************************************************************************
 * @class Collection
 * @constructor
 *
 * A Collection is a wrapper around an Endpoint that exposes a higher-level
 * set of methods that abstracts the endpoint as a resource collection.
 *
 */
function Collection(endpoint) {
  this.endpoint = endpoint
}

/**********************************************************************
 * find
 *
 * @param {Object} query (optional)
 * @param {Object} options (optional)
 *
 * Supported calling forms:
 *   find()
 *   find(query)
 *   find(query, options)
 *
 * @return CollectionCursor
 */
Collection.prototype.find = function() {
  return new CollectionCursor(this, arguments)
}

/**********************************************************************
 * _doFind
 *
 * @param {Object} query (optional)
 * @param {Object} options (optional)
 * @param {Function} cb
 *
 * Supported calling forms:
 *   find(cb)
 *   find(query, cb)
 *   find(query, options, cb)
 */
Collection.prototype._doFind = function() {
  var query = undefined
  var options = {}
  var cb = undefined

  if (arguments.length === 1) {
    cb = arguments[0]
  } else if (arguments.length === 2) {
    query = arguments[0]
    cb = arguments[1]
  } else if (arguments.length === 3) {
    query = arguments[0]
    options = arguments[1]
    cb = arguments[2]
  }

  // Create proper get query parameters
  var params = {}
  if (query) {
    params.query = query
  }
  if (options.sort) {
    params.sort = options.sort
  }
  if (options.fields) {
    params.fields = options.fields
  }
  if (options.skip) {
    params.skip = options.skip
  }
  if (options.limit) {
    params.limit = options.limit
  }

  return this.endpoint.get({ params: params }, function(err, res) {
//  return this.endpoint.get({}, function(err, res) {
//  return this.endpoint.get(function(err, res) {
    // XXX using same error for now but may want to abstract away HttpError
    cb(err, res ? res.body : null)
  })
}

/**********************************************************************
 * insert
 *
 * @param {Object} obj // XXX do we support arrays?
 * @param {Function} cb
 *
 * Supported calling forms:
 *   insert(obj, cb)
 */
Collection.prototype.insert = function(obj, cb) {
  return this.endpoint.post(obj, {}, function(err, res) {
    // XXX using same error for now but may want to abstract away HttpError
    cb(err, res.body)
  })
}

/**********************************************************************
 * update
 *
 * @param {Object} query
 * @param {Object} obj
 * @param {Object} options // XXX see leafnode
 * @param {Function} cb
 *
 * Supported calling forms:
 *   update(query, obj, cb)
 *   update(query, obj, options, cb)
 */
Collection.prototype.update = function() {
  var query = {}
  var obj = undefined
  var options = {}
  var cb = undefined

  if (arguments.length === 3) {
    query = arguments[0]
    obj = arguments[1]
    cb = arguments[2]
  } else if (arguments.length === 3) {
    query = arguments[0]
    obj = arguments[1]
    options = arguments[2]
    cb = arguments[3]
  } else {
    throw new Error("Must supply a query and an obj.")
  }

  return this.endpoint.put(query, {}, function(err, res) { // XXX put or patch depending on obj? Hmmm?
    // XXX using same error for now but may want to abstract away HttpError
    cb(err, res.body)
  })
}

/**********************************************************************
 * remove
 *
 * @param {Object} query
 * @param {Object} options // XXX see leafnode
 * @param {Function} cb
 *
 * Supported calling forms:
 *   remove(query, cb)
 *   remove(query, options, cb)
 */
Collection.prototype.remove = function() {
  var query = {}
  var options = {}
  var cb = undefined

  if (arguments.length === 2) {
    query = arguments[0]
    cb = arguments[1]
  } else if (arguments.length === 3) {
    query = arguments[0]
    options = arguments[1]
    cb = arguments[2]
  } else {
    throw new Error("Must supply a query and a cb.")
  }

  return this.endpoint.delete(query, {}, function(err, res) {
    // XXX using same error for now but may want to abstract away HttpError
    cb(err, res.body)
  })
}

/******************************************************************************
 * @class CollectionCursor
 * @constructor
 *
 * A CollectionCursor is a cursor object returned by Collection.find() method and used for iterating over
 * results from find()
 *
 */
function CollectionCursor(collection, findArguments) {
  this.collection = collection
  this.findArguments = parseFindArgs(findArguments)

  this.limit = 1
  this.skip = 0
  this.items = null
  this.nextItemPos = null
  this.done = false
}

/**********************************************************************
 *
 * @param cb
 */
CollectionCursor.prototype.each = function(cb) {
  if (this.done) {
    // NOOP
    return
  }

  var self = this

  function callForeachItem(e) {
    if (self.done) {
      // NOOP
    } else if (e) {
      cb(e)
    } else {
      while (self.nextItemPos in self.items) {
        self._nextObject(cb)
      }

      if (self._needToGetMore()){
        self.getMore(callForeachItem)
      }

    }

  }

  if (this._needToGetMore()) {
    this.getMore(callForeachItem)
  } else {
    callForeachItem()
  }
}

CollectionCursor.prototype.toArray = function(cb) {
  if (this.done) {
    cb()
    return
  }
  this.limit = null
  this.skip = null

  var self = this
  this.getMore(function(e) {
    cb(e, self.items)
    self.done = true
  })

}

/**********************************************************************
 *
 * @param cb
 */
CollectionCursor.prototype.next = function(cb) {

  if (this.done) {
    cb(null, null)
    return
  }

  var self = this

  function nextCallback(e) {
    if (self.done) {
      cb(null, null)
    } else if (e) {
      cb(e)
    } else {
      self._nextObject(cb)
    }

  }

  if (this._needToGetMore()) {
    this.getMore(nextCallback)
  } else {
    this._nextObject(nextCallback)
  }

}

/**********************************************************************
 *
 * @param cb
 */
CollectionCursor.prototype.getMore = function(cb) {

  if ( this.done ) {
    cb()
  }
  var options = {
    skip: this.skip * this.limit,
    limit: this.limit
  }

  var self = this
  this.collection._doFind(this.findArguments.query, options, function(e, data) {
    if (data && data.length > 0) {
      self.skip++
      self.items = data
      self.nextItemPos = 0
      cb()
    } else if (e) {
      cb(e)
    } else {
      self.done = true
      cb()
    }
  })

}

/**********************************************************************
 *
 * @param cb
 * @private
 */
CollectionCursor.prototype._nextObject = function(cb) {
  if (this.items && this.nextItemPos in this.items) {
    var item = this.items[this.nextItemPos]
    this.nextItemPos++
    cb(null, item)
  }

}

/**********************************************************************
 *
 * @returns {boolean}
 * @private
 */
CollectionCursor.prototype._needToGetMore = function() {
  return !this.done && (this.items == null || !(this.nextItemPos in this.items))

}

/**********************************************************************
 *
 * @param cb
 * @private
 */
CollectionCursor.prototype._doMoveEach = function(cb) {
  if (this.items) {
    while (this.nextItemPos in this.items) {
      var item = this.items[this.nextItemPos]
      this.nextItemPos++
      cb(null, item)
    }
      this.items = null
      this.getMore(cb)

  }

}

/**********************************************************************
 *
 * @param findArgs
 * @returns {{query: undefined, options: {}, cb: undefined}}
 */
function parseFindArgs(findArgs) {
  var query = undefined
  var options = {}

  if (arguments.length === 1) {
    query = arguments[0]
  } else if (arguments.length === 2) {
    query = arguments[0]
    options = arguments[1]
  }

  return {
    query: query,
    options: options
  }
}

Collection.collectionCursorClass = CollectionCursor

/**********************************************************************
 * exports
 */
module.exports = Collection

<commit_msg>bump up limit<commit_after>var request = require('request')
var Endpoint = require('./Endpoint')
var HttpErrors = require('http-errors')

/******************************************************************************
 * @class Collection
 * @constructor
 *
 * A Collection is a wrapper around an Endpoint that exposes a higher-level
 * set of methods that abstracts the endpoint as a resource collection.
 *
 */
function Collection(endpoint) {
  this.endpoint = endpoint
}

/**********************************************************************
 * find
 *
 * @param {Object} query (optional)
 * @param {Object} options (optional)
 *
 * Supported calling forms:
 *   find()
 *   find(query)
 *   find(query, options)
 *
 * @return CollectionCursor
 */
Collection.prototype.find = function() {
  return new CollectionCursor(this, arguments)
}

/**********************************************************************
 * _doFind
 *
 * @param {Object} query (optional)
 * @param {Object} options (optional)
 * @param {Function} cb
 *
 * Supported calling forms:
 *   find(cb)
 *   find(query, cb)
 *   find(query, options, cb)
 */
Collection.prototype._doFind = function() {
  var query = undefined
  var options = {}
  var cb = undefined

  if (arguments.length === 1) {
    cb = arguments[0]
  } else if (arguments.length === 2) {
    query = arguments[0]
    cb = arguments[1]
  } else if (arguments.length === 3) {
    query = arguments[0]
    options = arguments[1]
    cb = arguments[2]
  }

  // Create proper get query parameters
  var params = {}
  if (query) {
    params.query = query
  }
  if (options.sort) {
    params.sort = options.sort
  }
  if (options.fields) {
    params.fields = options.fields
  }
  if (options.skip) {
    params.skip = options.skip
  }
  if (options.limit) {
    params.limit = options.limit
  }

  return this.endpoint.get({ params: params }, function(err, res) {
//  return this.endpoint.get({}, function(err, res) {
//  return this.endpoint.get(function(err, res) {
    // XXX using same error for now but may want to abstract away HttpError
    cb(err, res ? res.body : null)
  })
}

/**********************************************************************
 * insert
 *
 * @param {Object} obj // XXX do we support arrays?
 * @param {Function} cb
 *
 * Supported calling forms:
 *   insert(obj, cb)
 */
Collection.prototype.insert = function(obj, cb) {
  return this.endpoint.post(obj, {}, function(err, res) {
    // XXX using same error for now but may want to abstract away HttpError
    cb(err, res.body)
  })
}

/**********************************************************************
 * update
 *
 * @param {Object} query
 * @param {Object} obj
 * @param {Object} options // XXX see leafnode
 * @param {Function} cb
 *
 * Supported calling forms:
 *   update(query, obj, cb)
 *   update(query, obj, options, cb)
 */
Collection.prototype.update = function() {
  var query = {}
  var obj = undefined
  var options = {}
  var cb = undefined

  if (arguments.length === 3) {
    query = arguments[0]
    obj = arguments[1]
    cb = arguments[2]
  } else if (arguments.length === 3) {
    query = arguments[0]
    obj = arguments[1]
    options = arguments[2]
    cb = arguments[3]
  } else {
    throw new Error("Must supply a query and an obj.")
  }

  return this.endpoint.put(query, {}, function(err, res) { // XXX put or patch depending on obj? Hmmm?
    // XXX using same error for now but may want to abstract away HttpError
    cb(err, res.body)
  })
}

/**********************************************************************
 * remove
 *
 * @param {Object} query
 * @param {Object} options // XXX see leafnode
 * @param {Function} cb
 *
 * Supported calling forms:
 *   remove(query, cb)
 *   remove(query, options, cb)
 */
Collection.prototype.remove = function() {
  var query = {}
  var options = {}
  var cb = undefined

  if (arguments.length === 2) {
    query = arguments[0]
    cb = arguments[1]
  } else if (arguments.length === 3) {
    query = arguments[0]
    options = arguments[1]
    cb = arguments[2]
  } else {
    throw new Error("Must supply a query and a cb.")
  }

  return this.endpoint.delete(query, {}, function(err, res) {
    // XXX using same error for now but may want to abstract away HttpError
    cb(err, res.body)
  })
}

/******************************************************************************
 * @class CollectionCursor
 * @constructor
 *
 * A CollectionCursor is a cursor object returned by Collection.find() method and used for iterating over
 * results from find()
 *
 */
function CollectionCursor(collection, findArguments) {
  this.collection = collection
  this.findArguments = parseFindArgs(findArguments)

  this.limit = 100
  this.skip = 0
  this.items = null
  this.nextItemPos = null
  this.done = false
}

/**********************************************************************
 *
 * @param cb
 */
CollectionCursor.prototype.each = function(cb) {
  if (this.done) {
    // NOOP
    return
  }

  var self = this

  function callForeachItem(e) {
    if (self.done) {
      // NOOP
    } else if (e) {
      cb(e)
    } else {
      while (self.nextItemPos in self.items) {
        self._nextObject(cb)
      }

      if (self._needToGetMore()){
        self.getMore(callForeachItem)
      }

    }

  }

  if (this._needToGetMore()) {
    this.getMore(callForeachItem)
  } else {
    callForeachItem()
  }
}

CollectionCursor.prototype.toArray = function(cb) {
  if (this.done) {
    cb()
    return
  }
  this.limit = null
  this.skip = null

  var self = this
  this.getMore(function(e) {
    cb(e, self.items)
    self.done = true
  })

}

/**********************************************************************
 *
 * @param cb
 */
CollectionCursor.prototype.next = function(cb) {

  if (this.done) {
    cb(null, null)
    return
  }

  var self = this

  function nextCallback(e) {
    if (self.done) {
      cb(null, null)
    } else if (e) {
      cb(e)
    } else {
      self._nextObject(cb)
    }

  }

  if (this._needToGetMore()) {
    this.getMore(nextCallback)
  } else {
    this._nextObject(nextCallback)
  }

}

/**********************************************************************
 *
 * @param cb
 */
CollectionCursor.prototype.getMore = function(cb) {

  if ( this.done ) {
    cb()
  }
  var options = {
    skip: this.skip * this.limit,
    limit: this.limit
  }

  var self = this
  this.collection._doFind(this.findArguments.query, options, function(e, data) {
    if (data && data.length > 0) {
      self.skip++
      self.items = data
      self.nextItemPos = 0
      cb()
    } else if (e) {
      cb(e)
    } else {
      self.done = true
      cb()
    }
  })

}

/**********************************************************************
 *
 * @param cb
 * @private
 */
CollectionCursor.prototype._nextObject = function(cb) {
  if (this.items && this.nextItemPos in this.items) {
    var item = this.items[this.nextItemPos]
    this.nextItemPos++
    cb(null, item)
  }

}

/**********************************************************************
 *
 * @returns {boolean}
 * @private
 */
CollectionCursor.prototype._needToGetMore = function() {
  return !this.done && (this.items == null || !(this.nextItemPos in this.items))

}

/**********************************************************************
 *
 * @param cb
 * @private
 */
CollectionCursor.prototype._doMoveEach = function(cb) {
  if (this.items) {
    while (this.nextItemPos in this.items) {
      var item = this.items[this.nextItemPos]
      this.nextItemPos++
      cb(null, item)
    }
      this.items = null
      this.getMore(cb)

  }

}

/**********************************************************************
 *
 * @param findArgs
 * @returns {{query: undefined, options: {}, cb: undefined}}
 */
function parseFindArgs(findArgs) {
  var query = undefined
  var options = {}

  if (arguments.length === 1) {
    query = arguments[0]
  } else if (arguments.length === 2) {
    query = arguments[0]
    options = arguments[1]
  }

  return {
    query: query,
    options: options
  }
}

Collection.collectionCursorClass = CollectionCursor

/**********************************************************************
 * exports
 */
module.exports = Collection

<|endoftext|>


<commit_before>/*
 * Copyright 2010 Acuminous Ltd / Energized Work Ltd
 *
 * 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
 *
 *     http://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.
 */

/* jslint node: true */
"use strict";

var $ = require('./Array');
var RegularExpression = require('./RegularExpression');

// Understands term definitions
var Dictionary = function(prefix) {

    /* jslint shadow: true */
    var prefix = prefix || '$';
    var definitions = {};
    var term_pattern = new RegularExpression(new RegExp('(?:^|[^\\\\])\\' + prefix + '(\\w+)', 'g'));
    var _this = this;

    this.define = function(term, pattern) {
        if (this.is_defined(term)) throw new Error('Duplicate term: [' + term + ']');
        definitions[term] = normalise(pattern);
        return this;
    };

    this.is_defined = function(term) {
        return definitions[term];
    };

    this.merge = function(other) {
        if (other._prefix() != this._prefix()) throw new Error('Cannot merge dictionaries with different prefixes');
        return new Dictionary(prefix)._merge(this)._merge(other);
    };

    this._merge = function(other) {
        other.each_term(this.define.bind(this));
        return this;
    };

    this._prefix = function() {
        return prefix;
    };

    this.each_term = function(callback) {
        for (var term in definitions) {
            callback(term, definitions[term]);
        }
    };

    this.expand = function(term, already_expanding) {
        if (!is_expandable(term)) return term;
        return expand_sub_terms(term, $(already_expanding));
    };

    var expand_sub_terms = function(term, already_expanding) {
        return get_sub_terms(term).each(function(sub_term) {
            if (already_expanding.in_array(sub_term)) throw new Error('Circular Definition: [' + already_expanding.join(', ') + ']');
            var sub_term_pattern = expand_sub_term(sub_term, already_expanding);
            term = term.replace(prefix + sub_term, sub_term_pattern);
            return term;
        });
    };

    var get_sub_terms = function(term) {
        return term_pattern.groups(term);
    };

    var expand_sub_term = function(sub_term, already_expanding) {
        var definition = definitions[sub_term] || '(.+)';
        return is_expandable(definition) ? _this.expand(definition, already_expanding.concat(sub_term)) : definition;
    };

    var normalise = function(definition) {
        return definition.toString().replace(/^\/|\/$/g, '');
    };

    var is_expandable = function(definition) {
        return term_pattern.test(definition);
    };
};

module.exports = Dictionary;
<commit_msg>Renaming term to text<commit_after>/*
 * Copyright 2010 Acuminous Ltd / Energized Work Ltd
 *
 * 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
 *
 *     http://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.
 */

/* jslint node: true */
"use strict";

var $ = require('./Array');
var RegularExpression = require('./RegularExpression');

// Understands term definitions
var Dictionary = function(prefix) {

    /* jslint shadow: true */
    var prefix = prefix || '$';
    var definitions = {};
    var term_pattern = new RegularExpression(new RegExp('(?:^|[^\\\\])\\' + prefix + '(\\w+)', 'g'));
    var _this = this;

    this.define = function(term, pattern) {
        if (this.is_defined(term)) throw new Error('Duplicate term: [' + term + ']');
        definitions[term] = { pattern: normalise(pattern) };
        return this;
    };

    this.is_defined = function(term) {
        return !!definitions[term];
    };

    this.merge = function(other) {
        if (other._prefix() != this._prefix()) throw new Error('Cannot merge dictionaries with different prefixes');
        return new Dictionary(prefix)._merge(this)._merge(other);
    };

    this._merge = function(other) {
        other.each(function(term, definition) {
            _this.define(term, definition.pattern);
        });
        return this;
    };

    this._prefix = function() {
        return prefix;
    };

    this.each = function(callback) {
        for (var term in definitions) {
            callback(term, definitions[term]);
        }
    };

    this.expand = function(text, already_expanding) {
        if (!is_expandable(text)) return text;
        return expand_sub_terms(text, $(already_expanding));
    };

    var expand_sub_terms = function(text, already_expanding) {
        return get_sub_terms(text).each(function(sub_term) {
            if (already_expanding.in_array(sub_term)) throw new Error('Circular Definition: [' + already_expanding.join(', ') + ']');
            var sub_term_pattern = expand_sub_term(sub_term, already_expanding);
            text = text.replace(prefix + sub_term, sub_term_pattern);
            return text;
        });
    };

    var get_sub_terms = function(text) {
        return term_pattern.groups(text);
    };

    var expand_sub_term = function(sub_term, already_expanding) {
        var definition = definitions[sub_term] || { pattern: '(.+)' };
        return is_expandable(definition.pattern) ? _this.expand(definition.pattern, already_expanding.concat(sub_term)) : definition.pattern;
    };

    var normalise = function(pattern) {
        return pattern.toString().replace(/^\/|\/$/g, '');
    };

    var is_expandable = function(text) {
        return term_pattern.test(text);
    };
};

module.exports = Dictionary;
<|endoftext|>


<commit_before>/* globals hopscotch: false */
/*
 * Elements courtesy of https://github.com/gthomas3
 * https://github.com/linkedin/hopscotch/issues/80#issuecomment-48330396
*/
function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
};

function deleteCookie(key) {
  document.cookie = key +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
};

var tour = {
  id: 'hello-spark-on-bluemix',
  steps: [
    {
      target: document.querySelectorAll('.data-nav-title')[0],
      title: 'Welcome to the IBM Bluemix Spark-as-a-Service tl;dr',
      content: 'Hey there!  IBM jStart is honored to be a partner in your journey with Apache Spark, Jupyter Notebooks and OpenStack Object Storage. There\'s plenty of time to read doc and sample code, but join us first on this quick feature fly-by!',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['instances', 'all-instances'],
      title: 'Apache Spark Instances',
      content: 'A multi-tenant Spark cluster means up to 10 separate instances just for you.  As you create \'em, find them here',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['storage'],
      title: 'Object Storage',
      content: 'Jupyter (iPython) notebooks need data from somewhere.  Here\'s your goto spot! A tab that shows you OpenStack Object Storage instances',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['notebooks', 'all-notebooks'],
      title: 'Jupyter Notebooks',
      content: 'Did you notice this tab to show you all of your Jupyter (iPython) notebooks?',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: document.querySelectorAll('.data-page-icon.services')[0],
      title: 'Services',
      content: 'Look here! Here\'s a view to explore getting data into your services',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.data')[0],
      title: 'Data',
      content: 'Got data sources? View and Edit connections for them here',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.analytics')[0],
      title: 'Analytics',
      content: 'Almost done, this is homebase for Spark using notebooks',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.exchange')[0],
      title: 'Exchange',
      content: 'Behind Door #3, check out 200+ Datasets via the Analytics Exchange.',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.notebooks-desc')[0],
      title: 'Precipitation Analysis',
      content: 'Rain, rain go away - check out the Precipitation Analysis notebook for a simple starter',
      placement: 'top',
      arrowOffset: 30
    },
  ],
  showPrevButton: true,
  scrollTopMargin: 100,
  onEnd: function() {
      setCookie("toured", "toured");
  }
  //onClose: function() {
    //setCookie("toured", "toured");
  //}
},

/* ========== */
/* TOUR SETUP */
/* ========== */
addClickListener = function(el, fn) {
  if (el.addEventListener) {
    el.addEventListener('click', fn, false);
  }
  else {
    el.attachEvent('onclick', fn);
  }
},

init = function() {
  var startBtnId = 'startTourBtn',
      calloutId = 'startTourCallout',
      mgr = hopscotch.getCalloutManager(),
      state = hopscotch.getState();

  if (state && state.indexOf('hello-spark-on-bluemix') === 0) {
    // Already started the tour at some point!
    hopscotch.startTour(tour);
  }
  else {
    // Looking at the page for the first(?) time.
    if (!getCookie("toured")) {
        setTimeout(function() {
          mgr.createCallout({
            id: calloutId,
            target: startBtnId,
            placement: 'left',
            title: 'Friend, interested in a tour?',
            content: 'We shall not cease from exploration
And the end of all our exploring
Will be to arrive where we started
And know the place for the first time.
∞T.S. Eliot∞',
            yOffset: -25,
            arrowOffset: 20,
            width: 240
          });
        }, 100);
    }
  }

  addClickListener(document.getElementById(startBtnId), function() {
    if (!hopscotch.isActive) {
      mgr.removeAllCallouts();
      deleteCookie('toured');
      hopscotch.startTour(tour);
    }
  });
};

init();
<commit_msg>Update spark.js<commit_after>/* globals hopscotch: false */
/*
 * Elements courtesy of https://github.com/gthomas3
 * https://github.com/linkedin/hopscotch/issues/80#issuecomment-48330396
*/
function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
};

function deleteCookie(key) {
  document.cookie = key +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
};

var tour = {
  id: 'hello-spark-on-bluemix',
  steps: [
    {
      target: document.querySelectorAll('.data-nav-title')[0],
      title: 'Welcome to the IBM Bluemix Spark-as-a-Service tl;dr',
      content: 'Hey there!  IBM jStart is honored to be a partner in your journey with Apache Spark, Jupyter Notebooks and OpenStack Object Storage. There\'s plenty of time to read doc and sample code, but join us first on this quick feature fly-by!',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['instances', 'all-instances'],
      title: 'Apache Spark Instances',
      content: 'A multi-tenant Spark cluster means up to 10 separate instances just for you.  As you create \'em, find them here',
      placement: 'bottom',
      arrowOffset: 0
    },
    {
      target: ['storage'],
      title: 'Object Storage',
      content: 'Jupyter (iPython) notebooks need data from somewhere.  Here\'s your goto spot! A tab that shows you OpenStack Object Storage instances',
      placement: 'bottom',
      arrowOffset: 0
    },
    {
      target: ['notebooks', 'all-notebooks'],
      title: 'Jupyter Notebooks',
      content: 'Did you notice this tab to show you all of your Jupyter (iPython) notebooks?',
      placement: 'bottom',
      arrowOffset: 0
    },
    {
      target: document.querySelectorAll('.data-page-icon.services')[0],
      title: 'Services',
      content: 'Look here! Here\'s a view to explore getting data into your services',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.data')[0],
      title: 'Data',
      content: 'Got data sources? View and Edit connections for them here',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.analytics')[0],
      title: 'Analytics',
      content: 'Almost done, this is homebase for Spark using notebooks',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.exchange')[0],
      title: 'Exchange',
      content: 'Behind Door #3, check out 200+ Datasets via the Analytics Exchange.',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.notebooks-desc')[0],
      title: 'Precipitation Analysis',
      content: 'Rain, rain go away - check out the Precipitation Analysis notebook for a simple starter',
      placement: 'top',
      arrowOffset: 30
    },
  ],
  showPrevButton: true,
  scrollTopMargin: 100,
  onEnd: function() {
      setCookie("toured", "toured");
  }
  //onClose: function() {
    //setCookie("toured", "toured");
  //}
},

/* ========== */
/* TOUR SETUP */
/* ========== */
addClickListener = function(el, fn) {
  if (el.addEventListener) {
    el.addEventListener('click', fn, false);
  }
  else {
    el.attachEvent('onclick', fn);
  }
},

init = function() {
  var startBtnId = 'startTourBtn',
      calloutId = 'startTourCallout',
      mgr = hopscotch.getCalloutManager(),
      state = hopscotch.getState();

  if (state && state.indexOf('hello-spark-on-bluemix') === 0) {
    // Already started the tour at some point!
    hopscotch.startTour(tour);
  }
  else {
    // Looking at the page for the first(?) time.
    if (!getCookie("toured")) {
        setTimeout(function() {
          mgr.createCallout({
            id: calloutId,
            target: startBtnId,
            placement: 'left',
            title: 'Friend, interested in a tour?',
            content: 'We shall not cease from exploration
And the end of all our exploring
Will be to arrive where we started
And know the place for the first time.
∞T.S. Eliot∞',
            yOffset: -25,
            arrowOffset: 20,
            width: 240
          });
        }, 100);
    }
  }

  addClickListener(document.getElementById(startBtnId), function() {
    if (!hopscotch.isActive) {
      mgr.removeAllCallouts();
      deleteCookie('toured');
      hopscotch.startTour(tour);
    }
  });
};

init();
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const ChunkGroup = require("./ChunkGroup");

class Entrypoint extends ChunkGroup {
	constructor(name) {
		super(name);
		this.runtimeChunk = undefined;
	}

	isInitial() {
		return true;
	}

	getFiles() {
		const files = new Set();

		for(let chunkIdx = 0; chunkIdx < this.chunks.length; chunkIdx++) {
			for(let fileIdx = 0; fileIdx < this.chunks[chunkIdx].files.length; fileIdx++) {
				files.add(this.chunks[chunkIdx].files[fileIdx]);
			}
		}

		return Array.from(files);
	}

	setRuntimeChunk(chunk) {
		this.runtimeChunk = chunk;
	}

	getRuntimeChunk() {
		return this.runtimeChunk || this.chunks[0];
	}
}

module.exports = Entrypoint;
<commit_msg>Simplify for loop in EntryPoint.getFiles<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const ChunkGroup = require("./ChunkGroup");

class Entrypoint extends ChunkGroup {
	constructor(name) {
		super(name);
		this.runtimeChunk = undefined;
	}

	isInitial() {
		return true;
	}

	getFiles() {
		const files = new Set();

		for(const chunk of this.chunks) {
			for(const file of chunk) {
				files.add(file);
			}
		}

		return Array.from(files);
	}

	setRuntimeChunk(chunk) {
		this.runtimeChunk = chunk;
	}

	getRuntimeChunk() {
		return this.runtimeChunk || this.chunks[0];
	}
}

module.exports = Entrypoint;
<|endoftext|>


<commit_before>import dayjs from '../dayjs.js'
import i18n from '@/plugins/i18n'

function dateShort(dateTimeString){
  return dayjs.utc(dateTimeString).format(i18n.tc('global.datetime.dateShort'))
}

function dateLong(dateTimeString){
  return dayjs.utc(dateTimeString).format(i18n.tc('global.datetime.dateLong'))
}

function hourShort(dateTimeString){
  return dayjs.utc(dateTimeString).format(i18n.tc('global.datetime.hourShort'))
}

// short format of dateTime range
// doesn't repeat end date if on the same day
function rangeShort(start, end){
  let result = ''

  result += dateShort(start)
  result += ' '
  result += hourShort(start)

  result += ' - '

  if( dateShort(start) !== dateShort(end) ){
    result += dateShort(end)
    result += ' '
  }

  result += hourShort(end)

  return result
}

export {
  dateShort,
  dateLong,
  hourShort,
  rangeShort
}
<commit_msg>linter<commit_after>import dayjs from '../dayjs.js'
import i18n from '@/plugins/i18n'

function dateShort (dateTimeString) {
  return dayjs.utc(dateTimeString).format(i18n.tc('global.datetime.dateShort'))
}

function dateLong (dateTimeString) {
  return dayjs.utc(dateTimeString).format(i18n.tc('global.datetime.dateLong'))
}

function hourShort (dateTimeString) {
  return dayjs.utc(dateTimeString).format(i18n.tc('global.datetime.hourShort'))
}

// short format of dateTime range
// doesn't repeat end date if on the same day
function rangeShort (start, end) {
  let result = ''

  result += dateShort(start)
  result += ' '
  result += hourShort(start)

  result += ' - '

  if (dateShort(start) !== dateShort(end)) {
    result += dateShort(end)
    result += ' '
  }

  result += hourShort(end)

  return result
}

export {
  dateShort,
  dateLong,
  hourShort,
  rangeShort
}
<|endoftext|>