<commit_before>var fs = require('fs')
  , tessel = require('tessel')
  , envfile = require('envfile')
  , config = envfile.parseFileSync(__dirname + '/../config.env')
  , ssh = require('./tessel-ssh')
  ;

function sftpDeploy(opts, push) {
  var filepath = '/tmp/remote_script';
  if (push) {
    filepath = 'pushfolder';
  }

  tessel.logs.info('Connecting to remote Tessel...');

  // Create a new SSH client connection object
  ssh.createConnection(function(err, conn) {

    // Throw any errors that pop up
    if (err) throw err;

    // Log that it was successful
    tessel.logs.info('Connected.');

    tessel.logs.info('Bundling up code...');
    // Command V2 to extract a tarball it receives on stdin to the remote deploy dir
    conn.exec('mkdir -p ' + filepath + '/; rm -rf ' + filepath + '/*; tar -x -C ' + filepath, function(err, rstdin) {
      // Gather details about the file structure of the script being sent
      var ret = tessel.analyzeScript(process.cwd() + "/" + opts.entryPoint, {verbose: opts.verbose});
      // Tar up the code to improve transfer rates
      tessel.tarCode(ret.pushdir, {node: true}, function(err, bundle) {
        tessel.logs.info('Bundled.')
        // Throw any unfortunate errors
        if (err) throw err;

        tessel.logs.info('Deploying code of size', ret.size, 'bytes ...');
        // Write the zipped code to stdin on v2
        rstdin.end(bundle);

        // Wait for the transfer to finish...
        rstdin.once('finish', function() {
          tessel.logs.info('Deployed.');
          if (push) {
            tessel.logs.info('You may now disconnect from the Tessel. Your code will be run whenever Tessel boots up. To remove this code, use `tessel erase`.');
          }
          tessel.logs.info('Running script...');
          // Once it has been written, run the script with Node
          conn.exec('node ' + filepath + '/' + ret.relpath, function(err, stream) {
            if (err) throw err;
            stream.on('close', function(code, signal) {
              stream.signal('KILL');
              conn.end();
            }).on('data', function(data) {
              console.log(data.toString());
            }).stderr.on('data', function(data) {
              console.log("Err: ", data.toString());
              stream.signal('KILL');
              conn.end();
            });
          });
        });
      });
    });
  });
}

module.exports.sftpDeploy = sftpDeploy;
<commit_msg>fixed merge conflicts<commit_after>var fs = require('fs')
  , tessel = require('tessel')
  , envfile = require('envfile')
  , config = envfile.parseFileSync(__dirname + '/../config.env')
  , ssh = require('./tessel-ssh')
  ;

function sftpDeploy(opts, push) {
  var filepath = '/tmp/remote_script';
  if (push) {
    filepath = 'pushfolder';
  }

  tessel.logs.info('Connecting to remote Tessel...');

  // Create a new SSH client connection object
  ssh.createConnection(function(err, conn) {

    // Throw any errors that pop up
    if (err) throw err;

    // Log that it was successful
    tessel.logs.info('Connected.');

    tessel.logs.info('Bundling up code...');
    // Command V2 to extract a tarball it receives on stdin to the remote deploy dir
    conn.exec('mkdir -p ' + filepath + '/; rm -rf ' + filepath + '/*; tar -x -C ' + filepath, function(err, rstdin) {
      rstdin.on('error', function(e) {
        tessel.logs.error("Unable to deploy code:", e);
        process.exit(1);
      });

      // Gather details about the file structure of the script being sent
      var ret = tessel.analyzeScript(process.cwd() + "/" + opts.entryPoint, {verbose: opts.verbose});
      // Tar up the code to improve transfer rates
      tessel.tarCode(ret.pushdir, {node: true}, function(err, bundle) {
        tessel.logs.info('Bundled.')
        // Throw any unfortunate errors
        if (err) throw err;

        tessel.logs.info('Deploying code of size', ret.size, 'bytes ...');

        // Wait for the transfer to finish...
        rstdin.once('finish', function() {
          tessel.logs.info('Deployed.');
          if (push) {
            tessel.logs.info('You may now disconnect from the Tessel. Your code will be run whenever Tessel boots up. To remove this code, use `tessel erase`.');
          }
          tessel.logs.info('Running script...');
          // Once it has been written, run the script with Node
          conn.exec('node ' + filepath + '/' + ret.relpath, function(err, stream) {
            if (err) throw err;
            stream.on('close', function(code, signal) {
              stream.signal('KILL');
              conn.end();
            }).on('data', function(data) {
              console.log(data.toString());
            }).stderr.on('data', function(data) {
              console.log("Err: ", data.toString());
              stream.signal('KILL');
              conn.end();
            });
          });
        });
        rstdin.end(bundle);
      });
    });
  });
}

module.exports.sftpDeploy = sftpDeploy;
<|endoftext|>


<commit_before>'use strict';

const
	EnrollClient = require('./enroll'),
	RecognizeClient = require('./recognize');

/**
 * mashape-animetrics-face-api module
 * @class Detect
 * @constructor
 */

class Detect {
	constructor(images, request) {
		if (!images.length)
			throw new Error('No images in response');

		this.request = request;

		this.faces = images[0].faces && images[0].faces.slice() || [];

		delete images[0].faces;
		this.image = images[0];
	}

	/**
	 * Get image data
	 * @method getImage
	 * @return {Object} The image object
	 */

	getImage() {
		return this.image
	}

	/**
	 * Get faces list
	 * @method getFaces
	 * @return {Array} The list of faces
	 */

	getFaces() {
		return this.faces
	}

	/**
	 * Get faces count
	 * @method getFacesCount
	 * @return {Integer} The count of faces
	 */

	getFacesCount() {
		return this.faces.length
	}

	/**
	 * Check if the image has faces found
	 * @method hasFaces
	 * @return {Boolean}
	 */

	hasFaces() {
		return this.faces.length > 0 || false
	}

	/**
	 * Get face by index
	 * @method getFace
	 * @param {Integer} index Face index
	 * @return {Object}
	 */
	getFace(index = 0) {

		if (this.faces.length <= index)
			throw new Error('Face index is out of range');

		return this.faces[index]
	}

	/**
	 * Enrol one face from image
	 * @method enroll
	 * @param {String} galleryId Gallery id
	 * @param {String} subjectId Subject id
	 * @param {Integer} index Face index
	 * @return {Enroll}
	 */
	enroll(galleryId, subjectId, index = 0) {
		return new EnrollClient(this.request, this.image, this.getFace(index)).execute(galleryId, subjectId)
	}

	/**
	 * Recognize image from detect
	 * @method recognize
	 * @param {String} galleryId Gallery id
	 * @param {Integer} index Face index
	 * @return {Recognize}
	 */

	recognize(galleryId, index = 0) {
		return new RecognizeClient(this.request).execute(galleryId, this.image, this.getFace(index))
	}
}

/**
 * mashape-animetrics-face-api module
 * @class DetectClient
 * @constructor
 */

class DetectClient {

	constructor(request) {
		this.request = request;
		this.path = '/detect'
	}

	/**
	 * Get detector from url
	 * @method fromUrl
	 * @param {String} url Image url
	 * @param {String} selector Selectors for find filter, default: FULL, ex: 'FACE, EYES, FULL'
	 * @return {Detect} Instance of detect class
	 */

	fromUrl(url, selector = 'FULL') {

		return this.request.post(this.path, {
			url,
			selector
		})
			.then(response => {
				return new Detect(
					response.body.images,
					this.request
				);
			})
	}

}

module.exports = DetectClient;
<commit_msg>Update detect.js<commit_after>'use strict';

const
	EnrollClient = require('./enroll'),
	RecognizeClient = require('./recognize');

/**
 * mashape-animetrics-face-api module
 * @class Detect
 * @constructor
 */

class Detect {
	constructor(images, request) {
		if (!images.length)
			throw new Error('No images in response');

		this.request = request;

		this.faces = images[0].faces && images[0].faces.slice() || [];
		console.log('from detect:', this.faces);
		delete images[0].faces;
		this.image = images[0];
	}

	/**
	 * Get image data
	 * @method getImage
	 * @return {Object} The image object
	 */

	getImage() {
		return this.image
	}

	/**
	 * Get faces list
	 * @method getFaces
	 * @return {Array} The list of faces
	 */

	getFaces() {
		return this.faces
	}

	/**
	 * Get faces count
	 * @method getFacesCount
	 * @return {Integer} The count of faces
	 */

	getFacesCount() {
		return this.faces.length
	}

	/**
	 * Check if the image has faces found
	 * @method hasFaces
	 * @return {Boolean}
	 */

	hasFaces() {
		return this.faces.length > 0 || false
	}

	/**
	 * Get face by index
	 * @method getFace
	 * @param {Integer} index Face index
	 * @return {Object}
	 */
	getFace(index = 0) {

		if (this.faces.length <= index)
			throw new Error('Face index is out of range');

		return this.faces[index]
	}

	/**
	 * Enrol one face from image
	 * @method enroll
	 * @param {String} galleryId Gallery id
	 * @param {String} subjectId Subject id
	 * @param {Integer} index Face index
	 * @return {Enroll}
	 */
	enroll(galleryId, subjectId, index = 0) {
		return new EnrollClient(this.request, this.image, this.getFace(index)).execute(galleryId, subjectId)
	}

	/**
	 * Recognize image from detect
	 * @method recognize
	 * @param {String} galleryId Gallery id
	 * @param {Integer} index Face index
	 * @return {Recognize}
	 */

	recognize(galleryId, index = 0) {
		return new RecognizeClient(this.request).execute(galleryId, this.image, this.getFace(index))
	}
}

/**
 * mashape-animetrics-face-api module
 * @class DetectClient
 * @constructor
 */

class DetectClient {

	constructor(request) {
		this.request = request;
		this.path = '/detect'
	}

	/**
	 * Get detector from url
	 * @method fromUrl
	 * @param {String} url Image url
	 * @param {String} selector Selectors for find filter, default: FULL, ex: 'FACE, EYES, FULL'
	 * @return {Detect} Instance of detect class
	 */

	fromUrl(url, selector = 'FULL') {

		return this.request.post(this.path, {
			url,
			selector
		})
			.then(response => {
				return new Detect(
					response.body.images,
					this.request
				);
			})
	}

}

