<commit_before>'use strict';

//global variables
var hours = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm: '];

//store information stored as an object
var firstAndPike = {
  minHourlyCust: 23,
  maxHourlyCust: 65,
  avgCookies: 6.3,
  location: [],
  customers: function() {   //average number of customers per hour
    var people = Math.floor(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    console.log(people);
    return people;
  },
  cookiesPerHour: function() {    //amount of cookies sold per hour
    for(var i = 0; i < hours.length; i ++){
      var amount = Math.floor(this.customers() * this.avgCookies);
      console.log(amount);
      this.location.push(amount);
    }
    return this.location;
  },

  print: function() {   //print to sales.html
    var businessList = document.getElementById('pike');
    this.cookiesPerHour();
    console.log(this.location);
    for(var i = 0; i < this.location.length; i ++) {
      var listEl = document.createElement('li');
      listEl.textContent = hours[i] + this.location[i];
      businessList.appendChild(listEl);
    }
  }
};
firstAndPike.print();

//store information stored as an object
var seatac = {
  minHourlyCust: 23,
  maxHourlyCust: 65,
  avgCookies: 6.3,
  location: [],
  customers: function() {   //average number of customers per hour
    var people = Math.floor(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    console.log(people);
    return people;
  },
  cookiesPerHour: function() {    //amount of cookies sold per hour
    for(var i = 0; i < hours.length; i ++){
      var amount = Math.floor(this.customers() * this.avgCookies);
      console.log(amount);
      this.location.push(amount);
    }
    return this.location;
  },

  print: function() {   //print to sales.html
    var businessList = document.getElementById('seatac');
    this.cookiesPerHour();
    console.log(this.location);
    for(var i = 0; i < this.location.length; i ++) {
      var listEl = document.createElement('li');
      listEl.textContent = hours[i] + this.location[i];
      businessList.appendChild(listEl);
    }
  }
};
seatac.print();

//store information stored as an object
var seattleCenter = {
  minHourlyCust: 23,
  maxHourlyCust: 65,
  avgCookies: 6.3,
  location: [],
  customers: function() {   //average number of customers per hour
    var people = Math.floor(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    console.log(people);
    return people;
  },
  cookiesPerHour: function() {    //amount of cookies sold per hour
    for(var i = 0; i < hours.length; i ++){
      var amount = Math.floor(this.customers() * this.avgCookies);
      console.log(amount);
      this.location.push(amount);
    }
    return this.location;
  },

  print: function() {   //print to sales.html
    var businessList = document.getElementById('seattleCenter');
    this.cookiesPerHour();
    console.log(this.location);
    for(var i = 0; i < this.location.length; i ++) {
      var listEl = document.createElement('li');
      listEl.textContent = hours[i] + this.location[i];
      businessList.appendChild(listEl);
    }
  }
};
seattleCenter.print();
<commit_msg>added final two stores to the sales.html file<commit_after>'use strict';

//global variables
var hours = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm: '];

//store information stored as an object
var firstAndPike = {
  minHourlyCust: 23,
  maxHourlyCust: 65,
  avgCookies: 6.3,
  location: [],
  customers: function() {   //average number of customers per hour
    var people = Math.floor(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    console.log(people);
    return people;
  },
  cookiesPerHour: function() {    //amount of cookies sold per hour
    for(var i = 0; i < hours.length; i ++){
      var amount = Math.floor(this.customers() * this.avgCookies);
      console.log(amount);
      this.location.push(amount);
    }
    return this.location;
  },

  print: function() {   //print to sales.html
    var businessList = document.getElementById('pike');
    this.cookiesPerHour();
    console.log(this.location);
    for(var i = 0; i < this.location.length; i ++) {
      var listEl = document.createElement('li');
      listEl.textContent = hours[i] + this.location[i];
      businessList.appendChild(listEl);
    }
  }
};
firstAndPike.print();

//store information stored as an object
var seatac = {
  minHourlyCust: 23,
  maxHourlyCust: 65,
  avgCookies: 6.3,
  location: [],
  customers: function() {   //average number of customers per hour
    var people = Math.floor(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    console.log(people);
    return people;
  },
  cookiesPerHour: function() {    //amount of cookies sold per hour
    for(var i = 0; i < hours.length; i ++){
      var amount = Math.floor(this.customers() * this.avgCookies);
      console.log(amount);
      this.location.push(amount);
    }
    return this.location;
  },

  print: function() {   //print to sales.html
    var businessList = document.getElementById('seatac');
    this.cookiesPerHour();
    console.log(this.location);
    for(var i = 0; i < this.location.length; i ++) {
      var listEl = document.createElement('li');
      listEl.textContent = hours[i] + this.location[i];
      businessList.appendChild(listEl);
    }
  }
};
seatac.print();

//store information stored as an object
var seattleCenter = {
  minHourlyCust: 23,
  maxHourlyCust: 65,
  avgCookies: 6.3,
  location: [],
  customers: function() {   //average number of customers per hour
    var people = Math.floor(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    console.log(people);
    return people;
  },
  cookiesPerHour: function() {    //amount of cookies sold per hour
    for(var i = 0; i < hours.length; i ++){
      var amount = Math.floor(this.customers() * this.avgCookies);
      console.log(amount);
      this.location.push(amount);
    }
    return this.location;
  },

  print: function() {   //print to sales.html
    var businessList = document.getElementById('seattleCenter');
    this.cookiesPerHour();
    console.log(this.location);
    for(var i = 0; i < this.location.length; i ++) {
      var listEl = document.createElement('li');
      listEl.textContent = hours[i] + this.location[i];
      businessList.appendChild(listEl);
    }
  }
};
seattleCenter.print();

//store information stored as an object
var capitalHill = {
  minHourlyCust: 23,
  maxHourlyCust: 65,
  avgCookies: 6.3,
  location: [],
  customers: function() {   //average number of customers per hour
    var people = Math.floor(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    console.log(people);
    return people;
  },
  cookiesPerHour: function() {    //amount of cookies sold per hour
    for(var i = 0; i < hours.length; i ++){
      var amount = Math.floor(this.customers() * this.avgCookies);
      console.log(amount);
      this.location.push(amount);
    }
    return this.location;
  },

  print: function() {   //print to sales.html
    var businessList = document.getElementById('capitalHill');
    this.cookiesPerHour();
    console.log(this.location);
    for(var i = 0; i < this.location.length; i ++) {
      var listEl = document.createElement('li');
      listEl.textContent = hours[i] + this.location[i];
      businessList.appendChild(listEl);
    }
  }
};
capitalHill.print();

//store information stored as an object
var alki = {
  minHourlyCust: 23,
  maxHourlyCust: 65,
  avgCookies: 6.3,
  location: [],
  customers: function() {   //average number of customers per hour
    var people = Math.floor(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    console.log(people);
    return people;
  },
  cookiesPerHour: function() {    //amount of cookies sold per hour
    for(var i = 0; i < hours.length; i ++){
      var amount = Math.floor(this.customers() * this.avgCookies);
      console.log(amount);
      this.location.push(amount);
    }
    return this.location;
  },

  print: function() {   //print to sales.html
    var businessList = document.getElementById('alki');
    this.cookiesPerHour();
    console.log(this.location);
    for(var i = 0; i < this.location.length; i ++) {
      var listEl = document.createElement('li');
      listEl.textContent = hours[i] + this.location[i];
      businessList.appendChild(listEl);
    }
  }
};
alki.print();
<|endoftext|>


<commit_before>// Link types.
exports.types = {
	loopback   : 'loopback',    // Loopback.
	ethernet   : 'ether',       // Ethernet.
	pointopoint: 'ppp'          // Point to Point.
};

// Virtual link types.
exports.vl_types = [
	'bridge',   // Ethernet Bridge device.
	'can',      // Controller Area Network interface.
	'dummy',    // Dummy network interface.
	'ifb',      // Intermediate Functional Block device.
	'ipoib',    // IP over Infiniband device.
	'macvlan',  // Virtual interface base on link layer address (MAC).
	'vcan',     // Virtual Local CAN interface.
	'veth',     // Virtual ethernet interface.
	'vlan',     // 802.1q tagged virtual LAN interface.
	'vxlan'     // Virtual eXtended LAN.
];

// Interface flags.
exports.flags = [
	'UP',
	'LOOPBACK',
	'BROADCAST',
	'POINTOPOINT',
	'MULTICAST',
	'PROMISC',
	'ALLMULTI',
	'NOARP',
	'DYNAMIC',
	'SLAVE',

	// Undocumented.
	'LOWER_UP',
	'NO-CARRIER',
	'M-DOWN'
];

exports.flag_statuses = {
	on : 'on',
	off: 'off'
};

// Interface statuses.
exports.statuses = {
	UP            : 'UP',               // Ready to pass packets (if admin status is changed to up, then operational status should change to up if the interface is ready to transmit and receive network traffic).
	DOWN          : 'DOWN',             // If admin status is down, then operational status should be down.
	UNKNOWN       : 'UNKNOWN',          // Status can not be determined for some reason.
	LOWERLAYERDOWN: 'LOWERLAYERDOWN',   // Down due to state of lower layer interface.
	NOTPRESENT    : 'NOTPRESENT',       // Some component is missing, typically hardware.
	TESTING       : 'TESTING',          // In test mode, no operational packets can be passed.
	DORMANT       : 'DORMANT'           // Interface is waiting for external actions.
};

/**
 * Parses .show() output.
 *
 * @param raw_data
 * @returns {Array}
 */
exports.parse_links = function (raw_data) {
	if (!raw_data) {
		throw new Error('Invalid arguments.');
	}
	else {
		/*
		 * Process the output to give parsed results.
		 */
		var links = [];

		var output = raw_data.split('\n');

		for (var line = 0, output_length = output.length - 1;
		     line < output_length;
		     line += 2 /* Each link is composed for two lines. */) {

			var link_line_1 = output[line];
			var link_fields_1 = link_line_1.trim().split(/\s/g);

			var link_line_2 = output[line + 1];
			var link_fields_2 = link_line_2.trim().split(/\s/g);

			var name = link_fields_1[1].split(':')[0];
			var link = {
				index: link_fields_1[0].split(':')[0], // Don't needed since the array is ordered anyway but just in case.
				name : name,
				flags: link_fields_1[2].slice(1, -1).split(','), // First remove the <,> chars.

				type: link_fields_2[0].split('\/')[1],

				mac: link_fields_2[1],
				brd: link_fields_2[3]
			};

			/*
			 * Parses dynamically the following fields, if are there.
			 *
			 * mtu
			 * qdisc
			 * state
			 * mode
			 * qlen
			 */
			var rest_line_fields = link_fields_1.slice(3);
			for (var i = 0, rest_line_length = rest_line_fields.length - 1;
			     i < rest_line_length;
			     i += 2 /* Each field is composed for two consecutive items. */) {

				link[rest_line_fields[i]] = rest_line_fields[i + 1];
			}

			/*
			 * Parses and append the virtual link type, if any.
			 */
			if (name.split('@').length == 2) {
				// Is a VLAN.
				link['vl_type'] = 'vlan';
				link['name'] = name.split('@')[0];
			}

			/*
			 * Finally, add the parsed link to the output.
			 */
			links.push(link);
		}

		return links;
	}
};<commit_msg>ip-link: Changed vl_types to an object format to make it really usable.<commit_after>// Link types.
exports.types = {
	loopback   : 'loopback',    // Loopback.
	ethernet   : 'ether',       // Ethernet.
	pointopoint: 'ppp'          // Point to Point.
};

// Virtual link types.
exports.vl_types = {
	bridge : 'bridge',   // Ethernet Bridge device.
	can    : 'can',      // Controller Area Network interface.
	dummy  : 'dummy',    // Dummy network interface.
	ifb    : 'ifb',      // Intermediate Functional Block device.
	ipoib  : 'ipoib',    // IP over Infiniband device.
	macvlan: 'macvlan',  // Virtual interface base on link layer address (MAC).
	vcan   : 'vcan',     // Virtual Local CAN interface.
	veth   : 'veth',     // Virtual ethernet interface.
	vlan   : 'vlan',     // 802.1q tagged virtual LAN interface.
	vxlan  : 'vxlan'     // Virtual eXtended LAN.
};

// Interface flags.
exports.flags = [
	'UP',
	'LOOPBACK',
	'BROADCAST',
	'POINTOPOINT',
	'MULTICAST',
	'PROMISC',
	'ALLMULTI',
	'NOARP',
	'DYNAMIC',
	'SLAVE',

	// Undocumented.
	'LOWER_UP',
	'NO-CARRIER',
	'M-DOWN'
];

exports.flag_statuses = {
	on : 'on',
	off: 'off'
};

// Interface statuses.
exports.statuses = {
	UP            : 'UP',               // Ready to pass packets (if admin status is changed to up, then operational status should change to up if the interface is ready to transmit and receive network traffic).
	DOWN          : 'DOWN',             // If admin status is down, then operational status should be down.
	UNKNOWN       : 'UNKNOWN',          // Status can not be determined for some reason.
	LOWERLAYERDOWN: 'LOWERLAYERDOWN',   // Down due to state of lower layer interface.
	NOTPRESENT    : 'NOTPRESENT',       // Some component is missing, typically hardware.
	TESTING       : 'TESTING',          // In test mode, no operational packets can be passed.
	DORMANT       : 'DORMANT'           // Interface is waiting for external actions.
};

/**
 * Parses .show() output.
 *
 * @param raw_data
 * @returns {Array}
 */
exports.parse_links = function (raw_data) {
	if (!raw_data) {
		throw new Error('Invalid arguments.');
	}
	else {
		/*
		 * Process the output to give parsed results.
		 */
		var links = [];

		var output = raw_data.split('\n');

		for (var line = 0, output_length = output.length - 1;
		     line < output_length;
		     line += 2 /* Each link is composed for two lines. */) {

			var link_line_1 = output[line];
			var link_fields_1 = link_line_1.trim().split(/\s/g);

			var link_line_2 = output[line + 1];
			var link_fields_2 = link_line_2.trim().split(/\s/g);

			var name = link_fields_1[1].split(':')[0];
			var link = {
				index: link_fields_1[0].split(':')[0], // Don't needed since the array is ordered anyway but just in case.
				name : name,
				flags: link_fields_1[2].slice(1, -1).split(','), // First remove the <,> chars.

				type: link_fields_2[0].split('\/')[1],

				mac: link_fields_2[1],
				brd: link_fields_2[3]
			};

			/*
			 * Parses dynamically the following fields, if are there.
			 *
			 * mtu
			 * qdisc
			 * state
			 * mode
			 * qlen
			 */
			var rest_line_fields = link_fields_1.slice(3);
			for (var i = 0, rest_line_length = rest_line_fields.length - 1;
			     i < rest_line_length;
			     i += 2 /* Each field is composed for two consecutive items. */) {

				link[rest_line_fields[i]] = rest_line_fields[i + 1];
			}

			/*
			 * Parses and append the virtual link type, if any.
			 */
			if (name.split('@').length == 2) {
				// Is a VLAN.
				link['vl_type'] = 'vlan';
				link['name'] = name.split('@')[0];
			}

			/*
			 * Finally, add the parsed link to the output.
			 */
			links.push(link);
		}

		return links;
	}
};<|endoftext|>


<commit_before>const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

if (process.env.NODE_ENV == 'production') {
  require('newrelic');
}

server.all('*', (req, res, next) => {
  if (req.method !== 'GET') {
    res.status(403).jsonp({
      error: true,
      message: '403 Forbidden'
    })
  } else {
    next()
  }
})

server.get('/', (req, res) => {
  res.redirect('https://github.com/wgenial/br-cidades-estados-nodejs/blob/master/README.md')
})

server.use(jsonServer.rewriter({
  '/estados/:id': '/estados/:id?_embed=cidades',
  '/estados/:id/cidades': '/estados/:id?_embed=cidades',
  '/estados/:id/capital': '/estados/:id/cidades?capital=true',
  '/capitais': '/cidades?capital=true'
}))

router.render = (req, res) => {
  if (res.statusCode == 404) {
    res.jsonp({
      error: true,
      message: '404 Not Found'
    })
  } else {
    res.jsonp(res.locals.data)
  }
}

server.use(middlewares)

server.use(router)

server.listen(process.env.PORT || 3000, () => { console.log('JSON Server is running.') })

exports = module.exports = server;<commit_msg>cleanup<commit_after>const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

server.all('*', (req, res, next) => {
  if (req.method !== 'GET') {
    res.status(403).jsonp({
      error: true,
      message: '403 Forbidden'
    })
  } else {
    next()
  }
})

server.get('/', (req, res) => {
  res.redirect('https://github.com/wgenial/br-cidades-estados-nodejs/blob/master/README.md')
})

server.use(jsonServer.rewriter({
  '/estados/:id': '/estados/:id?_embed=cidades',
  '/estados/:id/cidades': '/estados/:id?_embed=cidades',
  '/estados/:id/capital': '/estados/:id/cidades?capital=true',
  '/capitais': '/cidades?capital=true'
}))

router.render = (req, res) => {
  if (res.statusCode == 404) {
    res.jsonp({
      error: true,
      message: '404 Not Found'
    })
  } else {
    res.jsonp(res.locals.data)
  }
}

server.use(middlewares)

server.use(router)

server.listen(process.env.PORT || 3000, () => { console.log('JSON Server is running.') })

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


<commit_before>'use strict';

var async = require( 'async' ),
    request = require( 'request' ),
    jwt = require( 'jsonwebtoken' ),
    spawn = require( 'cross-spawn-async' ),
    child = require( 'child_process' ),
    logger = require( './lib/logger' ),
    nconf = require( 'nconf' ),
    uuid = require( 'node-uuid' ),
    sigInt = false;

nconf.file( {file: 'config.json'} );

function requestSettings( config, callback ) {
    async.waterfall( [
        function( callback ) {
            var apiKeyId = config.apiKey.slice( 0, 40 ),
                apiKeySecret = config.apiKey.slice( 40, 80 ),
                token = jwt.sign( {apiKeyId: apiKeyId}, apiKeySecret, {
                    expiresIn: '60s'
                } );
            callback( null, token );
        },
        function( token, callback ) {
            request( {
                url: config.host + config.apiEndpoint,
                headers: {
                    'Authorization': token
                },
                json: true
            }, function( err, res, body ) {
                if( err ) return logger.error( err );
                if( res.statusCode !== 200 ) return logger.error( 'HTTP' + res.statusCode, res.body );
                callback( null, body );
            } );
        }
    ], callback );
}

function ipwVersion( callback ) {
    var process = spawn( 'npm', ['list', '-json', '--depth=0'] ),
        stdout = '',
        stderr = '';
    process.stdout.on( 'data', function( data ) {
        stdout += data;
    } );
    process.stderr.on( 'data', function( data ) {
        stderr += data;
    } );
    process.on( 'close', function() {
        if( stderr ) logger.error( stderr );
        try
        {
            var list = JSON.parse( stdout );
            if( !list.dependencies.ipw ) return callback();
            callback( null, list.dependencies.ipw.version || null );
        } catch( err )
        {
            if( err ) return callback( err );
        }
    } );
}

function ipwInstall( ver, callback ) {
    var repo = 'https://github.com/amokrushin/ipw.git',
        url = repo + '#v' + ver,
        process = spawn( 'npm', ['i', url] ),
        stdout = '',
        stderr = '';
    process.stdout.on( 'data', function( data ) {
        stdout += data;
    } );
    process.stderr.on( 'data', function( data ) {
        stderr += data;
    } );
    process.on( 'close', function() {
        if( stderr ) logger.error( stderr );
        callback( null, stdout );
    } );
}

function forkIpw( settings ) {
    logger.info( 'Fork Image processing worker...' );
    var ipw = child.fork( './node_modules/ipw/app.js' );
    ipw.send( {
        msg: 'uuid',
        content: uuid
    } );
    ipw.send( {
        msg: 'settings',
        content: settings
    } );

    return ipw;
}

function ipwUpdate( requiredVersion, callback ) {
    ipwVersion( function( err, installedVersion ) {
        if( err ) return callback( err );
        if( installedVersion === requiredVersion ) return callback();
        if( !installedVersion )
        {
            logger.info( 'Image processing worker is not installed, required v' + requiredVersion );
            logger.info( 'Image processing worker installing...' );
        }
        else
        {
            logger.info( 'Image processing worker v' + installedVersion + ', required v' + requiredVersion );
            logger.info( 'Image processing worker updating...' );
        }
        ipwInstall( requiredVersion, function( err ) {
            if( err ) return callback( err );
            logger.info( 'Image processing worker v' + requiredVersion + ' installed' );
            return callback();
        } );
    } );
}

function startIpw( config ) {
    async.waterfall( [
        async.apply( requestSettings, config ),
        function( settings, callback ) {
            var requiredVersion = settings.ipw.version;
            if( !requiredVersion ) return callback( 'required IPW version is not defined' );
            ipwUpdate( requiredVersion, function( err ) {
                if( err ) return callback( err );
                callback( null, settings );
            } )
        }
    ], function( err, settings ) {
        if( err ) return logger.error( err );
        var ipw = forkIpw( settings );
        ipw.on( 'exit', function() {
            if( !sigInt ) startIpw( config );
        } );
    } );
}

process.once( 'SIGINT', function() {
    sigInt = true;
    logger.info( 'SIGINT' );
    setTimeout( function() {
        logger.info( 'EXIT' );
        process.exit();
    }, 1000 );
} );

async.waterfall( [
    nconf.load.bind( nconf ),
    function( config, callback ) {
        if( !config.uuid ) nconf.set( 'uuid', uuid.v1() );
        nconf.save( function( err ) {
            if( err ) return logger.error( err );
            callback( null, config );
        } );
    },
    startIpw
] );
<commit_msg>fix (save uuid)<commit_after>'use strict';

var async = require( 'async' ),
    request = require( 'request' ),
    jwt = require( 'jsonwebtoken' ),
    spawn = require( 'cross-spawn-async' ),
    child = require( 'child_process' ),
    logger = require( './lib/logger' ),
    nconf = require( 'nconf' ),
    uuid = require( 'node-uuid' ),
    sigInt = false;

nconf.file( {file: 'config.json'} );

function requestSettings( config, callback ) {
    async.waterfall( [
        function( callback ) {
            var apiKeyId = config.apiKey.slice( 0, 40 ),
                apiKeySecret = config.apiKey.slice( 40, 80 ),
                token = jwt.sign( {apiKeyId: apiKeyId}, apiKeySecret, {
                    expiresIn: '60s'
                } );
            callback( null, token );
        },
        function( token, callback ) {
            request( {
                url: config.host + config.apiEndpoint,
                headers: {
                    'Authorization': token
                },
                json: true
            }, function( err, res, body ) {
                if( err ) return logger.error( err );
                if( res.statusCode !== 200 ) return logger.error( 'HTTP' + res.statusCode, res.body );
                callback( null, body );
            } );
        }
    ], callback );
}

function ipwVersion( callback ) {
    var process = spawn( 'npm', ['list', '-json', '--depth=0'] ),
        stdout = '',
        stderr = '';
    process.stdout.on( 'data', function( data ) {
        stdout += data;
    } );
    process.stderr.on( 'data', function( data ) {
        stderr += data;
    } );
    process.on( 'close', function() {
        if( stderr ) logger.error( stderr );
        try
        {
            var list = JSON.parse( stdout );
            if( !list.dependencies.ipw ) return callback();
            callback( null, list.dependencies.ipw.version || null );
        } catch( err )
        {
            if( err ) return callback( err );
        }
    } );
}

function ipwInstall( ver, callback ) {
    var repo = 'https://github.com/amokrushin/ipw.git',
        url = repo + '#v' + ver,
        process = spawn( 'npm', ['i', url] ),
        stdout = '',
        stderr = '';
    process.stdout.on( 'data', function( data ) {
        stdout += data;
    } );
    process.stderr.on( 'data', function( data ) {
        stderr += data;
    } );
    process.on( 'close', function() {
        if( stderr ) logger.error( stderr );
        callback( null, stdout );
    } );
}

function forkIpw( config, settings ) {
    logger.info( 'Fork Image processing worker...' );
    var ipw = child.fork( './node_modules/ipw/app.js' );
    ipw.send( {
        msg: 'uuid',
        content: config.uuid
    } );
    ipw.send( {
        msg: 'settings',
        content: settings
    } );

    return ipw;
}

function ipwUpdate( requiredVersion, callback ) {
    ipwVersion( function( err, installedVersion ) {
        if( err ) return callback( err );
        if( installedVersion === requiredVersion ) return callback();
        if( !installedVersion )
        {
            logger.info( 'Image processing worker is not installed, required v' + requiredVersion );
            logger.info( 'Image processing worker installing...' );
        }
        else
        {
            logger.info( 'Image processing worker v' + installedVersion + ', required v' + requiredVersion );
            logger.info( 'Image processing worker updating...' );
        }
        ipwInstall( requiredVersion, function( err ) {
            if( err ) return callback( err );
            logger.info( 'Image processing worker v' + requiredVersion + ' installed' );
            return callback();
        } );
    } );
}

function startIpw( config ) {
    async.waterfall( [
        async.apply( requestSettings, config ),
        function( settings, callback ) {
            var requiredVersion = settings.ipw.version;
            if( !requiredVersion ) return callback( 'required IPW version is not defined' );
            ipwUpdate( requiredVersion, function( err ) {
                if( err ) return callback( err );
                callback( null, settings );
            } )
        }
    ], function( err, settings ) {
        if( err ) return logger.error( err );
        var ipw = forkIpw( config, settings );
        ipw.on( 'exit', function() {
            if( !sigInt ) startIpw( config );
        } );
    } );
}

process.once( 'SIGINT', function() {
    sigInt = true;
    logger.info( 'SIGINT' );
    setTimeout( function() {
        logger.info( 'EXIT' );
        process.exit();
    }, 1000 );
} );

async.waterfall( [
    nconf.load.bind( nconf ),
    function( config, callback ) {
        if( !config.uuid ) nconf.set( 'uuid', uuid.v1() );
        nconf.save( function( err ) {
            if( err ) return logger.error( err );
            callback( null, config );
        } );
    },
    startIpw
] );
<|endoftext|>


<commit_before>/*
 * jQuery UI Slider @VERSION
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */

(function($) {

$.widget("ui.slider", $.extend({}, $.ui.mouse, {

	_init: function() {

		var self = this;

		this._keySliding = false;

		this._mouseInit();

		this.element
			.addClass("ui-slider"
				+ " ui-slider-" + this._orientation()
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all");

		this.range = $([]);

		if (this.options.range) {
			if (this.options.range === true) {
				this.range = $('');
				if (!this.options.values) this.options.values = [this._valueMin(), this._valueMin()];
				if (this.options.values.length && this.options.values.length != 2) {
					this.options.values = [this.options.values[0], this.options.values[0]];
				}
			} else {
				this.range = $('

');
			}
			this.range
				.appendTo(this.element)
				.addClass("ui-slider-range"
					+ " ui-widget-header");

			var oRange = this.options.range, oOrientation = this._orientation();
			(oRange == "min") && (oOrientation == "horizontal") && this.range.css({ left : 0 });
			(oRange == "max") && (oOrientation == "horizontal") && this.range.css({ right : 0 });
			(oRange == "min") && (oOrientation == "vertical") && this.range.css({ bottom : 0 });
			(oRange == "max") && (oOrientation == "vertical") && this.range.css({ top : 0 });
		}

		if ($(".ui-slider-handle", this.element).length == 0)
			$('')
				.appendTo(this.element)
				.addClass("ui-slider-handle");

		if (this.options.values && this.options.values.length) {
			while ($(".ui-slider-handle", this.element).length < this.options.values.length)
				$('')
					.appendTo(this.element)
					.addClass("ui-slider-handle");
		}

		this.handles = $(".ui-slider-handle", this.element)
			.addClass("ui-state-default"
				+ " ui-corner-all");

		this.handle = this.handles.eq(0);

		this.handles.add(this.range).filter("a")
			.click(function(event) { event.preventDefault(); })
			.hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
			.focus(function() { self.handles.removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); })
			.blur(function() { $(this).removeClass('ui-state-focus'); });

		this.handles.each(function(i) {
			$(this).data("index.ui-slider-handle", i);
		})

		this.handles.keydown(function(event) {
			var index = $(this).data("index.ui-slider-handle");

			if (self.options.disabled)
				return;

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if (!self._keySliding) {
						self._keySliding = true;
						$(this).addClass("ui-state-active");
						self._start(event);
					}
					break;
			}

			var curVal, newVal, step = self._step();
			if (self.options.values && self.options.values.length) {
				curVal = newVal = self.values(index);
			} else {
				curVal = newVal = self.value();
			}

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
					newVal = self._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = self._valueMax();
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					newVal = curVal + step;
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					newVal = curVal - step;
					break;
			}

			self._slide(event, newVal);
		}).keyup(function(event) {
			if (self._keySliding) {
				self._stop(event);
				self._change(event);
				self._keySliding = false;
				$(this).removeClass("ui-state-active");
			}
		});

		this._refreshValue();

	},

	destroy: function() {

		this.handles.remove();

		this.element
			.removeClass("ui-slider"
				+ " ui-slider-horizontal"
				+ " ui-slider-vertical"
				+ " ui-slider-disabled"
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all")
			.removeData("slider")
			.unbind(".slider");

		this._mouseDestroy();

	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (o.disabled)
			return false;

		this._start(event);

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);

		var distance = this._valueMax(), closestHandle;
		var self = this;
		this.handles.each(function(i) {
			var thisDistance = Math.abs(normValue - self.values(i));
			if (distance > thisDistance) {
				distance = thisDistance;
				closestHandle = $(this);
			}
		});

		closestHandle
			.addClass("ui-state-active")
			.focus();

		this._slide(event, normValue);

		return true;

	},

	_mouseStart: function(event) {
		return true;
	},

	_mouseDrag: function(event) {
		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);

		this._slide(event, normValue);

		return false;
	},

	_mouseStop: function(event) {
		this.handles.removeClass("ui-state-active");
		this._stop(event);
		this._change(event);

		return false;
	},

	_normValueFromMouse: function(position) {

		var pixelTotal, pixelMouse;
		if ('horizontal' == this._orientation()) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left;
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top;
		}

		var percentMouse = (pixelMouse / pixelTotal);
		if (percentMouse > 1) percentMouse = 1;
		if (percentMouse < 0) percentMouse = 0;
		if ('vertical' == this._orientation())
			percentMouse = 1 - percentMouse;

		var valueTotal = this._valueMax() - this._valueMin();

		var valueMouse = percentMouse * valueTotal;

		var valueMouseModStep = valueMouse % this.options.step;

		var normValue = this._valueMin() + valueMouse - valueMouseModStep;

		if (valueMouseModStep > (this.options.step / 2))
			normValue += this.options.step;

		return normValue;
	},

	_start: function(event) {
		this._trigger("start", event, {
			value: this.value()
		});
	},

	_slide: function(event, newVal) {
		if (this.options.values && this.options.values.length) {
			var handle = this.handles.filter(".ui-state-active");
			var index = handle.data("index.ui-slider-handle");
			if (newVal != this.values(index)) {
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					handle: handle,
					value: newVal
				});
				if (allowed !== false)
					this.values(index, newVal);
			}
		} else {
			if (newVal != this.value()) {
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					value: newVal
				});
				if (allowed !== false)
					this._setData('value', newVal);
			}
		}
	},

	_stop: function(event) {
		this._trigger("stop", event, {
			value: this.value()
		});
	},

	_change: function(event) {
		this._trigger("change", event, {
			value: this.value()
		});
	},

	value: function(newValue) {
		if (arguments.length) {
			this._setData("value", newValue);
			this._change();
		}

		return this._value();
	},

	values: function(index, newValue) {
		if (arguments.length > 1) {
			this.options.values[index] = newValue;
			this._refreshValue();
			this._change();
		}

		if (arguments.length) {
			if (this.options.values && this.options.values.length) {
				return this._values(index);
			} else {
				return this.value();
			}
		} else {
			return this._values();
		}
	},

	_setData: function(key, value) {
		$.widget.prototype._setData.apply(this, arguments);

		switch (key) {
			case 'orientation':
				this.element
					.removeClass("ui-slider-horizontal ui-slider-vertical")
					.addClass("ui-slider-" + this._orientation());
				this._refreshValue();
				break;
			case 'value':
				this._refreshValue();
				break;
		}
	},

	_orientation: function() {
		var orientation = this.options.orientation;
		if (orientation != 'horizontal' && orientation != 'vertical')
			orientation = 'horizontal';

		return orientation;
	},

	_step: function() {
		var step = this.options.step;

		return step;
	},

	_value: function() {
		var val = this.options.value;
		if (val < this._valueMin()) val = this._valueMin();
		if (val > this._valueMax()) val = this._valueMax();

		return val;
	},

	_values: function(index) {
		if (arguments.length) {
			var val = this.options.values[index];
			if (val < this._valueMin()) val = this._valueMin();
			if (val > this._valueMax()) val = this._valueMax();

			return val;
		} else {
			return this.options.values;
		}
	},

	_valueMin: function() {
		var valueMin = this.options.min;

		return valueMin;
	},

	_valueMax: function() {
		var valueMax = this.options.max;

		return valueMax;
	},

	_refreshValue: function() {
		var oRange = this.options.range, oOrientation = this._orientation();

		if (this.options.values && this.options.values.length) {
			var self = this, vp0, vp1;
			this.handles.each(function(i, j) {
				var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100;
				$(this).css(oOrientation == 'horizontal' ? 'left' : 'bottom', valPercent + '%');
				if (self.options.range === true) {
					if (oOrientation == 'horizontal') {
						(i == 0) && self.range.css('left', valPercent + '%');
						(i == 1) && self.range.css('width', (valPercent - lastValPercent) + '%');
					} else {
						(i == 0) && self.range.css('bottom', (valPercent) + '%');
						(i == 1) && self.range.css('height', (valPercent - lastValPercent) + '%');
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			var valPercent = (this.value() - this._valueMin()) / (this._valueMax() - this._valueMin()) * 100;
			this.handle.css(oOrientation == 'horizontal' ? 'left' : 'bottom', valPercent + '%');

			(oRange == "min") && (oOrientation == "horizontal") && this.range.css({ left: 0, width: valPercent + '%' });
			(oRange == "max") && (oOrientation == "horizontal") && this.range.css({ left: valPercent + '%', width: (100 - valPercent) + '%' });
			(oRange == "min") && (oOrientation == "vertical") && this.range.css({ top: (100 - valPercent) + '%', height: valPercent + '%' });
			(oRange == "max") && (oOrientation == "vertical") && this.range.css({ bottom: valPercent + '%', height: (100 - valPercent) + '%' });
		}
	}

}));

$.extend($.ui.slider, {
	getter: "value values",
	version: "@VERSION",
	defaults: {
		delay: 0,
		distance: 0,
		max: 100,
		min: 0,
		orientation: 'horizontal',
		range: false,
		step: 1,
		value: 0,
		values: null
	}
});

})(jQuery);
<commit_msg>slider: removed hover and focus from range as it's not draggable (yet)<commit_after>/*
 * jQuery UI Slider @VERSION
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */

(function($) {

$.widget("ui.slider", $.extend({}, $.ui.mouse, {

	_init: function() {

		var self = this;

		this._keySliding = false;

		this._mouseInit();

		this.element
			.addClass("ui-slider"
				+ " ui-slider-" + this._orientation()
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all");

		this.range = $([]);

		if (this.options.range) {
			if (this.options.range === true) {
				//this.range = $('');
				this.range = $('

');
				if (!this.options.values) this.options.values = [this._valueMin(), this._valueMin()];
				if (this.options.values.length && this.options.values.length != 2) {
					this.options.values = [this.options.values[0], this.options.values[0]];
				}
			} else {
				this.range = $('

');
			}
			this.range
				.appendTo(this.element)
				.addClass("ui-slider-range"
					+ " ui-widget-header");

			var oRange = this.options.range, oOrientation = this._orientation();
			(oRange == "min") && (oOrientation == "horizontal") && this.range.css({ left : 0 });
			(oRange == "max") && (oOrientation == "horizontal") && this.range.css({ right : 0 });
			(oRange == "min") && (oOrientation == "vertical") && this.range.css({ bottom : 0 });
			(oRange == "max") && (oOrientation == "vertical") && this.range.css({ top : 0 });
		}

		if ($(".ui-slider-handle", this.element).length == 0)
			$('')
				.appendTo(this.element)
				.addClass("ui-slider-handle");

		if (this.options.values && this.options.values.length) {
			while ($(".ui-slider-handle", this.element).length < this.options.values.length)
				$('')
					.appendTo(this.element)
					.addClass("ui-slider-handle");
		}

		this.handles = $(".ui-slider-handle", this.element)
			.addClass("ui-state-default"
				+ " ui-corner-all");

		this.handle = this.handles.eq(0);

		this.handles.add(this.range).filter("a")
			.click(function(event) { event.preventDefault(); })
			.hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
			.focus(function() { self.handles.removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); })
			.blur(function() { $(this).removeClass('ui-state-focus'); });

		this.handles.each(function(i) {
			$(this).data("index.ui-slider-handle", i);
		})

		this.handles.keydown(function(event) {
			var index = $(this).data("index.ui-slider-handle");

			if (self.options.disabled)
				return;

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if (!self._keySliding) {
						self._keySliding = true;
						$(this).addClass("ui-state-active");
						self._start(event);
					}
					break;
			}

			var curVal, newVal, step = self._step();
			if (self.options.values && self.options.values.length) {
				curVal = newVal = self.values(index);
			} else {
				curVal = newVal = self.value();
			}

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
					newVal = self._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = self._valueMax();
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					newVal = curVal + step;
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					newVal = curVal - step;
					break;
			}

			self._slide(event, newVal);
		}).keyup(function(event) {
			if (self._keySliding) {
				self._stop(event);
				self._change(event);
				self._keySliding = false;
				$(this).removeClass("ui-state-active");
			}
		});

		this._refreshValue();

	},

	destroy: function() {

		this.handles.remove();

		this.element
			.removeClass("ui-slider"
				+ " ui-slider-horizontal"
				+ " ui-slider-vertical"
				+ " ui-slider-disabled"
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all")
			.removeData("slider")
			.unbind(".slider");

		this._mouseDestroy();

	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (o.disabled)
			return false;

		this._start(event);

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);

		var distance = this._valueMax(), closestHandle;
		var self = this;
		this.handles.each(function(i) {
			var thisDistance = Math.abs(normValue - self.values(i));
			if (distance > thisDistance) {
				distance = thisDistance;
				closestHandle = $(this);
			}
		});

		closestHandle
			.addClass("ui-state-active")
			.focus();

		this._slide(event, normValue);

		return true;

	},

	_mouseStart: function(event) {
		return true;
	},

	_mouseDrag: function(event) {
		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);

		this._slide(event, normValue);

		return false;
	},

	_mouseStop: function(event) {
		this.handles.removeClass("ui-state-active");
		this._stop(event);
		this._change(event);

		return false;
	},

	_normValueFromMouse: function(position) {

		var pixelTotal, pixelMouse;
		if ('horizontal' == this._orientation()) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left;
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top;
		}

		var percentMouse = (pixelMouse / pixelTotal);
		if (percentMouse > 1) percentMouse = 1;
		if (percentMouse < 0) percentMouse = 0;
		if ('vertical' == this._orientation())
			percentMouse = 1 - percentMouse;

		var valueTotal = this._valueMax() - this._valueMin();

		var valueMouse = percentMouse * valueTotal;

		var valueMouseModStep = valueMouse % this.options.step;

		var normValue = this._valueMin() + valueMouse - valueMouseModStep;

		if (valueMouseModStep > (this.options.step / 2))
			normValue += this.options.step;

		return normValue;
	},

	_start: function(event) {
		this._trigger("start", event, {
			value: this.value()
		});
	},

	_slide: function(event, newVal) {
		if (this.options.values && this.options.values.length) {
			var handle = this.handles.filter(".ui-state-active");
			var index = handle.data("index.ui-slider-handle");
			if (newVal != this.values(index)) {
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					handle: handle,
					value: newVal
				});
				if (allowed !== false)
					this.values(index, newVal);
			}
		} else {
			if (newVal != this.value()) {
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					value: newVal
				});
				if (allowed !== false)
					this._setData('value', newVal);
			}
		}
	},

	_stop: function(event) {
		this._trigger("stop", event, {
			value: this.value()
		});
	},

	_change: function(event) {
		this._trigger("change", event, {
			value: this.value()
		});
	},

	value: function(newValue) {
		if (arguments.length) {
			this._setData("value", newValue);
			this._change();
		}

		return this._value();
	},

	values: function(index, newValue) {
		if (arguments.length > 1) {
			this.options.values[index] = newValue;
			this._refreshValue();
			this._change();
		}

		if (arguments.length) {
			if (this.options.values && this.options.values.length) {
				return this._values(index);
			} else {
				return this.value();
			}
		} else {
			return this._values();
		}
	},

	_setData: function(key, value) {
		$.widget.prototype._setData.apply(this, arguments);

		switch (key) {
			case 'orientation':
				this.element
					.removeClass("ui-slider-horizontal ui-slider-vertical")
					.addClass("ui-slider-" + this._orientation());
				this._refreshValue();
				break;
			case 'value':
				this._refreshValue();
				break;
		}
	},

	_orientation: function() {
		var orientation = this.options.orientation;
		if (orientation != 'horizontal' && orientation != 'vertical')
			orientation = 'horizontal';

		return orientation;
	},

	_step: function() {
		var step = this.options.step;

		return step;
	},

	_value: function() {
		var val = this.options.value;
		if (val < this._valueMin()) val = this._valueMin();
		if (val > this._valueMax()) val = this._valueMax();

		return val;
	},

	_values: function(index) {
		if (arguments.length) {
			var val = this.options.values[index];
			if (val < this._valueMin()) val = this._valueMin();
			if (val > this._valueMax()) val = this._valueMax();

			return val;
		} else {
			return this.options.values;
		}
	},

	_valueMin: function() {
		var valueMin = this.options.min;

		return valueMin;
	},

	_valueMax: function() {
		var valueMax = this.options.max;

		return valueMax;
	},

	_refreshValue: function() {
		var oRange = this.options.range, oOrientation = this._orientation();

		if (this.options.values && this.options.values.length) {
			var self = this, vp0, vp1;
			this.handles.each(function(i, j) {
				var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100;
				$(this).css(oOrientation == 'horizontal' ? 'left' : 'bottom', valPercent + '%');
				if (self.options.range === true) {
					if (oOrientation == 'horizontal') {
						(i == 0) && self.range.css('left', valPercent + '%');
						(i == 1) && self.range.css('width', (valPercent - lastValPercent) + '%');
					} else {
						(i == 0) && self.range.css('bottom', (valPercent) + '%');
						(i == 1) && self.range.css('height', (valPercent - lastValPercent) + '%');
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			var valPercent = (this.value() - this._valueMin()) / (this._valueMax() - this._valueMin()) * 100;
			this.handle.css(oOrientation == 'horizontal' ? 'left' : 'bottom', valPercent + '%');

			(oRange == "min") && (oOrientation == "horizontal") && this.range.css({ left: 0, width: valPercent + '%' });
			(oRange == "max") && (oOrientation == "horizontal") && this.range.css({ left: valPercent + '%', width: (100 - valPercent) + '%' });
			(oRange == "min") && (oOrientation == "vertical") && this.range.css({ top: (100 - valPercent) + '%', height: valPercent + '%' });
			(oRange == "max") && (oOrientation == "vertical") && this.range.css({ bottom: valPercent + '%', height: (100 - valPercent) + '%' });
		}
	}

}));

$.extend($.ui.slider, {
	getter: "value values",
	version: "@VERSION",
	defaults: {
		delay: 0,
		distance: 0,
		max: 100,
		min: 0,
		orientation: 'horizontal',
		range: false,
		step: 1,
		value: 0,
		values: null
	}
});

})(jQuery);
<|endoftext|>


<commit_before>var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
var https = require('https'), config = require('./config');
var exec = require('child_process').exec, child;

app.engine('html', swig.renderFile);

app.set('view engine', 'html');
app.set('views', __dirname + '/pages');

app.set('view cache', false);
swig.setDefaults({ cache: false });

app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

app.get('/', function(req, res) {
	res.render('index', { 'foo': 'hi' });
});

app.post('/hook', function(req, res) {
	if (req.body && (req.body.after || req.body.pull_request && (req.body.after = req.body.pull_request.head.sha))) {
		console.log("checking: " + req.body.after);
		var request = https.request({ 'host': 'api.github.com',
			'path': '/repos/' + config.repoURL + '/statuses/' + req.body.after + '?access_token=' + config.githubToken,
			'method': 'POST',
			'headers': { 'User-Agent': 'PiCi' }}, function(res) {
				res.on('data', function(data) {
					console.log(data.toString());
				});
			});
		request.write(JSON.stringify({ 'state': 'pending' }));
		request.end();
		var i = 0;
		var cmd = function(n) {
			var inner = function(c) {
				child = exec(config.tasks[n].commands[c], function(error, stdout, stderr) {
					if (error == null) {
						if ((c + 1) < config.tasks[n].commands.length) {
							inner(c + 1);
						}
						else {
							cmd(n + 1);
						}
					}
					else {
						console.log(error);
					}
				});
			}
			inner(n);
		};
		cmd(0);
	}
	console.log(req.body);
	res.end();
});

app.listen(2345);

<commit_msg>Send passed or failed message after running commands<commit_after>var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
var https = require('https'), config = require('./config');
var exec = require('child_process').exec, child;

app.engine('html', swig.renderFile);

app.set('view engine', 'html');
app.set('views', __dirname + '/pages');

app.set('view cache', false);
swig.setDefaults({ cache: false });

app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

app.get('/', function(req, res) {
	res.render('index', { 'foo': 'hi' });
});

app.post('/hook', function(req, res) {
	if (req.body && (req.body.after || req.body.pull_request && (req.body.after = req.body.pull_request.head.sha))) {
		console.log("checking: " + req.body.after);
		sendStatus(req.body.after, 'pending');
		var i = 0;
		var cmd = function(n) {
			var inner = function(c) {
				child = exec(config.tasks[n].commands[c], function(error, stdout, stderr) {
					if (error == null) {
						if ((c + 1) < config.tasks[n].commands.length) {
							inner(c + 1);
						}
						else if ((n + 1) < config.tasks.length) {
							cmd(n + 1);
						}
						else {
							sendStatus(req.body.after, 'passed');
						}
					}
					else {
						console.log(error);
						sendStatus(req.body.after, 'failed');
					}
				});
			}
			inner(n);
		};
		cmd(0);
	}
	console.log(req.body);
	res.end();
});

function sendStatus(sha, state) {
	var request = https.request({ 'host': 'api.github.com',
		'path': '/repos/' + config.repoURL + '/statuses/' + sha + '?access_token=' + config.githubToken,
		'method': 'POST',
		'headers': { 'User-Agent': 'PiCi' }}, function(res) {
			res.on('data', function(data) {
				console.log(data.toString());
			});
		});
	request.write(JSON.stringify({ 'state': state }));
	request.end();
}

app.listen(2345);

<|endoftext|>


<commit_before>/*
 * Mail
 */

var _ = require('underscore')
  , mongodb = require("mongodb")
  , ObjectID = mongodb.ObjectID
  , fs = require('fs')
  , async = require('async')
  , moment = require("moment")
  , MailParser = require("mailparser").MailParser
  , mongo = require("../db")
  , spawn = require('child_process').spawn

  ;

exports.http_add = function (req, res) {

  // アップロードファイル
  var file = req.files.mail.path;

  add(fs.createReadStream(file), function (err, result) {

    // ファイル削除
    fs.unlink(file);

    var info = {
      subject: result.subject,
      to: result.to
    };
    res.send(info);

  });
};

/**
 *
 * @param stream RFC2822(eml形式) stream
 * @param callback
 */
function add(stream, callback) {

  async.waterfall([
    // パース
    function (done) {
      _parse(stream, function (err, mailInfo) {
        done(err, mailInfo);
      });
    },
    // DB登録
    function (mailInfo, done) {
      _insert(mailInfo, function (err, mailInfo) {
        done(err, mailInfo);
      });
    }
  ], function (err, mailInfo) {
    callback(err, mailInfo);
  });

}

function _parse(stream, done) {

  function StuructureInfo() {
    this.count = 0;
    this.array = [];
    this.flag = false;
  }

  StuructureInfo.prototype.end = function () {
    return !this.flag || (this.flag && this.count === 0);
  };

  var bodiesInfo = new StuructureInfo(); // 本文
  var attachInfo = new StuructureInfo(); // 添付ファイル
  var mailInfo = null;

  var parser = new MailParser({streamAttachments: true});

  stream.pipe(parser);

  parser.on("end", function (mail) {
    mailInfo = {
      from: mail.from,
      to: mail.to,
      cc: mail.cc,
      subject: mail.subject,
      messageId: mail.messageId,
      date: (new moment(mail.date)).toDate()
    };
    if (mail.text) {
      parser.emit('attachment', {info: bodiesInfo, buffer: mail.text, contentType: 'text/plain'});
    }
    if (mail.html) {
      parser.emit('attachment', {info: bodiesInfo, buffer: mail.html, contentType: 'text/html'});
    }
    end();
  });

  parser.on("attachment", function (attachment) {
    var info = attachment.info || attachInfo;
    info.flag = true;
    info.count++;
    add(attachment, function (attach) {
      info.array.push(attach);
      info.count--;
      end();
    });
  });

  function add(attachment, callback) {
    var _id = new ObjectID();
    var attach = {
      _id: _id,
      filename: attachment.generatedFileName,
      contentType: attachment.contentType,
      contentId: attachment.contentId,
      path: '/tmp/' + _id.toString() + '.%%%'
    };
    if (attachment.stream) {
      var ws = fs.createWriteStream(attach.path);
      attachment.stream.pipe(ws);
      ws.on('close', function () {
        callback(attach);
      });
    }
    if (attachment.buffer) {
      fs.writeFile(attach.path, attachment.buffer, function (err) {
        callback(attach);
      });
    }
  }

  function end() {
    if (bodiesInfo.end() && attachInfo.end()) {
      mailInfo.attachments = attachInfo.array;
      mailInfo.bodies = bodiesInfo.array;
      done(null, mailInfo);
    }
  }
}

function _delete(mailInfo, done) {
  async.waterfall([
    function (done) {
      mongo.open(function (err, db) {
        done(err, db);
      });
    },
    function (db, done) {
      _delete_files(db, mailInfo.bodies, function (err) {
        done(err, db);
      });
    },
    function (db, done) {
      _delete_files(db, mailInfo.attachments, function (err) {
        done(err, db);
      });
    },
    function (db, done) {
      var collection = db.collection('mails');
      collection.remove({_id: mailInfo._id}, function (err, result) {
        done(err, db);
      });
    }
  ], function (err, db) {
    db.close();
    done(err, mailInfo);
  });
}

function _insert(mailInfo, done) {
  async.waterfall([
    function (done) {
      mongo.open(function (err, db) {
        done(err, db);
      });
    },
    function (db, done) {
      _insert_files(db, mailInfo.bodies, function (err) {
        done(err, db);
      });
    },
    function (db, done) {
      _insert_files(db, mailInfo.attachments, function (err) {
        done(err, db);
      });
    },
    function (db, done) {
      var collection = db.collection('mails');
      collection.insert(mailInfo, function (err, result) {
        done(err, db);
      });
    }
  ], function (err, db) {
    db.close();
    done(err, mailInfo);
  });
}

// path のファイルを MongoDB に取り込む
function _insert_files(db, array, callback) {
  async.each(array, function (file, next) {
    var option = {content_type: file.contentType};
    var gs = new mongodb.GridStore(db, file._id, file.filename, "w", option);
    gs.writeFile(file.path, function (err, result) {
      fs.unlink(file.path);
      delete file.path;
      file.length = result.position;
      next();
    });
  }, function (err) {
    callback(err);
  });
}

// MongoDB から _id のファイルを 削除
function _delete_files(db, array, callback) {
  async.each(array, function (file, next) {
    file.path && fs.unlink(file.path);
    var gs = new mongodb.GridStore(db, file._id, "r");
    gs.unlink(function () {
      next();
    });
  }, function (err) {
    callback(err);
  });
}<commit_msg>すこし、うまくいっている<commit_after>/*
 * Mail
 */

var _ = require('underscore')
  , mongodb = require('mongodb')
  , ObjectID = mongodb.ObjectID
  , fs = require('fs')
  , async = require('async')
  , moment = require('moment')
  , MailParser = require('mailparser').MailParser
  , mongo = require('../db')
  , spawn = require('child_process').spawn
  ;

var GRID_ROOT = 'mails';
var COLLECTION = 'mails';

exports.http_add = function (req, res) {

  // アップロードファイル
  var path = req.files.mail.path;

  add(path, function (err, result) {

    // ファイル削除
    fs.unlink(path);

    var info = {
      subject: result.subject,
      to: result.to
    };
    res.send(info);

  });
};

/**
 *
 * @param stream RFC2822(eml形式) stream
 * @param callback
 */
function add(path, callback) {

  async.waterfall([
    function (done) {
      mongo.open(function (err, db) {
        done(err, db);
      });
    },
    // GridStore登録
    function (db, done) {
      var _id = new ObjectID();
      var option = {root: GRID_ROOT, content_type: 'message/rfc822'};
      var gs = new mongodb.GridStore(db, _id, 'w', option);
      gs.writeFile(path, function (err) {
        done(err, db, _id);
      });
    },
    // GridStore取得
    function (db, _id, done) {
      var option = {root: GRID_ROOT, content_type: 'message/rfc822'};
      var gs = new mongodb.GridStore(db, _id, 'r', option);
      gs.open(function (err, gs) {
        gs._id = _id;
        done(err, db, gs);
      })
    },
    // パース
    function (db, gs, done) {
      _parse(db, gs, function (err, mailInfo) {
        done(err, db, mailInfo);
      });
    },
    // DB登録
    function (db, mailInfo, done) {
      _insert(db, mailInfo, function (err, mailInfo) {
        done(err, db, mailInfo);
      });
    }
  ], function (err, db, mailInfo) {
    db.close();
    callback(err, mailInfo);
  });
}

function _parse(db, gs, done) {

  function StuructureInfo() {
    this.count = 0;
    this.array = [];
    this.flag = false;
  }

  StuructureInfo.prototype.end = function () {
    return !this.flag || (this.flag && this.count === 0);
  };

  var bodiesInfo = new StuructureInfo(); // 本文
  var attachInfo = new StuructureInfo(); // 添付ファイル
  var mailInfo = null;

  var parser = new MailParser({streamAttachments: true});

  gs.seek(0, function (err, store) {
    var stream = store.stream(true);
    stream.pipe(parser);
  });

  parser.on('end', function (mail) {
    mailInfo = {
      from: mail.from,
      to: mail.to,
      cc: mail.cc,
      subject: mail.subject,
      messageId: mail.messageId,
      date: (new moment(mail.date)).toDate(),
      message: {
        _id: gs._id,
        length: gs.length
      }
    };
    if (mail.text) {
      parser.emit('attachment', {info: bodiesInfo, buffer: mail.text, contentType: 'text/plain'});
    }
    if (mail.html) {
      parser.emit('attachment', {info: bodiesInfo, buffer: mail.html, contentType: 'text/html'});
    }
    end();
  });

  parser.on('attachment', function (attachment) {
    var info = attachment.info || attachInfo;
    info.flag = true;
    info.count++;
    add(attachment, function (attach) {
      info.array.push(attach);
      info.count--;
      end();
    });
  });

  function add(attachment, callback) {
    var _id = new ObjectID();
    var attach = {
      _id: _id,
      filename: attachment.generatedFileName,
      contentType: attachment.contentType,
      contentId: attachment.contentId,
      path: '/tmp/' + _id.toString() + '.%%%'
    };
    if (attachment.stream) {
      var ws = fs.createWriteStream(attach.path);
      attachment.stream.pipe(ws);
      ws.on('close', function () {
        callback(attach);
      });
    }
    if (attachment.buffer) {
      fs.writeFile(attach.path, attachment.buffer, function (err) {
        callback(attach);
      });
    }
  }

  function end() {
    if (bodiesInfo.end() && attachInfo.end()) {
      mailInfo.attachments = attachInfo.array;
      mailInfo.bodies = bodiesInfo.array;
      done(null, mailInfo);
    }
  }
}

function _delete(db, mailInfo, done) {
  async.waterfall([
    function (done) {
      _delete_files(db, mailInfo.bodies, function (err) {
        done(err);
      });
    },
    function (done) {
      _delete_files(db, mailInfo.attachments, function (err) {
        done(err);
      });
    },
    function (done) {
      var collection = db.collection(COLLECTION);
      collection.remove({_id: mailInfo._id}, function (err, result) {
        done(err);
      });
    }
  ], function (err) {
    done(err, mailInfo);
  });
}

function _insert(db, mailInfo, done) {
  async.waterfall([
    function (done) {
      _insert_files(db, mailInfo.bodies, function (err) {
        done(err);
      });
    },
    function (done) {
      _insert_files(db, mailInfo.attachments, function (err) {
        done(err);
      });
    },
    function (done) {
      var collection = db.collection(COLLECTION);
      collection.insert(mailInfo, function (err, result) {
        done(err);
      });
    }
  ], function (err) {
    done(err, mailInfo);
  });
}

// path のファイルを MongoDB に取り込む
function _insert_files(db, array, callback) {
  async.each(array, function (file, next) {
    var option = {content_type: file.contentType, root: GRID_ROOT};
    var gs = new mongodb.GridStore(db, file._id, file.filename, 'w', option);
    gs.writeFile(file.path, function (err, result) {
      fs.unlink(file.path);
      delete file.path;
      file.length = result.position;
      next();
    });
  }, function (err) {
    callback(err);
  });
}

// MongoDB から _id のファイルを 削除
function _delete_files(db, array, callback) {
  async.each(array, function (file, next) {
    file.path && fs.unlink(file.path);
    var gs = new mongodb.GridStore(db, file._id, "r");
    gs.unlink(function () {
      next();
    });
  }, function (err) {
    callback(err);
  });
}<|endoftext|>


<commit_before>function ddg_spice_coupon_mountain (api_result) {
  "use strict";

	if (api_result.count < 1) {
    return;
  }

	var header = api_result.keyword
			? api_result.keyword + " (CouponMountain)"
			: "Coupon Search (CouponMountain)",
		keyword = encodeURIComponent(api_result.keyword);

	Spice.add({
		data                     : api_result,
		id               : "coupon_mountain",
		sourceName              : 'CouponMountain',
		sourceUrl               : 'http://www.couponmountain.com/search.php?searchtext='+ keyword,
		header1                  : header,
		view: "Tiles",

		templates         : {
			items                : api_result.coupon,
			item: Spice.coupon_mountain.coupon_mountain,
			detail: Spice.coupon_mountain.coupon_mountain_detail,
			li_width             : 150
		},
		item_callback            : highlight_code
	});

	// highlight coupon code on detail area opening
	function highlight_code () {
		var coupon_code = $("#coupon_code");
		coupon_code.click(function() {
			coupon_code.focus().select();
		}).click();
	}

	// Manually trigger our callback function,
	// item_callback doesn't fire for single result
	if (api_result.count === 1) {
    highlight_code();
  }
}

Handlebars.registerHelper("check_expiry", function(string, options) {
  "use strict";

	if (string && string != "3333-03-03"){
		return options.fn(this);
	} else {
		return;
	}
});

Handlebars.registerHelper("dateString", function(string) {
  "use strict";

	var date = DDG.getDateFromString(string),
		months = [ 'Jan.','Feb.','Mar.','Apr.','May','Jun.','Jul.','Aug.','Sep.','Oct.','Nov.','Dec.'];
	return "Expires " + months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
});

Handlebars.registerHelper("stripExpiry", function(string) {
  "use strict";

	return string.replace(/(offer|good through|expires|ends|valid \w+) .+$/i, "");
});
<commit_msg>coupon_mountain.js: make it work for the new Spice API.<commit_after>function ddg_spice_coupon_mountain (api_result) {
  "use strict";

    if (api_result.count < 1) {
	return;
    }

	var header = api_result.keyword
			? api_result.keyword + " (CouponMountain)"
			: "Coupon Search (CouponMountain)",
		keyword = encodeURIComponent(api_result.keyword);

    console.log(api_result);
	Spice.add({
		data                     : api_result.coupon,
		id               : "coupon_mountain",
		sourceName              : 'CouponMountain',
		sourceUrl               : 'http://www.couponmountain.com/search.php?searchtext='+ keyword,
		templates         : {
		    item: Spice.coupon_mountain.coupon_mountain,
		    detail: Spice.coupon_mountain.coupon_mountain_detail,
		}
	});

	// highlight coupon code on detail area opening
	function highlight_code () {
		var coupon_code = $("#coupon_code");
		coupon_code.click(function() {
			coupon_code.focus().select();
		}).click();
	}

	// Manually trigger our callback function,
	// item_callback doesn't fire for single result
	if (api_result.count === 1) {
    highlight_code();
  }
}

Handlebars.registerHelper("check_expiry", function(string, options) {
  "use strict";

	if (string && string != "3333-03-03"){
		return options.fn(this);
	} else {
		return;
	}
});

Handlebars.registerHelper("dateString", function(string) {
  "use strict";

	var date = DDG.getDateFromString(string),
		months = [ 'Jan.','Feb.','Mar.','Apr.','May','Jun.','Jul.','Aug.','Sep.','Oct.','Nov.','Dec.'];
	return "Expires " + months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
});

Handlebars.registerHelper("stripExpiry", function(string) {
  "use strict";

	return string.replace(/(offer|good through|expires|ends|valid \w+) .+$/i, "");
});
<|endoftext|>


<commit_before>Tools.Menu = function (editor) {

    var signals = editor.signals;
    this.signals = editor.signals;

    //var buttonpanel = new UI.ButtonHelper.createButtonPanel( "menu" );
    //
    ////buttonpanel.addButton( "icon-file", function() { signals.menuButtonClicked.dispatch("file+help"); } );
    //buttonpanel.addButton( "icon-add", function() { signals.menuButtonClicked.dispatch("add"); } );
    ////buttonpanel.addButton( "icon-sound", function() { signals.menuButtonClicked.dispatch("sound"); } );

    var buttonPanels = [];

    var activeButton = "add";

    var backPanel = new UI.ButtonHelper.createButtonPanel("menu");
    backPanel.addButton("icon-back", function () {
        signals.menuButtonClicked.dispatch("back-to-gallery");
    }, 'menu-gallery', 'go back to gallery');

    this.sceneButton = backPanel.dom.children[0];
    setButtonActivationCallback(this.sceneButton, "back-to-gallery");

    buttonPanels.push(backPanel);

    signals.menuButtonClicked.add( function(name) {
        if(name=="back-to-gallery")
        {
            window.history.back();
            //location.href = location.origin+'/play/gallery/main';
        }
    });

    var editPanel = new UI.ButtonHelper.createButtonPanel("menu");
    editPanel.addButton("icon-file", function () {
        signals.menuButtonClicked.dispatch("file+help");
    }, 'menu-file');

    setButtonActivationCallback(editPanel.dom.children[0], "file+help");

    editPanel.addButton("icon-save", function () {
        signals.menuButtonClicked.dispatch("save");
    }, 'menu-save', 'save the scene');

    setButtonActivationCallback(editPanel.dom.children[1], "save");

    buttonPanels.push(editPanel);

    signals.menuButtonClicked.add( function(name) {
        if(name=="save")
        {
            showHide('sceneSave');
        }
    });

    var addPanel = new UI.ButtonHelper.createButtonPanel("menu");
    addPanel.addButton("icon-object active", function () {
        signals.menuButtonClicked.dispatch("add");
    }, 'menu-object', 'open panel to add objects');

    setButtonActivationCallback(addPanel.dom.children[0], "add");

    // todo AFTER MAKESHOP
    //addPanel.addButton("icon-template", function () {
    //    signals.menuButtonClicked.dispatch("add-template");
    //}, 'menu-template', 'open panel to add and edit templates');
    //setButtonActivationCallback(addPanel.dom.children[1], "add-template");

    addPanel.addButton("icon-scene", function () {
        signals.menuButtonClicked.dispatch("scene-properties");
    }, 'menu-scene', 'open scene panel');

    this.sceneButton = addPanel.dom.children[1];
    setButtonActivationCallback(this.sceneButton, "scene-properties");

    buttonPanels.push(addPanel);

    // todo AFTER MAKESHOP
    //var scenePanel = new UI.ButtonHelper.createButtonPanel("menu");
    //scenePanel.addButton("icon-scene", function () {
    //    signals.menuButtonClicked.dispatch("scene-properties");
    //});
    //this.sceneButton = scenePanel.dom.children[0];
    //setButtonActivationCallback(this.sceneButton, "scene-properties");
    //buttonPanels.push(scenePanel);

    function setButtonActivationCallback(button, key) {

        signals.menuButtonClicked.add(function (name) {
            if (name == key) {
                if ($(button).hasClass("active")) {
                    $(button).removeClass("active");
                } else {
                    $(button).addClass("active");
                }
            }
            else {
                $(button).removeClass("active");
            }
        });

    }

    function showHide ( id ) {
        var panel = $('#'+id);
        var inputs = $('.'+id);

        if(panel.css('display') == 'none'){
            panel.css('display','block');

            if( sessionStorage.getItem('scene') !== 'null'){
                inputs.hide();

                var uploadButton = $('.galleryUploadButton');
                uploadButton.text('Saving...').addClass('saving');
                uploadButton.click();

            }else {
                inputs.show();
            }

        }else{
            panel.css('display','none');

            inputs.hide();
        }
    }

    signals.objectSelected.add(function (object) {

        if (object != null) {

            if (!object.isTemplate && !$(this.sceneButton).hasClass("active")) {

                this.signals.menuButtonClicked.dispatch("scene-properties");
            }

        }

    }.bind(this));

    //return buttonpanel;
    return buttonPanels;
};
<commit_msg>back to gallery button test.<commit_after>Tools.Menu = function (editor) {

    var signals = editor.signals;
    this.signals = editor.signals;

    //var buttonpanel = new UI.ButtonHelper.createButtonPanel( "menu" );
    //
    ////buttonpanel.addButton( "icon-file", function() { signals.menuButtonClicked.dispatch("file+help"); } );
    //buttonpanel.addButton( "icon-add", function() { signals.menuButtonClicked.dispatch("add"); } );
    ////buttonpanel.addButton( "icon-sound", function() { signals.menuButtonClicked.dispatch("sound"); } );

    var buttonPanels = [];

    var activeButton = "add";

    var backPanel = new UI.ButtonHelper.createButtonPanel("menu");
    backPanel.addButton("icon-back", function () {
        signals.menuButtonClicked.dispatch("back-to-gallery");
    }, 'menu-gallery', 'go back to gallery');

    this.sceneButton = backPanel.dom.children[0];
    setButtonActivationCallback(this.sceneButton, "back-to-gallery");

    buttonPanels.push(backPanel);

    signals.menuButtonClicked.add( function(name) {
        if(name=="back-to-gallery")
        {
            //window.history.back();
            location.href = location.origin+'/play/gallery/main';
        }
    });

    var editPanel = new UI.ButtonHelper.createButtonPanel("menu");
    editPanel.addButton("icon-file", function () {
        signals.menuButtonClicked.dispatch("file+help");
    }, 'menu-file');

    setButtonActivationCallback(editPanel.dom.children[0], "file+help");

    editPanel.addButton("icon-save", function () {
        signals.menuButtonClicked.dispatch("save");
    }, 'menu-save', 'save the scene');

    setButtonActivationCallback(editPanel.dom.children[1], "save");

    buttonPanels.push(editPanel);

    signals.menuButtonClicked.add( function(name) {
        if(name=="save")
        {
            showHide('sceneSave');
        }
    });

    var addPanel = new UI.ButtonHelper.createButtonPanel("menu");
    addPanel.addButton("icon-object active", function () {
        signals.menuButtonClicked.dispatch("add");
    }, 'menu-object', 'open panel to add objects');

    setButtonActivationCallback(addPanel.dom.children[0], "add");

    // todo AFTER MAKESHOP
    //addPanel.addButton("icon-template", function () {
    //    signals.menuButtonClicked.dispatch("add-template");
    //}, 'menu-template', 'open panel to add and edit templates');
    //setButtonActivationCallback(addPanel.dom.children[1], "add-template");

    addPanel.addButton("icon-scene", function () {
        signals.menuButtonClicked.dispatch("scene-properties");
    }, 'menu-scene', 'open scene panel');

    this.sceneButton = addPanel.dom.children[1];
    setButtonActivationCallback(this.sceneButton, "scene-properties");

    buttonPanels.push(addPanel);

    // todo AFTER MAKESHOP
    //var scenePanel = new UI.ButtonHelper.createButtonPanel("menu");
    //scenePanel.addButton("icon-scene", function () {
    //    signals.menuButtonClicked.dispatch("scene-properties");
    //});
    //this.sceneButton = scenePanel.dom.children[0];
    //setButtonActivationCallback(this.sceneButton, "scene-properties");
    //buttonPanels.push(scenePanel);

    function setButtonActivationCallback(button, key) {

        signals.menuButtonClicked.add(function (name) {
            if (name == key) {
                if ($(button).hasClass("active")) {
                    $(button).removeClass("active");
                } else {
                    $(button).addClass("active");
                }
            }
            else {
                $(button).removeClass("active");
            }
        });

    }

    function showHide ( id ) {
        var panel = $('#'+id);
        var inputs = $('.'+id);

        if(panel.css('display') == 'none'){
            panel.css('display','block');

            if( sessionStorage.getItem('scene') !== 'null'){
                inputs.hide();

                var uploadButton = $('.galleryUploadButton');
                uploadButton.text('Saving...').addClass('saving');
                uploadButton.click();

            }else {
                inputs.show();
            }

        }else{
            panel.css('display','none');

            inputs.hide();
        }
    }

    signals.objectSelected.add(function (object) {

        if (object != null) {

            if (!object.isTemplate && !$(this.sceneButton).hasClass("active")) {

                this.signals.menuButtonClicked.dispatch("scene-properties");
            }

        }

    }.bind(this));

    //return buttonpanel;
    return buttonPanels;
};
<|endoftext|>


<commit_before>$( function() {
	$.widget( "vui.accordion", {

		options: {},

		_create: function() {

			var me = this;

			var $accordion = $( this.element );

			var displayMode = $accordion.attr( 'data-display-mode' );
			if ( displayMode !== 'stacked' ) {
				displayMode = 'accordion';
			}

			this.option( 'displayMode', displayMode );

			$accordion
				.attr( 'role', 'tablist' )
				.attr(
					'aria-multiselectable',
					displayMode !== 'accordion'
				);

			$.each(
				$accordion.find( '.vui-accordion-header' ),
				function( index, headerNode ) {
					me._initializePanel(
						$accordion,
						$( headerNode ),
						( index === 0 )
					);
				}
			);

		},

		_setOption: function( key, value ) {
			if ( key === 'displayMode' ) {
				if ( value === 'stacked' ) {
					value = 'stacked';
				} else {
					value = 'accordion';
				}
				$( this.element ).attr( 'data-display-mode', value );
			}
			$.Widget.prototype._setOption.apply( this, arguments );
		},

		collapseAll: function() {

			var me = this;

			$.each(
				$( this.element ).find( '.vui-accordion-header' ),
				function( index, headerNode ) {
					me._collapsePanel( $( headerNode ) );
				}
			);

		},

		_collapsePanel: function( $header ) {

			if ( !$header.hasClass( 'vui-accordion-panel-expanded' ) ) {
				return;
			}

			$( this.element ).trigger(
				'collapsePanel', {
					header: $header.get(0)
				}
			);

			$header.attr( 'aria-expanded', 'false' )
				.removeClass( 'vui-accordion-panel-expanded' );

			this._updateIcon( $header, false );

			var contentId = $header.attr( 'data-content-id' );

			var contentNode = document.getElementById( contentId );
			if ( contentNode === null ) {
				return;
			}

			$( contentNode )
				.attr( 'aria-hidden', 'true' )
				.animate( {
					height: [ 'hide', 'swing' ]
				}, 250 );

		},

		_expandPanel: function( $header ) {

			var $accordion = $( this.element );

			if ( this.option( 'displayMode' ) === 'accordion' ) {
				$accordion.accordion( 'collapseAll' );
			}

			$accordion.trigger(
				'expandPanel', {
					header: $header.get( 0 ),
					isFirstExpand: !$header.data( 'hasExpanded' )
				}
			);

			$header.attr( 'aria-expanded', 'true' )
				.addClass( 'vui-accordion-panel-expanded' )
				.data( 'hasExpanded', true );

			this._updateIcon( $header, true );

			var contentId = $header.attr( 'data-content-id' );

			var contentNode = document.getElementById( contentId );
			if ( contentNode === null ) {
				return;
			}

			$( contentNode )
				.attr( 'aria-hidden', 'false' )
				.animate( {
					height: [ 'show', 'swing' ]
				}, 250 );

		},

		_initializePanel: function( $accordion, $header, isFocusable ) {

			var me = this;

			var $content = me._tryGetContent( $header );
			if ( $content === null ) {
				return;
			}

			var contentId = $header.attr( 'data-content-id' );
			var contentNode = $content.get( 0 );

			var isExpanded = ( $header.attr( 'data-expanded' ) === 'true' );
			var labelledById = $header.attr( 'data-content-labelledby' );

			var $headerContent = $header.find( '.vui-accordion-header-content:first-child' );

			var isHeaderInteractive = ( $headerContent.length !== 0 );

			var togglePanel = function() {
				if ( $header.hasClass( 'vui-accordion-panel-expanded' ) ) {
					me._collapsePanel( $header );
				} else {
					me._expandPanel( $header );
				}
			};

			var isEnabled = !$content.is( ':empty' );

			if ( isHeaderInteractive ) {
				var toggle = document.createElement( 'div' );
				toggle.className = 'vui-accordion-toggle';

				var toggleIcon = toggle.appendChild( document.createElement( 'div' ) );
				if ( isExpanded ) {
					toggleIcon.className = 'vui-accordion-toggle-icon vui-icon-expanded';
				} else {
					toggleIcon.className = 'vui-accordion-toggle-icon vui-icon-collapsed';
				}

				$header.prepend( toggle );
			}

			$header
				.attr( 'role', 'tab' )
				.attr( 'aria-controls', contentId )
				.attr( 'aria-expanded', isExpanded )
				.attr( 'aria-selected', isFocusable ? 'true' : 'false' )
				.attr( 'tabindex', isFocusable ? '0' : '-1' )
				.css( 'padding', isHeaderInteractive ? '0' : 'auto' )
				.data( 'hasExpanded', isExpanded )
				.removeAttr( 'data-expanded' )
				.click( function( e ) {

					if ( !isEnabled ) {
						return;
					}

					var eventTarget = e.target;

					while ( eventTarget !== $header.get( 0 ) && eventTarget !== null ) {

						if ( eventTarget === $headerContent.get( 0 ) || $( eventTarget ).is( ':focusable' ) ) {
							return;
						}

						eventTarget = eventTarget.parentNode;
					}

					togglePanel();

				} ).focus( function() {

					$header.addClass( 'vui-accordion-header-active' );

				} ).blur( function() {

					$header.removeClass( 'vui-accordion-header-active' );

				} ).keydown( function( e ) {

					// prevent scrolling page when arrow keys, home, or end are pressed
					if ( e.keyCode >=35 && e.keyCode <=40 ) {
						e.preventDefault();
						return false;
					}

					return true;

				} ).keyup( function( e ) {

					if ( e.keyCode === 13 || e.keyCode === 32 ) {
						// enter/space
						if ( !isEnabled ) {
							return;
						}
						togglePanel();
					} else if ( e.keyCode === 39 || e.keyCode === 40 ) {
						// down/right
						me._focusPanel( $header, me._tryGetNextPanel( $header ) );
					} else if ( e.keyCode === 37 || e.keyCode === 38 ) {
						// up/left
						me._focusPanel( $header, me._tryGetPreviousPanel( $header ) );
					} else if ( e.keyCode === 35 ) {
						// end - last panel
						me._focusPanel( $header, me._getLastPanelHeader() );
					} else if ( e.keyCode === 36 ) {
						// home - first panel
						me._focusPanel( $header, me._getFirstPanelHeader() );
					}

				} );

			if ( !isEnabled ) {
				$header
					.attr( 'aria-disabled', 'true' )
					.addClass( 'vui-accordion-header-disabled' );
			}

			$content
				.attr( 'role', 'tabpanel' )
				.attr( 'aria-labelledby', labelledById )
				.attr( 'aria-hidden', 'true' );

			if ( isExpanded ) {

				if ( this.option( 'displayMode' ) === 'accordion' ) {
					$.each(
						$accordion.find( '.vui-accordion-panel-expanded' ),
						function( index, panelNode ) {
							me._collapsePanel( $( panelNode ) );
						}
					);
				}

				$header.addClass( 'vui-accordion-panel-expanded' );

				setTimeout( function() {
					$accordion.trigger(
						'expandPanel', {
							header: $header.get( 0 ),
							isFirstExpand: true
						}
					);
				}, 0 );

				$content
					.attr( 'aria-hidden', 'false' )
					.show();

			}

		},

		_focusPanel: function( $currentHeader, $header ) {

			if ( $header === null ) {
				return;
			}

			$currentHeader
				.attr( 'tabindex', '-1' )
				.attr( 'aria-selected', 'false' );

			$header
				.attr( 'tabindex', '0' )
				.attr( 'aria-selected', 'true' )
				.focus();

		},

		_getFirstPanelHeader: function() {
			var $headers = $( this.element )
				.find( '.vui-accordion-header');
			return $( $headers[ 0 ] );
		},

		_getLastPanelHeader: function() {
			var $headers = $( this.element )
				.find( '.vui-accordion-header');
			return $( $headers[ $headers.length - 1 ] );
		},

		_tryGetContent: function( $header ) {

			var contentId = $header.attr( 'data-content-id' );

			if ( contentId !== undefined ) {
				var contentNode = document.getElementById( contentId );
				if ( contentNode !== null ) {
					return $( contentNode );
				} else {
					return null;
				}
			}

			var $nextElement = $header.next( '.vui-accordion-content' );
			if ( $nextElement.length !== 0 ) {

				contentId = $nextElement.attr( 'id' );
				if ( contentId === undefined ) {
					$nextElement.uniqueId();
					contentId = $nextElement.attr( 'id' );
				}

				$header.attr( 'data-content-id', contentId );

				return $nextElement;

			}

			return null;

		},

		_tryGetPreviousPanel: function( $header ) {

			var $previousElement = $header.prev();

			if ( $previousElement.length === 0 ) {
				return this._getLastPanelHeader();
			} else if ( $previousElement.hasClass( 'vui-accordion-header' ) ) {
				return $previousElement;
			} else {
				return this._tryGetPreviousPanel( $previousElement );
			}

		},

		_tryGetNextPanel: function( $header ) {

			var $nextElement = $header.next();

			if ( $nextElement.length === 0 ) {
				return this._getFirstPanelHeader();
			} else if ( $nextElement.hasClass( 'vui-accordion-header' ) ) {
				return $nextElement;
			} else {
				return this._tryGetNextPanel( $nextElement );
			}

		},

		_updateIcon: function( $header, isExpanded ) {

			var toggleIcon = $header.find( '.vui-accordion-toggle-icon' );
			if ( toggleIcon.length > 0 ) {
				if ( isExpanded ) {
					toggleIcon.addClass( 'vui-icon-expanded' );
					toggleIcon.removeClass( 'vui-icon-collapsed' );
				} else {
					toggleIcon.addClass( 'vui-icon-collapsed' );
					toggleIcon.removeClass( 'vui-icon-expanded' );
				}
			}

		}

	} );

	vui.addClassInitializer(
			'vui-accordion',
			function( node ) {
				$( node ).accordion();
			}
		);

} );<commit_msg>FB#3618 - Cancelling default behaviour for [space] key so that page does not scroll when using [space] key to expand/collapse Accordion items.<commit_after>$( function() {
	$.widget( "vui.accordion", {

		options: {},

		_create: function() {

			var me = this;

			var $accordion = $( this.element );

			var displayMode = $accordion.attr( 'data-display-mode' );
			if ( displayMode !== 'stacked' ) {
				displayMode = 'accordion';
			}

			this.option( 'displayMode', displayMode );

			$accordion
				.attr( 'role', 'tablist' )
				.attr(
					'aria-multiselectable',
					displayMode !== 'accordion'
				);

			$.each(
				$accordion.find( '.vui-accordion-header' ),
				function( index, headerNode ) {
					me._initializePanel(
						$accordion,
						$( headerNode ),
						( index === 0 )
					);
				}
			);

		},

		_setOption: function( key, value ) {
			if ( key === 'displayMode' ) {
				if ( value === 'stacked' ) {
					value = 'stacked';
				} else {
					value = 'accordion';
				}
				$( this.element ).attr( 'data-display-mode', value );
			}
			$.Widget.prototype._setOption.apply( this, arguments );
		},

		collapseAll: function() {

			var me = this;

			$.each(
				$( this.element ).find( '.vui-accordion-header' ),
				function( index, headerNode ) {
					me._collapsePanel( $( headerNode ) );
				}
			);

		},

		_collapsePanel: function( $header ) {

			if ( !$header.hasClass( 'vui-accordion-panel-expanded' ) ) {
				return;
			}

			$( this.element ).trigger(
				'collapsePanel', {
					header: $header.get(0)
				}
			);

			$header.attr( 'aria-expanded', 'false' )
				.removeClass( 'vui-accordion-panel-expanded' );

			this._updateIcon( $header, false );

			var contentId = $header.attr( 'data-content-id' );

			var contentNode = document.getElementById( contentId );
			if ( contentNode === null ) {
				return;
			}

			$( contentNode )
				.attr( 'aria-hidden', 'true' )
				.animate( {
					height: [ 'hide', 'swing' ]
				}, 250 );

		},

		_expandPanel: function( $header ) {

			var $accordion = $( this.element );

			if ( this.option( 'displayMode' ) === 'accordion' ) {
				$accordion.accordion( 'collapseAll' );
			}

			$accordion.trigger(
				'expandPanel', {
					header: $header.get( 0 ),
					isFirstExpand: !$header.data( 'hasExpanded' )
				}
			);

			$header.attr( 'aria-expanded', 'true' )
				.addClass( 'vui-accordion-panel-expanded' )
				.data( 'hasExpanded', true );

			this._updateIcon( $header, true );

			var contentId = $header.attr( 'data-content-id' );

			var contentNode = document.getElementById( contentId );
			if ( contentNode === null ) {
				return;
			}

			$( contentNode )
				.attr( 'aria-hidden', 'false' )
				.animate( {
					height: [ 'show', 'swing' ]
				}, 250 );

		},

		_initializePanel: function( $accordion, $header, isFocusable ) {

			var me = this;

			var $content = me._tryGetContent( $header );
			if ( $content === null ) {
				return;
			}

			var contentId = $header.attr( 'data-content-id' );
			var contentNode = $content.get( 0 );

			var isExpanded = ( $header.attr( 'data-expanded' ) === 'true' );
			var labelledById = $header.attr( 'data-content-labelledby' );

			var $headerContent = $header.find( '.vui-accordion-header-content:first-child' );

			var isHeaderInteractive = ( $headerContent.length !== 0 );

			var togglePanel = function() {
				if ( $header.hasClass( 'vui-accordion-panel-expanded' ) ) {
					me._collapsePanel( $header );
				} else {
					me._expandPanel( $header );
				}
			};

			var isEnabled = !$content.is( ':empty' );

			if ( isHeaderInteractive ) {
				var toggle = document.createElement( 'div' );
				toggle.className = 'vui-accordion-toggle';

				var toggleIcon = toggle.appendChild( document.createElement( 'div' ) );
				if ( isExpanded ) {
					toggleIcon.className = 'vui-accordion-toggle-icon vui-icon-expanded';
				} else {
					toggleIcon.className = 'vui-accordion-toggle-icon vui-icon-collapsed';
				}

				$header.prepend( toggle );
			}

			$header
				.attr( 'role', 'tab' )
				.attr( 'aria-controls', contentId )
				.attr( 'aria-expanded', isExpanded )
				.attr( 'aria-selected', isFocusable ? 'true' : 'false' )
				.attr( 'tabindex', isFocusable ? '0' : '-1' )
				.css( 'padding', isHeaderInteractive ? '0' : 'auto' )
				.data( 'hasExpanded', isExpanded )
				.removeAttr( 'data-expanded' )
				.click( function( e ) {

					if ( !isEnabled ) {
						return;
					}

					var eventTarget = e.target;

					while ( eventTarget !== $header.get( 0 ) && eventTarget !== null ) {

						if ( eventTarget === $headerContent.get( 0 ) || $( eventTarget ).is( ':focusable' ) ) {
							return;
						}

						eventTarget = eventTarget.parentNode;
					}

					togglePanel();

				} ).focus( function() {

					$header.addClass( 'vui-accordion-header-active' );

				} ).blur( function() {

					$header.removeClass( 'vui-accordion-header-active' );

				} ).keydown( function( e ) {

					// prevent scrolling page when arrow keys, home, or end are pressed
					if ( e.keyCode >=35 && e.keyCode <=40 || e.keyCode==32 ) {
						e.preventDefault();
						return false;
					}

					return true;

				} ).keyup( function( e ) {

					if ( e.keyCode === 13 || e.keyCode === 32 ) {
						// enter/space
						if ( !isEnabled ) {
							return;
						}
						togglePanel();
					} else if ( e.keyCode === 39 || e.keyCode === 40 ) {
						// down/right
						me._focusPanel( $header, me._tryGetNextPanel( $header ) );
					} else if ( e.keyCode === 37 || e.keyCode === 38 ) {
						// up/left
						me._focusPanel( $header, me._tryGetPreviousPanel( $header ) );
					} else if ( e.keyCode === 35 ) {
						// end - last panel
						me._focusPanel( $header, me._getLastPanelHeader() );
					} else if ( e.keyCode === 36 ) {
						// home - first panel
						me._focusPanel( $header, me._getFirstPanelHeader() );
					}

				} );

			if ( !isEnabled ) {
				$header
					.attr( 'aria-disabled', 'true' )
					.addClass( 'vui-accordion-header-disabled' );
			}

			$content
				.attr( 'role', 'tabpanel' )
				.attr( 'aria-labelledby', labelledById )
				.attr( 'aria-hidden', 'true' );

			if ( isExpanded ) {

				if ( this.option( 'displayMode' ) === 'accordion' ) {
					$.each(
						$accordion.find( '.vui-accordion-panel-expanded' ),
						function( index, panelNode ) {
							me._collapsePanel( $( panelNode ) );
						}
					);
				}

				$header.addClass( 'vui-accordion-panel-expanded' );

				setTimeout( function() {
					$accordion.trigger(
						'expandPanel', {
							header: $header.get( 0 ),
							isFirstExpand: true
						}
					);
				}, 0 );

				$content
					.attr( 'aria-hidden', 'false' )
					.show();

			}

		},

		_focusPanel: function( $currentHeader, $header ) {

			if ( $header === null ) {
				return;
			}

			$currentHeader
				.attr( 'tabindex', '-1' )
				.attr( 'aria-selected', 'false' );

			$header
				.attr( 'tabindex', '0' )
				.attr( 'aria-selected', 'true' )
				.focus();

		},

		_getFirstPanelHeader: function() {
			var $headers = $( this.element )
				.find( '.vui-accordion-header');
			return $( $headers[ 0 ] );
		},

		_getLastPanelHeader: function() {
			var $headers = $( this.element )
				.find( '.vui-accordion-header');
			return $( $headers[ $headers.length - 1 ] );
		},

		_tryGetContent: function( $header ) {

			var contentId = $header.attr( 'data-content-id' );

			if ( contentId !== undefined ) {
				var contentNode = document.getElementById( contentId );
				if ( contentNode !== null ) {
					return $( contentNode );
				} else {
					return null;
				}
			}

			var $nextElement = $header.next( '.vui-accordion-content' );
			if ( $nextElement.length !== 0 ) {

				contentId = $nextElement.attr( 'id' );
				if ( contentId === undefined ) {
					$nextElement.uniqueId();
					contentId = $nextElement.attr( 'id' );
				}

				$header.attr( 'data-content-id', contentId );

				return $nextElement;

			}

			return null;

		},

		_tryGetPreviousPanel: function( $header ) {

			var $previousElement = $header.prev();

			if ( $previousElement.length === 0 ) {
				return this._getLastPanelHeader();
			} else if ( $previousElement.hasClass( 'vui-accordion-header' ) ) {
				return $previousElement;
			} else {
				return this._tryGetPreviousPanel( $previousElement );
			}

		},

		_tryGetNextPanel: function( $header ) {

			var $nextElement = $header.next();

			if ( $nextElement.length === 0 ) {
				return this._getFirstPanelHeader();
			} else if ( $nextElement.hasClass( 'vui-accordion-header' ) ) {
				return $nextElement;
			} else {
				return this._tryGetNextPanel( $nextElement );
			}

		},

		_updateIcon: function( $header, isExpanded ) {

			var toggleIcon = $header.find( '.vui-accordion-toggle-icon' );
			if ( toggleIcon.length > 0 ) {
				if ( isExpanded ) {
					toggleIcon.addClass( 'vui-icon-expanded' );
					toggleIcon.removeClass( 'vui-icon-collapsed' );
				} else {
					toggleIcon.addClass( 'vui-icon-collapsed' );
					toggleIcon.removeClass( 'vui-icon-expanded' );
				}
			}

		}

	} );

	vui.addClassInitializer(
			'vui-accordion',
			function( node ) {
				$( node ).accordion();
			}
		);

} );<|endoftext|>