module.exports = DetectClient;
<|endoftext|>


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

  var app = document.querySelector( '#app' );

  app.appName = "Analiz";

  /**
   * Require modules
   */
  app.remote = require( 'remote' );
  app.npm = require( 'npm' );
  app.async = require( 'async' );
  app.categories = require( './categories.js' );
  app.getFilters = require( './moduleLister.js' );
  app.directory = require( 'directory-tree' );
  app.directory.fs = require( 'fs' );
  app.directory.path = require( 'path' );
  app.dateFormat = require( 'dateformat' );
  app.i18n = require("i18n");
  var settingsFile = app.directory.path.resolve( __dirname, '..', 'settings.json' );
  app.settings = require( settingsFile );

  app.npmPrefix = app.directory.path.resolve( __dirname, '..' );

  /**
   * Configure i18n
   */
  app.i18n.configure({
    locales:['en', 'fr'],
    defaultLocale: app.settings.language,
    directory: app.directory.path.resolve(app.npmPrefix, 'locales')
  });

  app.__ = function ( string ) {
    return app.i18n.__( string );
  };

  /**
   * Get the categories list with the correct structure
   */
  app.categoriesList = [];
  Object.getOwnPropertyNames(app.categories).forEach( function ( element, index, array ) {
    app.categoriesList.push( app.categories[element] );
  } );

  /**
   * Show a toast
   * @param  {String} message Toast message
   */
  app.toast = function ( message ) {
    var toast = document.getElementById('toast');

    toast.text = message;
    toast.show();
  };

  /**
   * Get the filters from the external plugins
   */
  app.filters = [];
  app.getFilters();

  /**
   * Analyze config object
   */
  app.analyzeConfig = {
    path: '',
    plugins: [],

    set: function ( property, value ) {
      this[property] = value;
      // If the path and the config are set show the 'Analiz !' button
      document.getElementById( 'analyzeButton' ).disabled = ( this.path && this.plugins.length === 0 );
    }
  };

  app.analyzeResults = [];
  app.currentPlugin = {};

  /**
   * The analyse function
   * @param  {Object} data Data configuration object
   */
  app.analiz = function ( data ) {
    var files;

    app.loadingModal.set( 'data.pluginTotal', data.plugins.length);
    // Open the loader modal
    app.loadingModal.open();

    // Get all the files in the directory
    walk( data.path, function ( err, files ) {
      // Run the plugins one by one
      data.plugins.forEach( function ( plugin, index ) {
        // Prepare the parameters
        var parameters = {
          files: [],
          options: {}
        };

        // Get the files the plugin need
        files.forEach( function( file ) {
          if ( plugin.config.fileTypes.indexOf( app.directory.path.extname( file ) ) >= 0 ) {
            parameters.files.push( file );
          }
        } );

        // Get the options the plugin need
        plugin.config.options.forEach( function( option ) {
          parameters.options[option.name] = option;
        } );

        // Set the loading data for the current plugin
        app.loadingModal.push( 'data.name', plugin.config.name );
        app.loadingModal.set( 'data.fileTotal', parameters.files.length );

        app.currentPlugin = plugin.config;
        app.currentPlugin.id = index;

        // Run the plugin
        plugin.run( parameters.files, parameters.options, app.loadingResults );
      } );
    } );
  };

  app.loadingResults = function ( error, results ) {
    // Store the analyze results
    if ( !app.analyzeResults[app.currentPlugin.id] ) {
      app.analyzeResults[app.currentPlugin.id] = {
        name: app.currentPlugin.name,
        category: app.currentPlugin.category,
        options: app.currentPlugin.options,
        data: []
      };
    }
    app.analyzeResults[app.currentPlugin.id].data.push( results );

    // Set the file progress
    app.loadingModal.set( 'data.fileCount', app.loadingModal.data.fileCount + 1 );
    app.loadingModal.set( 'data.fileValue', Math.round( ( 100 * app.loadingModal.data.fileCount ) / app.loadingModal.data.fileTotal ));
    // Verify if all the files for the current plugin has been analyzed
    if ( app.loadingModal.data.fileCount == app.loadingModal.data.fileTotal ) {
      // Set the plugin progress
      app.loadingModal.set( 'data.pluginCount', app.loadingModal.data.pluginCount + 1 );
      app.loadingModal.set( 'data.pluginValue', Math.round( ( 100 * app.loadingModal.data.pluginCount ) / app.loadingModal.data.pluginTotal ));
      // Verify if the analyze is over
      if ( app.loadingModal.data.pluginCount == app.loadingModal.data.pluginTotal ) {
        app.isLoaded( app.analyzeResults );
      } else {
        app.loadingModal.set( 'data.fileCount', 0);
      }
    }
  };

  app.isLoaded = function ( results ) {
    // Close the modal, reset the loader and show the audit page
    document.querySelector('loading-modal').close();
    setTimeout(function () {
      document.querySelector('loading-modal').reset();
    }, 500);
    app.toast( app.__( 'Scan completed!' ) );

    app.analyzeResults = [];

    document.querySelector('page-audit').set('data', results);

    app.isAudit = true;
    app.selected = 2;
  };

  app.isAudit = false;

  app.changeTab = function ( e ) {
    document.querySelector( 'page-audit #pages' ).selected = 0;
  };

  // Default page
  app.selected = 0;

  var i = 0;

  window.addEventListener( 'WebComponentsReady', function() {
    document.querySelector( 'body' ).removeAttribute( 'unresolved' );
    app.isNarrow = document.getElementById('paperDrawerPanel').narrow;

    app.loadingModal = document.querySelector('loading-modal');
  });

  // About dialog
  app.aboutOpen = function ( e ) {
    document.querySelector( '.settings-dropdown' ).close();
    document.querySelector( 'about-dialog paper-dialog' ).open();
  };

  app.changeLanguage = function ( e ) {
    app.settings.language = (app.settings.language == 'fr') ? 'en' : 'fr';
    app.directory.fs.writeFileSync( settingsFile, JSON.stringify(app.settings) );

    app.remote.getCurrentWindow().reload();
  };

  app.filterResults = function ( e ) {
    app.changeTab();
    document.querySelector( '.result-card-' + e.detail.name ).classList.toggle( 'hide-result-card' );
  };

  app.computeItemLanguage = function ( item ) {
    return item[app.settings.language];
  };

  var walk = function(dir, done) {
    var results = [];
    app.directory.fs.readdir(dir, function(err, list) {
      if (err) return done(err);
      var pending = list.length;
      if (!pending) return done(null, results);
      list.forEach(function(file) {
        file = app.directory.path.resolve(dir, file);
        app.directory.fs.stat(file, function(err, stat) {
          if (stat && stat.isDirectory()) {
            walk(file, function(err, res) {
              results = results.concat(res);
              if (!--pending) done(null, results);
            });
          } else {
            results.push(file);
            if (!--pending) done(null, results);
          }
        });
      });
    });
  };

})(document);
<commit_msg>Change the option object structure<commit_after>(function ( document ) {
  'use strict';

  var app = document.querySelector( '#app' );

  app.appName = "Analiz";

  /**
   * Require modules
   */
  app.remote = require( 'remote' );
  app.npm = require( 'npm' );
  app.async = require( 'async' );
  app.categories = require( './categories.js' );
  app.getFilters = require( './moduleLister.js' );
  app.directory = require( 'directory-tree' );
  app.directory.fs = require( 'fs' );
  app.directory.path = require( 'path' );
  app.dateFormat = require( 'dateformat' );
  app.i18n = require("i18n");
  var settingsFile = app.directory.path.resolve( __dirname, '..', 'settings.json' );
  app.settings = require( settingsFile );

  app.npmPrefix = app.directory.path.resolve( __dirname, '..' );

  /**
   * Configure i18n
   */
  app.i18n.configure({
    locales:['en', 'fr'],
    defaultLocale: app.settings.language,
    directory: app.directory.path.resolve(app.npmPrefix, 'locales')
  });

  app.__ = function ( string ) {
    return app.i18n.__( string );
  };

  /**
   * Get the categories list with the correct structure
   */
  app.categoriesList = [];
  Object.getOwnPropertyNames(app.categories).forEach( function ( element, index, array ) {
    app.categoriesList.push( app.categories[element] );
  } );

  /**
   * Show a toast
   * @param  {String} message Toast message
   */
  app.toast = function ( message ) {
    var toast = document.getElementById('toast');

    toast.text = message;
    toast.show();
  };

  /**
   * Get the filters from the external plugins
   */
  app.filters = [];
  app.getFilters();

  /**
   * Analyze config object
   */
  app.analyzeConfig = {
    path: '',
    plugins: [],

    set: function ( property, value ) {
      this[property] = value;
      // If the path and the config are set show the 'Analiz !' button
      document.getElementById( 'analyzeButton' ).disabled = ( this.path && this.plugins.length === 0 );
    }
  };

  app.analyzeResults = [];
  app.currentPlugin = {};

  /**
   * The analyse function
   * @param  {Object} data Data configuration object
   */
  app.analiz = function ( data ) {
    var files;

    app.loadingModal.set( 'data.pluginTotal', data.plugins.length);
    // Open the loader modal
    app.loadingModal.open();

    // Get all the files in the directory
    walk( data.path, function ( err, files ) {
      // Run the plugins one by one
      data.plugins.forEach( function ( plugin, index ) {
        // Prepare the parameters
        var parameters = {
          files: [],
          options: {}
        };

        // Get the files the plugin need
        files.forEach( function( file ) {
          if ( plugin.config.fileTypes.indexOf( app.directory.path.extname( file ) ) >= 0 ) {
            parameters.files.push( file );
          }
        } );

        // Get the options the plugin need
        plugin.config.options.forEach( function( option ) {
          parameters.options[option.name] = option.data;
        } );

        // Set the loading data for the current plugin
        app.loadingModal.push( 'data.name', plugin.config.name );
        app.loadingModal.set( 'data.fileTotal', parameters.files.length );

        app.currentPlugin = plugin.config;
        app.currentPlugin.id = index;

        // Run the plugin
        plugin.run( parameters.files, parameters.options, app.loadingResults );
      } );
    } );
  };

  app.loadingResults = function ( error, results ) {
    // Store the analyze results
    if ( !app.analyzeResults[app.currentPlugin.id] ) {
      app.analyzeResults[app.currentPlugin.id] = {
        name: app.currentPlugin.name,
        category: app.currentPlugin.category,
        options: app.currentPlugin.options,
        data: []
      };
    }
    app.analyzeResults[app.currentPlugin.id].data.push( results );

    // Set the file progress
    app.loadingModal.set( 'data.fileCount', app.loadingModal.data.fileCount + 1 );
    app.loadingModal.set( 'data.fileValue', Math.round( ( 100 * app.loadingModal.data.fileCount ) / app.loadingModal.data.fileTotal ));
    // Verify if all the files for the current plugin has been analyzed
    if ( app.loadingModal.data.fileCount == app.loadingModal.data.fileTotal ) {
      // Set the plugin progress
      app.loadingModal.set( 'data.pluginCount', app.loadingModal.data.pluginCount + 1 );
      app.loadingModal.set( 'data.pluginValue', Math.round( ( 100 * app.loadingModal.data.pluginCount ) / app.loadingModal.data.pluginTotal ));
      // Verify if the analyze is over
      if ( app.loadingModal.data.pluginCount == app.loadingModal.data.pluginTotal ) {
        app.isLoaded( app.analyzeResults );
      } else {
        app.loadingModal.set( 'data.fileCount', 0);
      }
    }
  };

  app.isLoaded = function ( results ) {
    // Close the modal, reset the loader and show the audit page
    document.querySelector('loading-modal').close();
    setTimeout(function () {
      document.querySelector('loading-modal').reset();
    }, 500);
    app.toast( app.__( 'Scan completed!' ) );

    app.analyzeResults = [];

    document.querySelector('page-audit').set('data', results);

    app.isAudit = true;
    app.selected = 2;
  };

  app.isAudit = false;

  app.changeTab = function ( e ) {
    document.querySelector( 'page-audit #pages' ).selected = 0;
  };

  // Default page
  app.selected = 0;

  var i = 0;

  window.addEventListener( 'WebComponentsReady', function() {
    document.querySelector( 'body' ).removeAttribute( 'unresolved' );
    app.isNarrow = document.getElementById('paperDrawerPanel').narrow;

    app.loadingModal = document.querySelector('loading-modal');
  });

  // About dialog
  app.aboutOpen = function ( e ) {
    document.querySelector( '.settings-dropdown' ).close();
    document.querySelector( 'about-dialog paper-dialog' ).open();
  };

  app.changeLanguage = function ( e ) {
    app.settings.language = (app.settings.language == 'fr') ? 'en' : 'fr';
    app.directory.fs.writeFileSync( settingsFile, JSON.stringify(app.settings) );

    app.remote.getCurrentWindow().reload();
  };

  app.filterResults = function ( e ) {
    app.changeTab();
    document.querySelector( '.result-card-' + e.detail.name ).classList.toggle( 'hide-result-card' );
  };

  app.computeItemLanguage = function ( item ) {
    return item[app.settings.language];
  };

  var walk = function(dir, done) {
    var results = [];
    app.directory.fs.readdir(dir, function(err, list) {
      if (err) return done(err);
      var pending = list.length;
      if (!pending) return done(null, results);
      list.forEach(function(file) {
        file = app.directory.path.resolve(dir, file);
        app.directory.fs.stat(file, function(err, stat) {
          if (stat && stat.isDirectory()) {
            walk(file, function(err, res) {
              results = results.concat(res);
              if (!--pending) done(null, results);
            });
          } else {
            results.push(file);
            if (!--pending) done(null, results);
          }
        });
      });
    });
  };

})(document);
<|endoftext|>


<commit_before>const jsonGate = require( 'json-gate' );
const libgpib = require( '../build/Release/gpib.node' );
const Status = require( './status.js' );
const IBError = require( './error.js' );

const timeoutConstants = [
	'TNONE',
	'T10us',
	'T30us',
	'T100us',
	'T300us',
	'T1ms',
	'T3ms',
	'T10ms',
	'T30ms',
	'T100ms',
	'T300ms',
	'T1s',
	'T3s',
	'T10s',
	'T30s',
	'T100s',
	'T300s',
	'T1000s'
];

const schemaConnect = jsonGate.createSchema( {
	type: 'object',
	additionalProperties: false,
	required: true,
	properties: {
		pad: {
			type: 'integer',
			required: true,
			minimum: 0,
			maximum: 30
		},
		sad: {
			type: 'integer',
			minimum: 0,
			maximum: 30,
			default: 0
		},
		timeout: {
			type: 'string',
			enum: timeoutConstants,
			default: 'T300ms'
		},
		send_eoi: {
			type: 'boolean',
			default: true
		},
		eos: {
			type: 'integer',
			default: 0,
			minimum: 0,
			maximum: 255
		}
	}
} );

class Device {

	constructor( board_index, dev, sem ) {

		schemaConnect.validate( dev );

		this.sem = sem;

		// Convert timeout and send_eoi to int
		dev.timeout = timeoutConstants.indexOf( dev.timeout );
		dev.send_eoi = dev.send_eoi ? 1 : 0;

		// Create handle
		this.ud = libgpib.ibdev(
			board_index,
			dev.pad,
			dev.sad,
			dev.timeout,
			dev.send_eoi,
			dev.eos
		);

		if( this.ud == -1 ) throw new Error( `Cannot connect to PAD ${dev.pad}` );

	}

	_checkCon() {
		if( this.ud == -1 ) throw new Error( "Not connected to a device" );
	}

	disconnect() {
		return this.sem.take().then( () => {
			// Make sure we are still connected
			this._checkCon();

			// Disconnect form device
			const status = libgpib.ibonl( this.ud );
			this.ud = -1;

			// Free resources and return status
			this.sem.leave();
			return new Status( status );
		} );
	}

	write( data ) {
		return this.sem.take().then( () => new Promise( ( resolve, reject ) => {
			// Make sure we are still connected
			this._checkCon();

			libgpib.ibwrt( this.ud, data.toString(), ( err, status, bytesWritten ) => {
				status = new Status( status );

				// Free resources
				this.sem.leave();

				if( status.ERR ) {
					// If error bit is set, throw a new error
					reject( new IBError( err ) );
				} else {
					// Otherwise return written bytes and status
					resolve( [ status, bytesWritten ] );
				}
			} );

		} ) );
	}

}

module.exports = Device;
<commit_msg>Added read command<commit_after>const jsonGate = require( 'json-gate' );
const libgpib = require( '../build/Release/gpib.node' );
const Status = require( './status.js' );
const IBError = require( './error.js' );

const timeoutConstants = [
	'TNONE',
	'T10us',
	'T30us',
	'T100us',
	'T300us',
	'T1ms',
	'T3ms',
	'T10ms',
	'T30ms',
	'T100ms',
	'T300ms',
	'T1s',
	'T3s',
	'T10s',
	'T30s',
	'T100s',
	'T300s',
	'T1000s'
];

const schemaConnect = jsonGate.createSchema( {
	type: 'object',
	additionalProperties: false,
	required: true,
	properties: {
		pad: {
			type: 'integer',
			required: true,
			minimum: 0,
			maximum: 30
		},
		sad: {
			type: 'integer',
			minimum: 0,
			maximum: 30,
			default: 0
		},
		timeout: {
			type: 'string',
			enum: timeoutConstants,
			default: 'T300ms'
		},
		send_eoi: {
			type: 'boolean',
			default: true
		},
		eos: {
			type: 'integer',
			default: 0,
			minimum: 0,
			maximum: 255
		}
	}
} );

class Device {

	constructor( board_index, dev, sem ) {

		schemaConnect.validate( dev );

		this.sem = sem;

		// Convert timeout and send_eoi to int
		dev.timeout = timeoutConstants.indexOf( dev.timeout );
		dev.send_eoi = dev.send_eoi ? 1 : 0;

		// Create handle
		this.ud = libgpib.ibdev(
			board_index,
			dev.pad,
			dev.sad,
			dev.timeout,
			dev.send_eoi,
			dev.eos
		);

		if( this.ud == -1 ) throw new Error( `Cannot connect to PAD ${dev.pad}` );

	}

	_checkCon() {
		if( this.ud == -1 ) throw new Error( "Not connected to a device" );
	}

	disconnect() {
		return this.sem.take().then( () => {
			// Make sure we are still connected
			this._checkCon();

			// Disconnect form device
			const status = libgpib.ibonl( this.ud );
			this.ud = -1;

			// Free resources and return status
			this.sem.leave();
			return new Status( status );
		} );
	}

	write( data ) {
		return this.sem.take().then( () => new Promise( ( resolve, reject ) => {
			// Make sure we are still connected
			this._checkCon();

			libgpib.ibwrt( this.ud, data.toString(), ( err, status, bytesWritten ) => {
				status = new Status( status );

				// Free resources
				this.sem.leave();

				if( status.ERR ) {
					// If error bit is set, throw a new error
					reject( new IBError( err ) );
				} else {
					// Otherwise return written bytes and status
					resolve( bytesWritten );
				}
			} );

		} ) );
	}

	read() {
		return this.sem.take().then( () => new Promise( ( resolve, reject ) => {
			// Make sure we are still connected
			this._checkCon();

			libgpib.ibrd( this.ud, ( err, status, data ) => {
				status = new Status( status );

				// Free resources
				this.sem.leave();

				if( status.ERR ) {
					// If error bit is set, throw a new error
					reject( new IBError( err ) );
				} else {
					// Otherwise return data
					resolve( data );
				}
			} );

		} ) );
	}

}

module.exports = Device;
<|endoftext|>


<commit_before>(function(){
	function config ($locationProvider, $stateProvider){
		$locationProvider
			.html5Mode({
				enabled: true,
				requireBase: false
		});

        $stateProvider
            .state('active', {
                url: '/',
                controller: 'ActiveTaskCtrl as active',
                templateUrl: '/templates/active.html'
            })
			.state('archive',{
				url: '/archive',
				controller: 'ArchiveCtrl as archive',
				templateUrl: 'templates/archive.html'
			});
	}

	angular
		.module('blocitoff', ['ui.router', 'firebase'])
		.config(config);
})();<commit_msg>Small formatting fix<commit_after>(function(){
	function config ($locationProvider, $stateProvider){
		$locationProvider
			.html5Mode({
				enabled: true,
				requireBase: false
			});

		$stateProvider
			.state('active', {
				url: '/',
				controller: 'ActiveTaskCtrl as active',
				templateUrl: '/templates/active.html'
			})
			.state('archive',{
				url: '/archive',
				controller: 'ArchiveCtrl as archive',
				templateUrl: 'templates/archive.html'
			});
	}

	angular
		.module('blocitoff', ['ui.router', 'firebase'])
		.config(config);
})();<|endoftext|>


<commit_before>'use strict';

var app = angular
  .module('seenitApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        controllerAs: 'main'
      })
      .otherwise({
        redirectTo: '/'
      });
    $locationProvider.html5Mode(true);
  });
app.factory('reddit', ['$http', '$q', function($http, $q) {
  var getJSON = function() {
    var deferred = $q.defer();
    $http.get('https://www.reddit.com/r/videos.json?limit=100')
      .success(function(data) {
        var posts = data.data.children;
        posts.forEach(function(post, i) {
          if (post.data.is_self) {
            posts.splice(i, 1);
          }
        });
        deferred.resolve(posts);
      })
      .error(function(err) {
        deferred.reject(err);
      });
    return deferred.promise;
  };
  return {
    getData: getJSON
  };
}]);

app.controller('MainCtrl', ['$scope', 'reddit', function($scope, reddit){
  $scope.data = '';
  reddit.getData().then(function(data) {
    console.log(data);
    $scope.data = data;
  });
}]);
<commit_msg>Add sanitize filter for html (iframe) text<commit_after>'use strict';

var app = angular.module('seenitApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        controllerAs: 'main'
      })
      .otherwise({
        redirectTo: '/'
      });
    $locationProvider.html5Mode(true);
  });

app.filter('sanitize', ['$sce', function($sce) {
  return function(value){
    if (value) {
      return $sce.trustAsHtml(value.replace('<', '<').replace('>', '>'));
    }
  };
}]);

app.factory('reddit', ['$http', '$q', function($http, $q) {
  var getJSON = function() {
    var deferred = $q.defer();
    $http.get('https://www.reddit.com/r/videos.json?limit=100')
      .success(function(data) {
        var posts = data.data.children;
        posts.forEach(function(post, i) {
          if (post.data.is_self) {
            posts.splice(i, 1);
          }
        });
        deferred.resolve(posts);
      })
      .error(function(err) {
        deferred.reject(err);
      });
    return deferred.promise;
  };
  return {
    getData: getJSON
  };
}]);

app.controller('MainCtrl', ['$scope', 'reddit', function($scope, reddit){
  $scope.data = '';
  reddit.getData().then(function(data) {
    console.log(data);
    $scope.data = data;
  });
}]);
<|endoftext|>


<commit_before>/*
 Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
 This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 Code distributed by Google as part of the polymer project is also
 subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */

(function(document) {
  'use strict';

  function finishLazyLoading(){
    console.log('demo finishLazyLoading()');
    // Grab a reference to our auto-binding template
    // and give it some initial binding values
    // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
    var app = document.querySelector('#app');

    //set default host;
    app.host = 'dev.voyent.cloud';

    // Sets app default base URL
    app.baseUrl = '/';
    if (window.location.port === '') {  // if production
      // Uncomment app.baseURL below and
      // set app.baseURL to '/your-pathname/' if running from folder in production
      if(window.location.pathname.indexOf('client.html')!== -1){
        app.baseUrl = '/demos/freight/client.html/';
      }
      else{
        app.baseUrl = '/demos/freight/';
      }
    }

    app.displayInstalledToast = function() {
      // Check to make sure caching is actually enabled—it won't be in the dev environment.
      if (!document.querySelector('platinum-sw-cache').disabled) {
        document.querySelector('#caching-complete').show();
      }
    };

    function setupNotificationListener() {
      voyent.xio.push.attach('http://'+app.host+'/pushio/demos/realms/' + voyent.io.auth.getLastKnownRealm(), voyent.io.auth.getLastKnownUsername());
      window.initializePushGroups(); //delegates to index.html for admins or client.html for regular users
    }

    document.addEventListener('notificationClicked',function(e) {
      var notification = e.detail.notification;
      //don't redirect link for admins since notifications
      //are only acted on by regular users
      if (app.$.demoView.isAdmin) {
        e.preventDefault();
        voyent.notify.hideNotification(e.detail.toast ? e.detail.toast : e.detail.native,0);
        return;
      }
      //set the current notification
      voyent.notify.selectNotification(notification);
      var route = notification.payload.route;
      if (route) {
        if (route === app.route) {
          var routeRef = app.$.demoView.querySelector(route + '-view');
          routeRef.loadNotification();
        }
        else {
          page.redirect('/'+route);
        }
      }
    });
    document.addEventListener('notificationChanged',function(e) {
      function waitForDemoView() {
        if (!window.app || !app.$ || !app.$.demoView) {
          setTimeout(waitForDemoView, 100);
          return;
        }
        //when the current notification is set we want to
        //load the notification if we are on the page
        if (!e.detail.notification || !e.detail.notification.payload) {
          return;
        }
        var route = e.detail.notification.payload.route;
        if (route && route === app.route) {
          var routeRef = app.$.demoView.querySelector(route+'-view');
          routeRef.loadNotification();
        }
      }
      waitForDemoView();
    });

    document.addEventListener('afterQueueUpdated',function(e) {
      function waitForDemoData() {
        if (!window.app || !window.app.$ || !window.app.$.demoView || !window.app.$.demoView.$$('demo-data')) {
          setTimeout(waitForDemoData, 100);
          return;
        }
        var demoData = app.$.demoView.$$('demo-data');
        if (demoData) {
          //sync the notification count
          demoData.set('notificationCount', voyent.notify.getNotificationCount());
          //sync the notification queue
          demoData.set('notifications', e.detail.queue);
          //convert the queue array to an user map object so we can group by users on the notification page
          demoData.set('notificationsByGroup', e.detail.queue.reduce(function (map, obj) {
            if (!map[obj.group]) {
              map[obj.group] = [];
            }
            map[obj.group].push(obj);
            return map;
          }, {}));
        }
        else {
          console.warn('could not locate demoData element to store user notification');
        }
      }
      waitForDemoData();
    });

    // Listen for template bound event to know when bindings
    // have resolved and content has been stamped to the page
    app.addEventListener('dom-change', function() {
      console.log('Initializing demo');
      if( voyent.io.auth.isLoggedIn()){
        setTimeout(function(){
          setupNotificationListener();
          //initialize lastNotificationTimestamp so user list displays
          var demoData = app.$.demoView.$$('#demoData');
          if( demoData ){
            demoData.lastNotificationTimestamp = new Date().getTime();
          }
        }, 5000);
      }
    });

    // Startup the Notification Push Listener after login
    window.addEventListener('onAfterLogin', function(){
      console.log('onAfterLogin callback: configuring notifications');
      setupNotificationListener();
    });

    // See https://github.com/Polymer/polymer/issues/1381
    window.addEventListener('WebComponentsReady', function() {
      // imports are loaded and elements have been registered
      console.log('WebComponentsReady!!!');
    });

    window.addEventListener('voyent-access-token-refreshed', function(e){
      console.log('demo app received event voyent-access-token-refreshed', e);
      voyent.xio.push.refreshConnection();
    });

    window.addEventListener('voyent-session-expired', function(e){
      console.log('demo app received event voyent-session-expired', e);
      voyent.xio.push.disconnect();
    });

    window.addEventListener('voyent-session-disconnected', function(e){
      console.log('demo app received event voyent-session-disconnected', e);
      voyent.xio.push.disconnect();
    });

    // Main area's paper-scroll-header-panel custom condensing transformation of
    // the appName in the middle-container and the bottom title in the bottom-container.
    // The appName is moved to top and shrunk on condensing. The bottom sub title
    // is shrunk to nothing on condensing.
    addEventListener('paper-header-transform', function(e) {
      var appName = document.querySelector('#mainToolbar .app-name');
      var middleContainer = document.querySelector('#mainToolbar .middle-container');
      var bottomContainer = document.querySelector('#mainToolbar .bottom-container');
      var detail = e.detail;
      var heightDiff = detail.height - detail.condensedHeight;
      var yRatio = Math.min(1, detail.y / heightDiff);
      var maxMiddleScale = 0.50;  // appName max size when condensed. The smaller the number the smaller the condensed size.
      var scaleMiddle = Math.max(maxMiddleScale, (heightDiff - detail.y) / (heightDiff / (1-maxMiddleScale))  + maxMiddleScale);
      var scaleBottom = 1 - yRatio;

      // Move/translate middleContainer
      Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer);

      // Scale bottomContainer and bottom sub title to nothing and back
      Polymer.Base.transform('scale(' + scaleBottom + ') translateZ(0)', bottomContainer);

      // Scale middleContainer appName
      Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName);
    });
  }

  var webComponentsSupported = (
  'registerElement' in document &&
  'import' in document.createElement('link') &&
  'content' in document.createElement('template'));

  if( !webComponentsSupported ){
    var script = document.createElement('script');
    script.async = true;
    script.src = 'bower_components/webcomponentsjs/webcomponents-lite.min.js';
    script.onload = finishLazyLoading;
    document.head.appendChild(script);
  }
  else{
    finishLazyLoading();
  }

})(document);
<commit_msg>Dynamically check protocol to ensure HTTPS works with our push attachment<commit_after>/*
 Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
 This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 Code distributed by Google as part of the polymer project is also
 subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */

(function(document) {
  'use strict';

  function finishLazyLoading(){
    console.log('demo finishLazyLoading()');
    // Grab a reference to our auto-binding template
    // and give it some initial binding values
    // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
    var app = document.querySelector('#app');

    //set default host;
    app.host = 'dev.voyent.cloud';

    // Sets app default base URL
    app.baseUrl = '/';
    if (window.location.port === '') {  // if production
      // Uncomment app.baseURL below and
      // set app.baseURL to '/your-pathname/' if running from folder in production
      if(window.location.pathname.indexOf('client.html')!== -1){
        app.baseUrl = '/demos/freight/client.html/';
      }
      else{
        app.baseUrl = '/demos/freight/';
      }
    }

    app.displayInstalledToast = function() {
      // Check to make sure caching is actually enabled—it won't be in the dev environment.
      if (!document.querySelector('platinum-sw-cache').disabled) {
        document.querySelector('#caching-complete').show();
      }
    };

    function setupNotificationListener() {
      voyent.xio.push.attach(('https:' == document.location.protocol ? 'https://' : 'http://')+app.host+'/pushio/demos/realms/' + voyent.io.auth.getLastKnownRealm(), voyent.io.auth.getLastKnownUsername());
      window.initializePushGroups(); //delegates to index.html for admins or client.html for regular users
    }

    document.addEventListener('notificationClicked',function(e) {
      var notification = e.detail.notification;
      //don't redirect link for admins since notifications
      //are only acted on by regular users
      if (app.$.demoView.isAdmin) {
        e.preventDefault();
        voyent.notify.hideNotification(e.detail.toast ? e.detail.toast : e.detail.native,0);
        return;
      }
      //set the current notification
      voyent.notify.selectNotification(notification);
      var route = notification.payload.route;
      if (route) {
        if (route === app.route) {
          var routeRef = app.$.demoView.querySelector(route + '-view');
          routeRef.loadNotification();
        }
        else {
          page.redirect('/'+route);
        }
      }
    });
    document.addEventListener('notificationChanged',function(e) {
      function waitForDemoView() {
        if (!window.app || !app.$ || !app.$.demoView) {
          setTimeout(waitForDemoView, 100);
          return;
        }
        //when the current notification is set we want to
        //load the notification if we are on the page
        if (!e.detail.notification || !e.detail.notification.payload) {
          return;
        }
        var route = e.detail.notification.payload.route;
        if (route && route === app.route) {
          var routeRef = app.$.demoView.querySelector(route+'-view');
          routeRef.loadNotification();
        }
      }
      waitForDemoView();
    });

    document.addEventListener('afterQueueUpdated',function(e) {
      function waitForDemoData() {
        if (!window.app || !window.app.$ || !window.app.$.demoView || !window.app.$.demoView.$$('demo-data')) {
          setTimeout(waitForDemoData, 100);
          return;
        }
        var demoData = app.$.demoView.$$('demo-data');
        if (demoData) {
          //sync the notification count
          demoData.set('notificationCount', voyent.notify.getNotificationCount());
          //sync the notification queue
          demoData.set('notifications', e.detail.queue);
          //convert the queue array to an user map object so we can group by users on the notification page
          demoData.set('notificationsByGroup', e.detail.queue.reduce(function (map, obj) {
            if (!map[obj.group]) {
              map[obj.group] = [];
            }
            map[obj.group].push(obj);
            return map;
          }, {}));
        }
        else {
          console.warn('could not locate demoData element to store user notification');
        }
      }
      waitForDemoData();
    });

    // Listen for template bound event to know when bindings
    // have resolved and content has been stamped to the page
    app.addEventListener('dom-change', function() {
      console.log('Initializing demo');
      if( voyent.io.auth.isLoggedIn()){
        setTimeout(function(){
          setupNotificationListener();
          //initialize lastNotificationTimestamp so user list displays
          var demoData = app.$.demoView.$$('#demoData');
          if( demoData ){
            demoData.lastNotificationTimestamp = new Date().getTime();
          }
        }, 5000);
      }
    });

    // Startup the Notification Push Listener after login
    window.addEventListener('onAfterLogin', function(){
      console.log('onAfterLogin callback: configuring notifications');
      setupNotificationListener();
    });

    // See https://github.com/Polymer/polymer/issues/1381
    window.addEventListener('WebComponentsReady', function() {
      // imports are loaded and elements have been registered
      console.log('WebComponentsReady!!!');
    });

    window.addEventListener('voyent-access-token-refreshed', function(e){
      console.log('demo app received event voyent-access-token-refreshed', e);
      voyent.xio.push.refreshConnection();
    });

    window.addEventListener('voyent-session-expired', function(e){
      console.log('demo app received event voyent-session-expired', e);
      voyent.xio.push.disconnect();
    });

    window.addEventListener('voyent-session-disconnected', function(e){
      console.log('demo app received event voyent-session-disconnected', e);
      voyent.xio.push.disconnect();
    });

    // Main area's paper-scroll-header-panel custom condensing transformation of
    // the appName in the middle-container and the bottom title in the bottom-container.
    // The appName is moved to top and shrunk on condensing. The bottom sub title
    // is shrunk to nothing on condensing.
    addEventListener('paper-header-transform', function(e) {
      var appName = document.querySelector('#mainToolbar .app-name');
      var middleContainer = document.querySelector('#mainToolbar .middle-container');
      var bottomContainer = document.querySelector('#mainToolbar .bottom-container');
      var detail = e.detail;
      var heightDiff = detail.height - detail.condensedHeight;
      var yRatio = Math.min(1, detail.y / heightDiff);
      var maxMiddleScale = 0.50;  // appName max size when condensed. The smaller the number the smaller the condensed size.
      var scaleMiddle = Math.max(maxMiddleScale, (heightDiff - detail.y) / (heightDiff / (1-maxMiddleScale))  + maxMiddleScale);
      var scaleBottom = 1 - yRatio;

      // Move/translate middleContainer
      Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer);

      // Scale bottomContainer and bottom sub title to nothing and back
      Polymer.Base.transform('scale(' + scaleBottom + ') translateZ(0)', bottomContainer);

      // Scale middleContainer appName
      Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName);
    });
  }

  var webComponentsSupported = (
  'registerElement' in document &&
  'import' in document.createElement('link') &&
  'content' in document.createElement('template'));

  if( !webComponentsSupported ){
    var script = document.createElement('script');
    script.async = true;
    script.src = 'bower_components/webcomponentsjs/webcomponents-lite.min.js';
    script.onload = finishLazyLoading;
    document.head.appendChild(script);
  }
  else{
    finishLazyLoading();
  }

})(document);
<|endoftext|>


<commit_before>seven = angular.module('seven', ['ui.router', 'firebase']);

seven.config(['$stateProvider', '$locationProvider', function($stateProvider, $locationProvider) {
    $locationProvider
            .html5Mode({
                enabled: true,
                requireBase: false
        });

    $stateProvider
            .state('home', {
                url: '/',
                controller: 'Home.controller',
                templateUrl: '/templates/home.html'
        });
}]);

seven.controller("Home.controller", function($scope, $timeout, $firebaseArray) {
    var ref = new Firebase("https://se7en.firebaseio.com/");
    $scope.tasks = $firebaseArray(ref);

//  Synchronize collections as arrays
    $scope.addTask = function() {
        $scope.tasks.$add({
          text: $scope.task,
          timeCreated: (new Date()).getTime()
        }).then(function(ref) {
            $scope.task = "";
        });
    }

    $scope.hideTask = function() {
        $scope.show = true;
        $timeout(function(){
            $scope.show = false;
        }, 3000);
        //$timeout(ng-hide, 3000);
    }
});

//authentication
//  app.controller("ProfileCtrl", function($scope, $firebaseAuth) {
//    var ref = new Firebase("https://se7en.firebaseio.com");
//
//    var auth = $firebaseAuth(ref);
//
//    auth.$authWithOAuthPopup("facebook").then(function(authData) {
//        console.log("Logged in as:", authData.uid);
//    }).catch(function(error) {
//        console.log("Authentication failed:", error);
//    });
//  });

//three-way data binding (notice the $bindTo method)
//  app.controller("SampleCtrl", function($scope, $firebaseObject) {
//      var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/data");
//download the data into a local object
//      var syncObject = $firebaseObject(ref);
//synchronize the object with a three-way data binding
//click on `index.html` above to see it used in the DOM!
//  syncObject.$bindTo($scope, "data");
//});<commit_msg>save js<commit_after>seven = angular.module('seven', ['ui.router', 'firebase']);

seven.config(['$stateProvider', '$locationProvider', function($stateProvider, $locationProvider) {
    $locationProvider
            .html5Mode({
                enabled: true,
                requireBase: false
        });

    $stateProvider
            .state('home', {
                url: '/',
                controller: 'Home.controller',
                templateUrl: '/templates/home.html'
        });
}]);

seven.controller("Home.controller", function($scope, $timeout, $firebaseArray) {
    var ref = new Firebase("https://se7en.firebaseio.com/");
    $scope.tasks = $firebaseArray(ref);

//  Synchronize collections as arrays
    $scope.addTask = function() {
        $scope.tasks.$add({
          text: $scope.task,
          timeCreated: (new Date()).getTime()
        }).then(function(ref) {
            $scope.task = "";
        });
    }

    $scope.hideTask = function() {

    }
});

//authentication
//  app.controller("ProfileCtrl", function($scope, $firebaseAuth) {
//    var ref = new Firebase("https://se7en.firebaseio.com");
//
//    var auth = $firebaseAuth(ref);
//
//    auth.$authWithOAuthPopup("facebook").then(function(authData) {
//        console.log("Logged in as:", authData.uid);
//    }).catch(function(error) {
//        console.log("Authentication failed:", error);
//    });
//  });

//three-way data binding (notice the $bindTo method)
//  app.controller("SampleCtrl", function($scope, $firebaseObject) {
//      var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/data");
//download the data into a local object
//      var syncObject = $firebaseObject(ref);
//synchronize the object with a three-way data binding
//click on `index.html` above to see it used in the DOM!
//  syncObject.$bindTo($scope, "data");
//});<|endoftext|>


<commit_before>const Router = require('express').Router
const Slapp = require('slapp')
const BeepBoopContext = require('slapp-context-beepboop')
const BeepBoopConvo = require('slapp-convo-beepboop')

module.exports = (app) => {
  var router = new Router()

  router.use((req, res, next) => {
    console.log(req.body)

    next()
  })

  app.slapp = Slapp({
    verify_token: app.config.slack.verifyToken,
    context: BeepBoopContext(),
    convo_store: BeepBoopConvo()
  })

  require('./commands')(app)

  require('./messages')(app)

  return app.slapp.attachToExpress(router)
}
<commit_msg>adds logger after context fn<commit_after>const Router = require('express').Router
const Slapp = require('slapp')
const BeepBoopContext = require('slapp-context-beepboop')
const BeepBoopConvo = require('slapp-convo-beepboop')

module.exports = (app) => {
  var router = new Router()

  var logger = (req, res, next) => {
    console.log('slapp: ', req.slapp)

    next()
  }

  app.slapp = Slapp({
    verify_token: app.config.slack.verifyToken,
    context: [BeepBoopContext(), logger],
    convo_store: BeepBoopConvo()
  })

  require('./commands')(app)

  require('./messages')(app)

  return app.slapp.attachToExpress(router)
}
<|endoftext|>


<commit_before>var
  nconf = require('./config').nconf
  , config = require('./config').config
  , redis = require("redis")
  , _ = require('underscore')._
  , neuron = require('neuron')
  , zlib = require('zlib')
  , winston = require('./logging').winston
  , bundleManager = require('./bundleManager')
  , cronJob = require("cron").CronJob
  //, crypto = require('crypto')
  //, sha = crypto.createHash('sha1')
;

var bundles = {},
	cronjobs = [];

require('date-utils');

// Connect to redis
var client = redis.createClient(config.redis.port, config.redis.address);
if (nconf.get(config.redis.auth)) {
	client.auth(config.redis.auth, function (err) {
		if (err) {
			// handle err;
		}
	});
}

//
// ## Recursive function to remove unwanted elements from API response
//
var filter = function( source, map) {
	if (_.isArray(source)) {
		_.each(source, function(item, index) { filter( item, map[0]); });
	} else {
		if (_.isString(source) || map === true || _.isUndefined(map)) return 0;
		_.each(source, function(obj, key, source) {
			if (_.isUndefined(map[key])) {
				delete source[key];
			} else {
				filter( obj, map[key]);
			}
		});
	};
}

//
// ## Listener for bundle updater
//
var bundler = new bundleManager();
bundler.on('bundlesUpdated', function(newBundles) {

	winston.info('event bundlesUpdated');
	bundles = newBundles;

	// ### Stop all the existing scheduled jobs
	_.each(cronjobs, function (job, idx) {
    	job.stop();
    	delete job;
	});

	cronjobs = [];

	// ### Schedule jobs defined in bundles
	_.each(bundles, function (bundle, bid) {
		_.each(bundle, function (api, key) {
			if (api.schedule) {
				var job = new cronJob(api.schedule, function(){
		    		winston.info('cronjob '+key+' called');
		    		exports.refresh(api, key, bid, bundle);
		    	}, null, true);
		    	cronjobs.push(job);
		    }
		});
	});

});

bundler.refreshBundles();

//
// ## Perform scheduled refresh
//
exports.refresh = function(api, key, bid, bundle) {

	winston.info('exports.refresh: ' + api);
	// We're forcing a refresh of the content so run the api.code
	api.resource( api.params, api.credentials, function( err, res ) {
		if ( err ) {

			// We got an error so set our output object to be the error and expire immediately
			api.expires = ( new Date() );
  			var tout = {
  				expires: api.expires,
  				result: err,
  				iid: bid+key,
  				cname: key,
  				scheduled: true
  			};

		} else {

  			winston.event('Get data for ' + bid + ' from ' + key + ', ' + res.size);

  			// Filter the response
  			if (_.has(api.filter)) {
	  			filter ( res, api.filter );
  			}

			// Perform cleanup function on API response
  			if (_.has(api, 'cleanup')) {
	  			res = api.cleanup(res);
  			}

			// Build the stored response
  			api.expires = ( new Date() ).addSeconds( api.cacheduration );
  			bundle[key] = api;

  			var tout = {
  				expires: api.expires,
  				result: res,
  				iid: api.iid,
  				cname: key,
  				scheduled: true
  			};

	   		// Save response to Redis
	   		client.set(bid+key, JSON.stringify(tout));

	   		// Update the bundle
	   		client.del('bid'+bid);
		}
  	});

}

//
// ## Retrieve the requested bundle
//
exports.fulfill = function ( myRes, ip, bid, bundle, callback, gzip, override ) {

	winston.info('exports.fulfill: ' + bid);

	// If the user requested a bundle that is not defined
	if (typeof bundle === 'undefined') {
		myRes.writeHead(404);
		myRes.end();
		return false;
	}

	// Count the number of queries in this bundle so we know when we are ready to respond
	var queriesInThisBundle = _.size(bundle),
		thisResponse = {};

	// cleanup is not an API request
	if(_.has(bundle, 'cleanup')) {
		queriesInThisBundle--;
	}

	// If override was not passed
	if( _.isUndefined( override )) {

		// Retrieve bundle response from Redis
		client.get('bid'+bid, function ( err, doc ) {

			if ( err || doc === null ) {
				// There was an error so force refresh on bundle
				exports.fulfill( myRes, ip, bid, bundle, callback, gzip, true );

			} else {

				jDoc = JSON.parse( doc );

				// If there is a valid expiration date for the bundle
				jDoc.expires = new Date(jDoc.expires);
				if ( 'expires' in jDoc && _.isDate(jDoc.expires) ) {
					jDoc.secleft = jDoc.expires.getSecondsBetween( new Date() ) * -1;
				} else {
					// This should never happen
					jDoc.secleft = 0;
				}

				if (Number(jDoc.secleft) < 0 ) {

					// The bundle has expired. Force a refresh
					exports.fulfill( myRes, ip, bid, bundle, callback, gzip, true );

				} else {

					//Respond with the cached data
					jDoc.fromcache = true;
					var responseType = callback ? 'application/javascript' : 'application/json';
					var responseHeaders = {'Content-Type': responseType, 'max-age': jDoc.secleft, 'cache-control': 'public, max-age='+jDoc.secleft+', no-transform', "Expires": jDoc.expires };

					doc = JSON.stringify(jDoc);

					// If a callback name was passed, use it. Otherwise, just output the object
					var tbuf = new Buffer(  ( !callback ) ? doc : callback + '('  + doc +  ');');

					if (gzip) {

						zlib.gzip(tbuf.toString(), function(err, zbuf) {
						  if (!err) {
						    winston.event('Send gzipped response for ' + bid +', ' + zbuf.toString().length + ', ' + ip);
						    myRes.writeHead(200, {'Content-Type': responseType, 'max-age': jDoc.secleft, 'cache-control': 'public, max-age='+jDoc.secleft+', no-transform', "Expires": jDoc.expires, 'content-encoding': 'gzip' });
						    myRes.end(zbuf);
						  }
						});
					} else {
						myRes.writeHead(200, responseHeaders);
						winston.event('Send response for ' + bid +', ' + doc.length + ', ' + ip);
						myRes.end(tbuf);
					}

				}
			}
		});

	} else {

		// ### Override was passed so we are forcing a refresh
		var manager = new neuron.JobManager();

		manager.on('empty', function (job) {

			winston.info('manager:empty');

			if (job.name === 'finishRequest' && queriesInThisBundle === 0) {
				var done = true;

				_.each(manager.job, function(job, key) {
					if (_.size(job.waiting)  !== 0 || _.size(job.running) !== 0 || job.queue.length !== 0) {
        				done = false;
        			}
        		});

        		if (done) manager.enqueue('composeResponse', bid);
			}
		});

		manager.addJob('fulfillPart', {
			work: function(api, bid, key, override, cachedPart) {

				winston.info('manager:fulfillPart: ' + bid + '.' + key);

				var self = this;

				if ( _.isUndefined( override ) ) {

					// Load the cached api response from Redis
			  		client.get(bid+key, function (err, doc) {
			  			if (err || doc === null){
			  				self.finished = true;
			  				manager.enqueue('fulfillPart', api, bid, key, true );
			  			} else {

				  			doc = JSON.parse( doc );
				  			doc.expires = new Date(doc.expires);
				  			if ( ('expires' in doc) && _.isDate(doc.expires) ) {
				  				var secleft = doc.expires.getSecondsBetween( new Date() ) * -1;
				  			}
				  			if (secleft < 0) {
				  				self.finished = true;
				  				manager.enqueue('fulfillPart', api, bid, key, true, doc );
				  			} else {
				  				doc.fromcache = true;
				  				manager.enqueue('finishRequest', doc );
				  				self.finished = true;
				  			}
				  		}
				  	});

				} else {

					if (_.has( api, 'auth')) {

						// If the API request object has an auth scheme defined
						api.auth.type.authorize (api, bid, key, function( result ) {
							if (result === true) {
								manager.enqueue('startRequest', api, key, cachedPart, bid);
							} else {
								manager.enqueue('finishRequest', result );
							}
							self.finished = true;
						});
					} else {
						// Authentication is not needed
						self.finished = true;
						manager.enqueue('startRequest', api, key, cachedPart, bid);
					}

				}

			}
		});

		manager.addJob('startRequest', {
			work: function( api, key, cachedPart, bid ) {

				winston.info('manager:startRequest: ' + key);

				var self = this;

				if (_.has( api, 'timeout') && _.isObject(cachedPart)) {
					self.timeout = setTimeout(function(self) {
						if(_.isObject(cachedPart)) {
							cachedPart.timeout = true;
							cachedPart.fromcache = true;
						} else {
							cachedPart= {
								"cname": key,
								"timeout" : true,
								"fromcache" : false
							};
						}
						manager.enqueue('finishRequest', cachedPart );
						self.finished = true;
					}, api.timeout, self)
				}

				api.resource( api.params, api.credentials, function( err, res ) {
		  			clearTimeout(self.timeout)
		  			delete self.timeout;

		  			if ( err ) {

		  				api.expires = ( new Date() );
			  			tout = _.isUndefined(cachedPart) ? {} : cachedPart;
			  			tout.cname = key;
			  			tout.expires = api.expires;
			  			tout.result = res;
			  			tout.fromcache = true;
			  			tout.err = err;

		  			} else {

			  			winston.event('Get data for ' + bid + ' from ' + key + ', ' + res.size);

			  			// Filter the response
			  			if (_.has(api, 'filter')) {
				  			filter ( res, api.filter );
			  			}

			  			// Perform cleanup function on API response
			  			if (_.has(api, 'cleanup')) {
				  			res = api.cleanup(res);
			  			}

			  			// Build the stored response
			  			api.expires = ( new Date() ).addSeconds( api.cacheduration );
			  			bundle[key] = api;
			  			//client.set('bundle'+bid, JSON.stringify(bundle));
			  			var tout = {
			  				expires: api.expires,
			  				result: res,
			  				iid: api.iid,
			  				cname: key
			  			};

				   		// Save response to Redis
				   		client.set(bid+key, JSON.stringify(tout));
				   	}
					manager.enqueue('finishRequest', tout );
	  				self.finished = true;
			  	});
			}
		})

		manager.addJob('finishRequest', {
			work: function(apiResponse) {

				winston.info('manager:finishRequest');

				queriesInThisBundle--;

				if (_.has(apiResponse, 'redirect')) thisResponse.redirect = apiResponse.redirect;
				thisResponse[apiResponse.cname] = apiResponse;

			  	this.finished = true;
			}
		});

		manager.addJob('composeResponse', {
			work: function() {

				winston.info('manager:composeResponse');

				// Update the expiration date on the bundle
				var tout = {
					expires: _.min( thisResponse, function( val ) { return val.expires } ).expires,
				};

				if (_.has( thisResponse, 'redirect')) tout.redirect = thisResponse.redirect;

				// Insert api responses into bundle
				_.each( thisResponse, function( val, idx ) {
					tout[val.cname] = val;
				});

				// Perform cleanup function on bundle
			  	if (_.has(bundle, 'cleanup')) {
				  	tout = bundle.cleanup(tout);
				}

				// Save cached bundle in Redis
				client.set('bid'+bid, JSON.stringify(tout));

				// Determine the seconds left before expiry
				if ( 'expires' in tout && _.isDate(tout.expires) ) {
					tout.secleft = tout.expires.getSecondsBetween( new Date() ) * -1;
				} else {
					tout.secleft = 3600;
				}

				manager.enqueue('sendResponse', tout);
				this.finished = true;

			}
		});

		manager.addJob('sendResponse', {
			work: function(doc) {

				winston.info('manager:sendResponse');

				if (_.has(doc, 'redirect')) {
					myRes.statusCode = 302;
					myRes.setHeader("Location", doc.redirect);
					myRes.end();
					this.finished = true;
				} else {

					// Send the results
					var responseType = callback ? 'application/javascript' : 'application/json';
					var responseHeaders = {'Content-Type': responseType, 'max-age': doc.secleft, 'cache-control': 'public, max-age='+doc.secleft+', no-transform', "Expires": doc.expires };

					var responseType = callback ? 'application/javascript' : 'application/json';
					var responseHeaders = {'Content-Type': responseType, 'max-age': doc.secleft, 'cache-control': 'public, max-age='+doc.secleft+', no-transform', "Expires": doc.expires };

					// If a callback name was passed, use it. Otherwise, just output the object
					var tbuf = new Buffer(  ( !callback ) ? JSON.stringify( doc ) : callback + '('  + JSON.stringify( doc ) +  ');');

					if (gzip) {

						zlib.gzip(tbuf.toString(), function(err, zbuf) {
						  if (!err) {
						    myRes.writeHead(200, {'Content-Type': responseType, 'max-age': doc.secleft, 'cache-control': 'public, max-age='+doc.secleft+', no-transform', "Expires": doc.expires, 'content-encoding': 'gzip' });
						    myRes.end(zbuf);
						    this.finished = true;
						  }
						});
					} else {
						myRes.writeHead(200, responseHeaders);
						myRes.end(tbuf);
						this.finished = true;
					}
				}
			}
		});

		_.each( bundle, function( api, key ) {
			if (key !== 'cleanup') {
				if (_.isUndefined(api, 'credentials')) {
					api.credentials = {};
				}
				manager.enqueue('fulfillPart', api, bid, key);
			}
		});

	}
}<commit_msg>Cath authparams and use them to extend params<commit_after>var
  nconf = require('./config').nconf
  , config = require('./config').config
  , redis = require("redis")
  , _ = require('underscore')._
  , neuron = require('neuron')
  , zlib = require('zlib')
  , winston = require('./logging').winston
  , bundleManager = require('./bundleManager')
  , cronJob = require("cron").CronJob
  //, crypto = require('crypto')
  //, sha = crypto.createHash('sha1')
;

var bundles = {},
	cronjobs = [];

require('date-utils');

// Connect to redis
var client = redis.createClient(config.redis.port, config.redis.address);
if (nconf.get(config.redis.auth)) {
	client.auth(config.redis.auth, function (err) {
		if (err) {
			// handle err;
		}
	});
}

//
// ## Recursive function to remove unwanted elements from API response
//
var filter = function( source, map) {
	if (_.isArray(source)) {
		_.each(source, function(item, index) { filter( item, map[0]); });
	} else {
		if (_.isString(source) || map === true || _.isUndefined(map)) return 0;
		_.each(source, function(obj, key, source) {
			if (_.isUndefined(map[key])) {
				delete source[key];
			} else {
				filter( obj, map[key]);
			}
		});
	};
}

//
// ## Listener for bundle updater
//
var bundler = new bundleManager();
bundler.on('bundlesUpdated', function(newBundles) {

	winston.info('event bundlesUpdated');
	bundles = newBundles;

	// ### Stop all the existing scheduled jobs
	_.each(cronjobs, function (job, idx) {
    	job.stop();
    	delete job;
	});

	cronjobs = [];

	// ### Schedule jobs defined in bundles
	_.each(bundles, function (bundle, bid) {
		_.each(bundle, function (api, key) {
			if (api.schedule) {
				var job = new cronJob(api.schedule, function(){
		    		winston.info('cronjob '+key+' called');
		    		exports.refresh(api, key, bid, bundle);
		    	}, null, true);
		    	cronjobs.push(job);
		    }
		});
	});

});

bundler.refreshBundles();

//
// ## Perform scheduled refresh
//
exports.refresh = function(api, key, bid, bundle) {

	winston.info('exports.refresh: ' + api);
	// We're forcing a refresh of the content so run the api.code
	api.resource( api.params, api.credentials, function( err, res ) {
		if ( err ) {

			// We got an error so set our output object to be the error and expire immediately
			api.expires = ( new Date() );
  			var tout = {
  				expires: api.expires,
  				result: err,
  				iid: bid+key,
  				cname: key,
  				scheduled: true
  			};

		} else {

  			winston.event('Get data for ' + bid + ' from ' + key + ', ' + res.size);

  			// Filter the response
  			if (_.has(api.filter)) {
	  			filter ( res, api.filter );
  			}

			// Perform cleanup function on API response
  			if (_.has(api, 'cleanup')) {
	  			res = api.cleanup(res);
  			}

			// Build the stored response
  			api.expires = ( new Date() ).addSeconds( api.cacheduration );
  			bundle[key] = api;

  			var tout = {
  				expires: api.expires,
  				result: res,
  				iid: api.iid,
  				cname: key,
  				scheduled: true
  			};

	   		// Save response to Redis
	   		client.set(bid+key, JSON.stringify(tout));

	   		// Update the bundle
	   		client.del('bid'+bid);
		}
  	});

}

//
// ## Retrieve the requested bundle
//
exports.fulfill = function ( myRes, ip, bid, bundle, callback, gzip, override ) {

	winston.info('exports.fulfill: ' + bid);

	// If the user requested a bundle that is not defined
	if (typeof bundle === 'undefined') {
		myRes.writeHead(404);
		myRes.end();
		return false;
	}

	// Count the number of queries in this bundle so we know when we are ready to respond
	var queriesInThisBundle = _.size(bundle),
		thisResponse = {};

	// cleanup is not an API request
	if(_.has(bundle, 'cleanup')) {
		queriesInThisBundle--;
	}

	// If override was not passed
	if( _.isUndefined( override )) {

		// Retrieve bundle response from Redis
		client.get('bid'+bid, function ( err, doc ) {

			if ( err || doc === null ) {
				// There was an error so force refresh on bundle
				exports.fulfill( myRes, ip, bid, bundle, callback, gzip, true );

			} else {

				jDoc = JSON.parse( doc );

				// If there is a valid expiration date for the bundle
				jDoc.expires = new Date(jDoc.expires);
				if ( 'expires' in jDoc && _.isDate(jDoc.expires) ) {
					jDoc.secleft = jDoc.expires.getSecondsBetween( new Date() ) * -1;
				} else {
					// This should never happen
					jDoc.secleft = 0;
				}

				if (Number(jDoc.secleft) < 0 ) {

					// The bundle has expired. Force a refresh
					exports.fulfill( myRes, ip, bid, bundle, callback, gzip, true );

				} else {

					//Respond with the cached data
					jDoc.fromcache = true;
					var responseType = callback ? 'application/javascript' : 'application/json';
					var responseHeaders = {'Content-Type': responseType, 'max-age': jDoc.secleft, 'cache-control': 'public, max-age='+jDoc.secleft+', no-transform', "Expires": jDoc.expires };

					doc = JSON.stringify(jDoc);

					// If a callback name was passed, use it. Otherwise, just output the object
					var tbuf = new Buffer(  ( !callback ) ? doc : callback + '('  + doc +  ');');

					if (gzip) {

						zlib.gzip(tbuf.toString(), function(err, zbuf) {
						  if (!err) {
						    winston.event('Send gzipped response for ' + bid +', ' + zbuf.toString().length + ', ' + ip);
						    myRes.writeHead(200, {'Content-Type': responseType, 'max-age': jDoc.secleft, 'cache-control': 'public, max-age='+jDoc.secleft+', no-transform', "Expires": jDoc.expires, 'content-encoding': 'gzip' });
						    myRes.end(zbuf);
						  }
						});
					} else {
						myRes.writeHead(200, responseHeaders);
						winston.event('Send response for ' + bid +', ' + doc.length + ', ' + ip);
						myRes.end(tbuf);
					}

				}
			}
		});

	} else {

		// ### Override was passed so we are forcing a refresh
		var manager = new neuron.JobManager();

		manager.on('empty', function (job) {

			winston.info('manager:empty');

			if (job.name === 'finishRequest' && queriesInThisBundle === 0) {
				var done = true;

				_.each(manager.job, function(job, key) {
					if (_.size(job.waiting)  !== 0 || _.size(job.running) !== 0 || job.queue.length !== 0) {
        				done = false;
        			}
        		});

        		if (done) manager.enqueue('composeResponse', bid);
			}
		});

		manager.addJob('fulfillPart', {
			work: function(api, bid, key, override, cachedPart) {

				winston.info('manager:fulfillPart: ' + bid + '.' + key);

				var self = this;

				if ( _.isUndefined( override ) ) {

					// Load the cached api response from Redis
			  		client.get(bid+key, function (err, doc) {
			  			if (err || doc === null){
			  				self.finished = true;
			  				manager.enqueue('fulfillPart', api, bid, key, true );
			  			} else {

				  			doc = JSON.parse( doc );
				  			doc.expires = new Date(doc.expires);
				  			if ( ('expires' in doc) && _.isDate(doc.expires) ) {
				  				var secleft = doc.expires.getSecondsBetween( new Date() ) * -1;
				  			}
				  			if (secleft < 0) {
				  				self.finished = true;
				  				manager.enqueue('fulfillPart', api, bid, key, true, doc );
				  			} else {
				  				doc.fromcache = true;
				  				manager.enqueue('finishRequest', doc );
				  				self.finished = true;
				  			}
				  		}
				  	});

				} else {

					if (_.has( api, 'auth')) {

						// If the API request object has an auth scheme defined
						api.auth.type.authorize (api, bid, key, function( result, authParams ) {
							if (result === true) {
								api.params = _.extend(api.params, authParams);
								manager.enqueue('startRequest', api, key, cachedPart, bid);
							} else {
								manager.enqueue('finishRequest', result );
							}
							self.finished = true;
						});
					} else {
						// Authentication is not needed
						self.finished = true;
						manager.enqueue('startRequest', api, key, cachedPart, bid);
					}

				}

			}
		});

		manager.addJob('startRequest', {
			work: function( api, key, cachedPart, bid ) {

				winston.info('manager:startRequest: ' + key);

				var self = this;

				if (_.has( api, 'timeout') && _.isObject(cachedPart)) {
					self.timeout = setTimeout(function(self) {
						if(_.isObject(cachedPart)) {
							cachedPart.timeout = true;
							cachedPart.fromcache = true;
						} else {
							cachedPart= {
								"cname": key,
								"timeout" : true,
								"fromcache" : false
							};
						}
						manager.enqueue('finishRequest', cachedPart );
						self.finished = true;
					}, api.timeout, self)
				}

				api.resource( api.params, api.credentials, function( err, res ) {
		  			clearTimeout(self.timeout)
		  			delete self.timeout;

		  			if ( err ) {

		  				api.expires = ( new Date() );
			  			tout = _.isUndefined(cachedPart) ? {} : cachedPart;
			  			tout.cname = key;
			  			tout.expires = api.expires;
			  			tout.result = res;
			  			tout.fromcache = true;
			  			tout.err = err;

		  			} else {

			  			winston.event('Get data for ' + bid + ' from ' + key + ', ' + res.size);

			  			// Filter the response
			  			if (_.has(api, 'filter')) {
				  			filter ( res, api.filter );
			  			}

			  			// Perform cleanup function on API response
			  			if (_.has(api, 'cleanup')) {
				  			res = api.cleanup(res);
			  			}

			  			// Build the stored response
			  			api.expires = ( new Date() ).addSeconds( api.cacheduration );
			  			bundle[key] = api;
			  			//client.set('bundle'+bid, JSON.stringify(bundle));
			  			var tout = {
			  				expires: api.expires,
			  				result: res,
			  				iid: api.iid,
			  				cname: key
			  			};

				   		// Save response to Redis
				   		client.set(bid+key, JSON.stringify(tout));
				   	}
					manager.enqueue('finishRequest', tout );
	  				self.finished = true;
			  	});
			}
		})

		manager.addJob('finishRequest', {
			work: function(apiResponse) {

				winston.info('manager:finishRequest');

				queriesInThisBundle--;

				if (_.has(apiResponse, 'redirect')) thisResponse.redirect = apiResponse.redirect;
				thisResponse[apiResponse.cname] = apiResponse;

			  	this.finished = true;
			}
		});

		manager.addJob('composeResponse', {
			work: function() {

				winston.info('manager:composeResponse');

				// Update the expiration date on the bundle
				var tout = {
					expires: _.min( thisResponse, function( val ) { return val.expires } ).expires,
				};

				if (_.has( thisResponse, 'redirect')) tout.redirect = thisResponse.redirect;

				// Insert api responses into bundle
				_.each( thisResponse, function( val, idx ) {
					tout[val.cname] = val;
				});

				// Perform cleanup function on bundle
			  	if (_.has(bundle, 'cleanup')) {
				  	tout = bundle.cleanup(tout);
				}

				// Save cached bundle in Redis
				client.set('bid'+bid, JSON.stringify(tout));

				// Determine the seconds left before expiry
				if ( 'expires' in tout && _.isDate(tout.expires) ) {
					tout.secleft = tout.expires.getSecondsBetween( new Date() ) * -1;
				} else {
					tout.secleft = 3600;
				}

				manager.enqueue('sendResponse', tout);
				this.finished = true;

			}
		});

		manager.addJob('sendResponse', {
			work: function(doc) {

				winston.info('manager:sendResponse');

				if (_.has(doc, 'redirect')) {
					myRes.statusCode = 302;
					myRes.setHeader("Location", doc.redirect);
					myRes.end();
					this.finished = true;
				} else {

					// Send the results
					var responseType = callback ? 'application/javascript' : 'application/json';
					var responseHeaders = {'Content-Type': responseType, 'max-age': doc.secleft, 'cache-control': 'public, max-age='+doc.secleft+', no-transform', "Expires": doc.expires };

					var responseType = callback ? 'application/javascript' : 'application/json';
					var responseHeaders = {'Content-Type': responseType, 'max-age': doc.secleft, 'cache-control': 'public, max-age='+doc.secleft+', no-transform', "Expires": doc.expires };

					// If a callback name was passed, use it. Otherwise, just output the object
					var tbuf = new Buffer(  ( !callback ) ? JSON.stringify( doc ) : callback + '('  + JSON.stringify( doc ) +  ');');

					if (gzip) {

						zlib.gzip(tbuf.toString(), function(err, zbuf) {
						  if (!err) {
						    myRes.writeHead(200, {'Content-Type': responseType, 'max-age': doc.secleft, 'cache-control': 'public, max-age='+doc.secleft+', no-transform', "Expires": doc.expires, 'content-encoding': 'gzip' });
						    myRes.end(zbuf);
						    this.finished = true;
						  }
						});
					} else {
						myRes.writeHead(200, responseHeaders);
						myRes.end(tbuf);
						this.finished = true;
					}
				}
			}
		});

		_.each( bundle, function( api, key ) {
			if (key !== 'cleanup') {
				if (_.isUndefined(api, 'credentials')) {
					api.credentials = {};
				}
				manager.enqueue('fulfillPart', api, bid, key);
			}
		});

	}
}<|endoftext|>


<commit_before>var GitHubApi = require("github")
  , config = require("config")

var apiOptions = {
  protocol: config.github.api.protocol,
  host: config.github.api.host,
  port: config.github.api.port,
  version: config.github.api.version,
  pathPrefix: config.github.api.pathPrefix,
  timeout: 5000
}

/**
 * Create an authenticated instance of the GitHub API accessor.
 *
 * @param {String} authToken OAuth access token
 * - If a user-specific token is not supplied, uses the master OAuth token
 */
module.exports.getInstance = function (authToken) {
  var instance = new GitHubApi(apiOptions)
  instance.authenticate({
    type: "oauth",
    token: authToken ? authToken : config.github.token
  })
  return instance
}
<commit_msg>Cache default github instance<commit_after>var GitHubApi = require("github")
  , config = require("config")

var apiOptions = {
  protocol: config.github.api.protocol,
  host: config.github.api.host,
  port: config.github.api.port,
  version: config.github.api.version,
  pathPrefix: config.github.api.pathPrefix,
  timeout: 5000
}

var defaultInstance = new GitHubApi(apiOptions)

defaultInstance.authenticate({
  type: "oauth",
  token: config.github.token
})

/**
 * Create an authenticated instance of the GitHub API accessor.
 *
 * @param {String} authToken OAuth access token
 * - If a user-specific token is not supplied, uses the master OAuth token
 */
module.exports.getInstance = function (authToken) {
  if (!authToken) return defaultInstance

  var instance = new GitHubApi(apiOptions)

  instance.authenticate({
    type: "oauth",
    token: authToken
  })

  return instance
}
<|endoftext|>


<commit_before>function isArray(obj) {
  return !!obj && obj.constructor === Array
}

export const isEmptyObject = (object) => Object.entries(object).length === 0

const checkLanguage = (item, language) =>
  language.size === 0 ||
  language.includes(item.language) ||
  (item.translations &&
    item.translations.some((translation) =>
      language.includes(translation.language)
    ))

export const getFilteredItems = (items, filters) =>
  items.filter((item) => {
    const [...filterNames] = filters.keys()
    return filterNames.every((filterName) => {
      if (filterName === 'language') {
        return checkLanguage(item, filters.get('language'))
      } else if (
        filters.get(filterName).size === 0 ||
        filters.get(filterName) === ''
      ) {
        return true
      } else if (
        typeof item[filterName] === 'string' ||
        typeof item[filterName] === 'number'
      ) {
        return (
          item[filterName] === filters.get(filterName) ||
          filters.get(filterName).includes(item[filterName])
        )
      } else if (isArray(item[filterName]) && item[filterName].length) {
        return item[filterName].some((keyItems) =>
          filters.get(filterName).includes(keyItems)
        )
      }
      return false
    })
  })

/* inside pictograms, check which keywords meets an specific searchText */
export const keywordSelector = (searchText, keywords) => {
  const searchTextArray = searchText.split(' ')
  if (!searchTextArray.length) return keywords[0]
  // if same keyword exists, return it
  const keyword = keywords.find(
    (keywordsItem) =>
      keywordsItem.keyword.toLowerCase() === searchText.toLowerCase()
  )
  if (keyword) return keyword
  // otherwise, return first partial match or fist keyword if no matches
  return (
    keywords.find((keywordsItem) => {
      const keywordArray = keywordsItem.keyword
        .split(' ')
        .map((keyword) => keyword.toLowerCase())
      return searchTextArray.some((word) =>
        keywordArray.includes(word.toLowerCase())
      )
    }) || keywords[0]
  )
}

/* for hair and skin options, get object key for a given value */
export const getKeyByValue = (object, value) =>
  Object.keys(object).find((key) => object[key] === value)
<commit_msg>fix error when picto keywords is empty<commit_after>function isArray(obj) {
  return !!obj && obj.constructor === Array
}

export const isEmptyObject = (object) => Object.entries(object).length === 0

const checkLanguage = (item, language) =>
  language.size === 0 ||
  language.includes(item.language) ||
  (item.translations &&
    item.translations.some((translation) =>
      language.includes(translation.language)
    ))

export const getFilteredItems = (items, filters) =>
  items.filter((item) => {
    const [...filterNames] = filters.keys()
    return filterNames.every((filterName) => {
      if (filterName === 'language') {
        return checkLanguage(item, filters.get('language'))
      } else if (
        filters.get(filterName).size === 0 ||
        filters.get(filterName) === ''
      ) {
        return true
      } else if (
        typeof item[filterName] === 'string' ||
        typeof item[filterName] === 'number'
      ) {
        return (
          item[filterName] === filters.get(filterName) ||
          filters.get(filterName).includes(item[filterName])
        )
      } else if (isArray(item[filterName]) && item[filterName].length) {
        return item[filterName].some((keyItems) =>
          filters.get(filterName).includes(keyItems)
        )
      }
      return false
    })
  })

/* inside pictograms, check which keywords meets an specific searchText */
export const keywordSelector = (searchText, keywords) => {
  const searchTextArray = searchText.split(' ')
  if (!searchTextArray.length) return keywords[0] || ''
  // if same keyword exists, return it
  const keyword = keywords.find(
    (keywordsItem) =>
      keywordsItem.keyword.toLowerCase() === searchText.toLowerCase()
  )
  if (keyword) return keyword || ''
  // otherwise, return first partial match or fist keyword if no matches
  return (
    keywords.find((keywordsItem) => {
      const keywordArray = keywordsItem.keyword
        .split(' ')
        .map((keyword) => keyword.toLowerCase())
      return searchTextArray.some((word) =>
        keywordArray.includes(word.toLowerCase())
      )
    }) ||
    keywords[0] ||
    ''
  )
}

/* for hair and skin options, get object key for a given value */
export const getKeyByValue = (object, value) =>
  Object.keys(object).find((key) => object[key] === value)
<|endoftext|>


<commit_before>!function(n){function s(c){if(this!=n)return s.call(n,c);var module={},e=module.exports=module.export=function(a){module.exports=a},d=eval(c);return module.exports!=e?module.exports:d||!0}!function(){var a={},b=function(b,c){function f(){var c=e.j=new XMLHttpRequest;c.onreadystatechange=function(){if(c.readyState==XMLHttpRequest.DONE)if(c.status>=200&&c.status<300)for(var d=0;d<e.t.length;d++){e.u=c.responseText;var g=c.getResponseHeader("Content-Type");g.match(/javascript/)&&(e.p=s(e.u)),e.t[d](c.status,e.p||e.u,g)}else if(e.s<5)e.s++,setTimeout(f,100*e.s);else{for(var d=0;d<e.t.length;d++)e.t[d](c.status);delete a[b]}},c.open("GET",b,!0),c.send()}var d=a[b];if(d&&d.u)c(d.j.status,d.p,d.j.getResponseHeader("Content-Type"));else if(d&&!d.u)d.t.push(c);else{var e=a[b]={t:[c],s:1};f()}};n.requireOnce=n.require_once=function(a,c,d){if(!c)throw"Success callback not defined";d=d||function(){};var e=[],f=0,g=function(){if(f==a.length){var b=!1;e.forEach(function(a){a||!1!==a||(b=!0)}),b?d.apply(n,e):c.apply(n,e)}};a.forEach(function(a,c){var d;"undefined"!=typeof require&&"undefined"==typeof XMLHttpRequest?(d=a.server,e[c]=!!d&&require(d),f++,g()):XMLHttpRequest&&(d=a.browser||a,b(d,function(a,b,d){f++,e[c]=b||!1,g()}))})}}(),"undefined"!=typeof module&&(module.exports=n.requireOnce)}(this);<commit_msg>minified file<commit_after>!function(a,b){var c={},d=function(a,b){function g(){var b=f.request=new XMLHttpRequest;b.onreadystatechange=function(){if(b.readyState==XMLHttpRequest.DONE)if(b.status>=200&&b.status<300){f.result="success";for(var c=0;c<f.waiters.length;c++)f.waiters[c](b)}else if(b.status>=300&&b.status<400)d=b.getResponseHeader("Location")||a,d!=a?g():(f.attempts++,setTimeout(g,100*f.attempts));else if(f.attempts<5)f.attempts++,setTimeout(g,100*f.attempts);else{for(var c=0;c<f.waiters.length;c++)f.waiters[c](b);f.result="failed"}},b.open("GET",d,!0),b.send()}var d=a,e=c[a];if(e&&void 0!==e.result)b(e.request,e.returnVal);else if(e&&"undefined"===e.result)e.waiters.push(b);else{var f=c[a]={waiters:[b],attempts:1};g()}};if("undefined"!=typeof document&&"undefined"!=typeof XMLHttpRequest){var e=[];document.addEventListener("readystatechange",function(){if("complete"==document.readyState)for(var a=0;a<e.length;a++)e[a]()});var g=[],h=[];XMLHttpRequest.prototype._send=XMLHttpRequest.prototype.send,XMLHttpRequest.prototype.send=function(){var a=this;g.push(a);a.addEventListener("loadend",function(){h.length&&h[h.length-1]()}),a._send()}}a.requireOnce=a.require_once=function(e,f,i){if(!f)throw"Success callback not defined";i=i||function(){};var j=[],k=0,l=function(){if(h.splice(h.length-1,1),g.reduce(function(a,b){return a&&(b.readyState==XMLHttpRequest.DONE||"complete"==b.readyState)},!0)){j.forEach(function(a,b){var d=e[b].browser||e[b];c[d].returnVal=a.returnVal,a&&a.evaluater&&(c[d].returnVal=a.returnVal=a.evaluater.module.export!=a.evaluater.module.exports?a.evaluater.module.exports:a.evaluater.output)});var d=!0,k=j.map(function(a){return a?a.returnVal:d=!1});d?f.apply(a,k):i.apply(a,k),h.length&&h[h.length-1]()}else h.push(l)},m=function(){if(k==e.length){j.forEach(function(a){a&&void 0===a.returnVal&&a.xhr.getResponseHeader("Content-Type").match(/javascript/i)?a.evaluater=b(a.xhr.responseText):a&&void 0===a.returnVal&&a.xhr&&(a.returnVal=a.xhr.responseText)}),h.push(l);g.reduce(function(a,b){return a&&(b.readyState==XMLHttpRequest.DONE||"complete"==b.readyState)},!0)&&h[h.length-1]()}};e.forEach(function(b,c){var g;"undefined"!=typeof require&&"undefined"==typeof XMLHttpRequest?(g=b.server,j[c]=!!g&&require(g),++k==e.length&&f.apply(a,j)):XMLHttpRequest&&(g=b.browser||b,d(g,function(a,b){a.status>=200&&a.status<300?j[c]={xhr:a,returnVal:b}:j[c]=!1,k++,m()}))})},"undefined"!=typeof module&&(module.exports=a.requireOnce)}(this,function(code){var module={},requireOnce=this.requireOnce,require_once=this.require_once,exporter=module.exports=module.export=function(a){module.exports=a},results=eval(code);return{output:results,module:module}});
<|endoftext|>


<commit_before>var restify = require('restify');
var _ = require('underscore');

var logError = console.error;
console.error = function () {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('-');
    args.unshift(new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''));
    logError.apply(this, args);
};

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

// We are looking for any config environment variable that matches our format
var shouldUseEnvForConfig = false;
_.filter(Object.keys(process.env), function(env_key){
  if(/[A-Z]{2,10}:SLACK_URL/i.test(env_key)){
    shouldUseEnvForConfig = true;
    return false; // break
  }
});

if(shouldUseEnvForConfig) {
  require('nconf').use('env');
  console.log('Using ENV variables for configuration.')
} else {
  var configFile = process.argv[2] ? process.argv[2] : './secret.config.json';
  console.log('Using config file: ' + configFile);
  require('nconf').use('file', { file: configFile }).argv();
}

var port = 3000,
    jira = require('./controllers/JiraCtrl'),
    server = restify.createServer({
        name: 'SlackIntegration API'
    });

server.use(restify.gzipResponse());
server.use(restify.queryParser());
server.use(restify.bodyParser({
    maxBodySize: 0
}));

server.on('uncaughtException', function (req, res, route, error) {
    /* jshint -W109 */
    console.error(error.toString());
    res.json(error.statusCode, {
        msg: error.message,
        stack: error.stack
    });
});

var respond = function(req, res, next) {
    res.send(200, {
        hello: 'world'
    });
    next();
};

server.get('/', respond);
server.post('/api/jira', jira.receiveEvent);

server.listen(port);
console.log('Starting Restify on port: ' + port);
<commit_msg>Accepts port from environment variable. Defaults to 3000.<commit_after>var restify = require('restify');
var _ = require('underscore');

var logError = console.error;
console.error = function () {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('-');
    args.unshift(new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''));
    logError.apply(this, args);
};

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

// We are looking for any config environment variable that matches our format
var shouldUseEnvForConfig = false;
_.filter(Object.keys(process.env), function(env_key){
  if(/[A-Z]{2,10}:SLACK_URL/i.test(env_key)){
    shouldUseEnvForConfig = true;
    return false; // break
  }
});

if(shouldUseEnvForConfig) {
  require('nconf').use('env');
  console.log('Using ENV variables for configuration.')
} else {
  var configFile = process.argv[2] ? process.argv[2] : './secret.config.json';
  console.log('Using config file: ' + configFile);
  require('nconf').use('file', { file: configFile }).argv();
}

var port = process.env.PORT || 3000,
    jira = require('./controllers/JiraCtrl'),
    server = restify.createServer({
        name: 'SlackIntegration API'
    });

server.use(restify.gzipResponse());
server.use(restify.queryParser());
server.use(restify.bodyParser({
    maxBodySize: 0
}));

server.on('uncaughtException', function (req, res, route, error) {
    /* jshint -W109 */
    console.error(error.toString());
    res.json(error.statusCode, {
        msg: error.message,
        stack: error.stack
    });
});

var respond = function(req, res, next) {
    res.send(200, {
        hello: 'world'
    });
    next();
};

server.get('/', respond);
server.post('/api/jira', jira.receiveEvent);

server.listen(port);
console.log('Starting Restify on port: ' + port);
<|endoftext|>