<commit_before>(function( jQuery ) {

var // Static reference to slice
	sliceDeferred = [].slice;

jQuery.extend({

	Deferred: function( func ) {
		var tuples = [
				// action, add listener, listener list, final state
				[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
				[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
				[ "notify", "progress", jQuery.Callbacks("memory") ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				then: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;
					return jQuery.Deferred(function( newDefer ) {
						jQuery.each( tuples, function( i, tuple ) {
							var action = tuple[ 0 ],
								fn = fns[ i ];
							// deferred[ done | fail | progress ] for forwarding actions to newDefer
							deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
								function() {
									var returned = fn.apply( this, arguments );
									if ( returned && jQuery.isFunction( returned.promise ) ) {
										returned.promise()
											.done( newDefer.resolve )
											.fail( newDefer.reject )
											.progress( newDefer.notify );
									} else {
										newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
									}
								} :
								newDefer[ action ]
							);
						});
						fns = null;
					}).promise();
				},
				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return typeof obj === "object" ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Keep pipe for back-compat
		promise.pipe = promise.then;

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 3 ];

			// promise[ done | fail | progress ] = list.add
			promise[ tuple[1] ] = list.add;

			// Handle state
			if ( i < 2 ) {
				list.add(function() {
					// state = [ resolved | rejected ]
					state = stateString;

				// [ reject_list | resolve_list ].disable; progress_list.lock
				}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );

				// [ isResolved | isRejected ] = [ resolve_list | reject_list ].fired
				promise[ "isR" + stateString.substr( 1 ) ] = list.fired;
			}

			// deferred[ resolve | reject | notify ] = list.fire
			deferred[ tuple[0] ] = list.fire;
			deferred[ tuple[0] + "With" ] = list.fireWith;
		});

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( subordinate /* , ..., subordinateN */ ) {
		var i = 0,
			resolveValues = sliceDeferred.call( arguments ),
			length = resolveValues.length,
			progressValues = new Array( length ),

			// the count of uncompleted subordinates
			remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,

			// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
			promise = deferred.promise(),

			// Update function for both resolve and progress values
			updateFunc = function( i, arr ) {
				return function( value ) {
					arr[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments ) : value;
					if( arr === progressValues ) {
						deferred.notifyWith( promise, arr );
					} else if ( !( --remaining ) ) {
						deferred.resolveWith( promise, arr );
					}
				};
			};

		// add listeners to Deferred subordinates; treat others as resolved
		if ( length > 1 ) {
			for ( ; i < length; i++ ) {
				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
					resolveValues[ i ].promise()
						.done( updateFunc( i, resolveValues ) )
						.fail( deferred.reject )
						.progress( updateFunc( i, progressValues ) );
				} else {
					--remaining;
				}
			}
		}

		// if we're not waiting on anything, resolve the master
		if ( !remaining ) {
			deferred.resolveWith( deferred, resolveValues );
		}

		return promise;
	}
});

})( jQuery );
<commit_msg>Gains 1 more byte min/gz and reminds that isResolved and isRejected are deprecated in the comments.<commit_after>(function( jQuery ) {

var // Static reference to slice
	sliceDeferred = [].slice;

jQuery.extend({

	Deferred: function( func ) {
		var tuples = [
				// action, add listener, listener list, final state
				[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
				[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
				[ "notify", "progress", jQuery.Callbacks("memory") ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				then: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;
					return jQuery.Deferred(function( newDefer ) {
						jQuery.each( tuples, function( i, tuple ) {
							var action = tuple[ 0 ],
								fn = fns[ i ];
							// deferred[ done | fail | progress ] for forwarding actions to newDefer
							deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
								function() {
									var returned = fn.apply( this, arguments );
									if ( returned && jQuery.isFunction( returned.promise ) ) {
										returned.promise()
											.done( newDefer.resolve )
											.fail( newDefer.reject )
											.progress( newDefer.notify );
									} else {
										newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
									}
								} :
								newDefer[ action ]
							);
						});
						fns = null;
					}).promise();
				},
				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return typeof obj === "object" ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Keep pipe for back-compat
		promise.pipe = promise.then;

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 3 ];

			// promise[ done | fail | progress ] = list.add
			promise[ tuple[1] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add(function() {
					// state = [ resolved | rejected ]
					state = stateString;

				// [ reject_list | resolve_list ].disable; progress_list.lock
				}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );

				// <DEPRECATED> [ isResolved | isRejected ] = [ resolve_list | reject_list ].fired
				promise[ "isR" + stateString.substr( 1 ) ] = list.fired;
			}

			// deferred[ resolve | reject | notify ] = list.fire
			deferred[ tuple[0] ] = list.fire;
			deferred[ tuple[0] + "With" ] = list.fireWith;
		});

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( subordinate /* , ..., subordinateN */ ) {
		var i = 0,
			resolveValues = sliceDeferred.call( arguments ),
			length = resolveValues.length,
			progressValues = new Array( length ),

			// the count of uncompleted subordinates
			remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,

			// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
			promise = deferred.promise(),

			// Update function for both resolve and progress values
			updateFunc = function( i, arr ) {
				return function( value ) {
					arr[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments ) : value;
					if( arr === progressValues ) {
						deferred.notifyWith( promise, arr );
					} else if ( !( --remaining ) ) {
						deferred.resolveWith( promise, arr );
					}
				};
			};

		// add listeners to Deferred subordinates; treat others as resolved
		if ( length > 1 ) {
			for ( ; i < length; i++ ) {
				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
					resolveValues[ i ].promise()
						.done( updateFunc( i, resolveValues ) )
						.fail( deferred.reject )
						.progress( updateFunc( i, progressValues ) );
				} else {
					--remaining;
				}
			}
		}

		// if we're not waiting on anything, resolve the master
		if ( !remaining ) {
			deferred.resolveWith( deferred, resolveValues );
		}

		return promise;
	}
});

})( jQuery );
<|endoftext|>


<commit_before>/* ============================================================ *\
    SETUP
\* ============================================================ */

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

// Gulp
var gulp   = require('gulp');
var argv   = require('yargs').argv;
var runSeq = require('run-sequence');

// Tasks
var del = require('del');

// Node
var path = require('path');
var fs   = require('fs');

// Config
var config    = require('./_config/project.json');
var creds     = require('./_config/creds.json');
var cartridge = JSON.parse(fs.readFileSync('./.cartridgerc', 'utf8'));

// Prep the cartridge settings object
var cartridgeSettings           = {};
cartridgeSettings.tasks         = {};
cartridgeSettings.tasks.default = [];
cartridgeSettings.tasks.watch   = [];
cartridgeSettings.cleanPaths    = [];

config.isprod = argv.prod ? true : false;

/* ============================================================ *\
	TASK MODULES
\* ============================================================ */

cartridge.modules.forEach(function(module) {
	require(path.resolve('node_modules/' + module.task))(config, cartridgeSettings, creds);
});

gulp.task('clean', function () {
	return del(cartridgeSettings.cleanPaths);
});

/* ============================================================ *\
	MAIN TASKS
\* ============================================================ */

gulp.task('watch', cartridgeSettings.tasks.watch);

// Task for local dev
gulp.task('default', cartridgeSettings.tasks.default.concat(['watch']));

// Task for team city
gulp.task('build', function (cb) {
	return runSeq(['clean'], cartridgeSettings.tasks.default, cb);
});
<commit_msg>Spacing issue in gulpfile<commit_after>/* ============================================================ *\
	SETUP
\* ============================================================ */

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

// Gulp
var gulp   = require('gulp');
var argv   = require('yargs').argv;
var runSeq = require('run-sequence');

// Tasks
var del = require('del');

// Node
var path = require('path');
var fs   = require('fs');

// Config
var config    = require('./_config/project.json');
var creds     = require('./_config/creds.json');
var cartridge = JSON.parse(fs.readFileSync('./.cartridgerc', 'utf8'));

// Prep the cartridge settings object
var cartridgeSettings           = {};
cartridgeSettings.tasks         = {};
cartridgeSettings.tasks.default = [];
cartridgeSettings.tasks.watch   = [];
cartridgeSettings.cleanPaths    = [];

config.isprod = argv.prod ? true : false;

/* ============================================================ *\
	TASK MODULES
\* ============================================================ */

cartridge.modules.forEach(function(module) {
	require(path.resolve('node_modules/' + module.task))(config, cartridgeSettings, creds);
});

gulp.task('clean', function () {
	return del(cartridgeSettings.cleanPaths);
});

/* ============================================================ *\
	MAIN TASKS
\* ============================================================ */

gulp.task('watch', cartridgeSettings.tasks.watch);

// Task for local dev
gulp.task('default', cartridgeSettings.tasks.default.concat(['watch']));

// Task for team city
gulp.task('build', function (cb) {
	return runSeq(['clean'], cartridgeSettings.tasks.default, cb);
});
<|endoftext|>


<commit_before>import ko from 'knockout';
import jQuery from 'jquery';
import hasher from 'hasher';
import {currentRoute} from '../../shared/router';

export default class ViewSwitch {
  constructor() {
    this.component = ko.observable();
    this._routeChangedSubscription = currentRoute.subscribe(this._onRouteChanged, this);
    jQuery(document).ready(hasher.init.bind(hasher));
  }

  dispose() {
    this._routeChangedSubscription.dispose();
  }

  _onRouteChanged(route) {
    var routeInfo = route.$route;

    // Clear current view
    this.component(undefined);

    if (routeInfo) {
      var componentName = 'c-' + (+new Date());

      if (!routeInfo.$component) {
        routeInfo.$component = ko.utils.extend({}, routeInfo.component);
        routeInfo.$component.name = componentName;

        if (typeof routeInfo.component === 'string') {
          ko.components.register(componentName, { component: routeInfo.component });
        }
        else {
          ko.components.register(componentName, routeInfo.component);
        }
      }
      else {
        componentName = routeInfo.$component.name;
      }
      this.component({ name: componentName, params: route.params });
    }
  }
}
<commit_msg>refactor(components/view-switch): simplify custom data attached to route information<commit_after>import ko from 'knockout';
import jQuery from 'jquery';
import hasher from 'hasher';
import {currentRoute} from '../../shared/router';

export default class ViewSwitch {
  constructor() {
    this.component = ko.observable();
    this._routeChangedSubscription = currentRoute.subscribe(this._onRouteChanged, this);
    jQuery(document).ready(hasher.init.bind(hasher));
  }

  dispose() {
    this._routeChangedSubscription.dispose();
  }

  _onRouteChanged(route) {
    var routeInfo = route.$route;

    // Clear current view
    this.component(undefined);

    if (routeInfo) {
      var componentName = 'c-' + (+new Date());

      if (!routeInfo.$component) {
        routeInfo.$component = { name: componentName };

        if (typeof routeInfo.component === 'string') {
          ko.components.register(componentName, { component: routeInfo.component });
        }
        else {
          ko.components.register(componentName, routeInfo.component);
        }
      }
      else {
        componentName = routeInfo.$component.name;
      }
      this.component({ name: componentName, params: route.params });
    }
  }
}
<|endoftext|>


<commit_before>var gulp = require('gulp');

// Now the rest of the dependencies
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
var del = require('del');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var plumber = require('gulp-plumber');
var cssPrefixed = require('gulp-autoprefixer');
var server = require('gulp-server-livereload');
var wiredep = require('wiredep');
var changed = require('gulp-changed');
var fs = require('fs');

// constants goes here
const WORDPRESS_THEME = 'smash-norge';

// Clean build folder
gulp.task('clean', ['clean:html', 'clean:js', 'clean:css']);

gulp.task('clean:html', function (cb) {
    del(['dist/*.html'], cb);
});

gulp.task('clean:js', function (cb) {
    del(['dist/*.js'], cb);
});

gulp.task('clean:css', function (cb) {
    del(['dist/*.css'], cb);
});

// Handle frontend JS build
gulp.task('script', function () {
    return gulp.src('js/*.js')
        .pipe(plumber())
        .pipe(jshint())
        .pipe(uglify())
        .pipe(concat('scripts.min.js'))
        .pipe(gulp.dest('dist/assets/'));

});

// Handle CSS build
gulp.task('style', function () {
    return gulp.src('css/*.css')
        .pipe(plumber())
        .pipe(cssPrefixed({browsers: ['last 2 versions'], cascade: false}))
        .pipe(minifyCss())
        .pipe(concat('styles.min.css'))
        .pipe(gulp.dest('dist/assets/'));
});

// Bower tasks
gulp.task('bower', ['bower:wire', 'bower:copy']);

gulp.task('bower:wire', function () {
    wiredep({src: './*.html', dest: '/*.html'});
});

gulp.task('images', function () {
    return gulp.src('img/**')
        .pipe(changed('dist/img'))
        .pipe(gulp.dest('dist/img'));
});

// Development server @ localhost:8000
gulp.task('server', function () {
    return gulp.src('dist')
        .pipe(server({
            livereload: false,
            open: true,
            log: 'debug'
        }));
});

// Prompt
gulp.task('prompt', function () {
    return fs.readFile('prompt.txt', 'utf8', function (err, data) {
        if (err) {
            throw err;
        }
        console.log(data);
    });
});

// Wordpress tasks
gulp.task('wordpress:theme', ['build'], function() {
    return gulp.src('dist/assets/**')
        .pipe(gulp.dest('theme/assets'));
});

gulp.task('wordpress', ['wordpress:theme'], function () {
    return gulp.src('theme/**')
        .pipe(gulp.dest('wordpress/wp-content/themes/' + WORDPRESS_THEME));
});

// Watch for updates in files to recompile assets
gulp.task('watch', function () {
    gulp.watch('js/*.js', ['script']);
    gulp.watch('css/*.css', ['style']);
    gulp.watch('bower.json', ['bower']);
    gulp.watch('*.html', ['bower:wire']);
    gulp.watch('bower.json', ['bower:copy']);
});

gulp.task('build', ['clean', 'script', 'style', 'bower', 'images']);
gulp.task('serve', ['build', 'watch', 'server']);
gulp.task('smash', ['prompt', 'serve']);
gulp.task('default', ['build']);
<commit_msg>Change build to respect new placement of files<commit_after>var gulp = require('gulp');

// Now the rest of the dependencies
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
var del = require('del');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var plumber = require('gulp-plumber');
var cssPrefixed = require('gulp-autoprefixer');
var server = require('gulp-server-livereload');
var wiredep = require('wiredep');
var changed = require('gulp-changed');
var fs = require('fs');

// constants goes here
const WORDPRESS_THEME = 'smash-norge';

// Clean build folder
gulp.task('clean', function(cb) {
    del(['dist/**', '!dist/**.[png|jpg]'], cb);
});

// Handle frontend JS build
gulp.task('script', ['clean'], function () {
    return gulp.src('src/js/*.js')
        .pipe(plumber())
        .pipe(jshint())
        .pipe(uglify())
        .pipe(concat('scripts.min.js'))
        .pipe(gulp.dest('dist/assets/'));

});

// Handle CSS build
gulp.task('style', ['clean'], function () {
    return gulp.src('src/css/*.css')
        .pipe(plumber())
        .pipe(cssPrefixed({browsers: ['last 2 versions'], cascade: false}))
        .pipe(minifyCss())
        .pipe(concat('styles.min.css'))
        .pipe(gulp.dest('dist/assets/'));
});

// Bower tasks
gulp.task('bower', ['bower:css', 'bower:js'], function() {
    console.log('bower tasks completed');
});

gulp.task('bower:js', ['clean'], function () {
    return gulp.src('bower_components/**.min.js')
        .pipe(changed('vendor.min.js'))
        .pipe(concat('vendor.min.js'))
        .pipe(gulp.dest('dist/assets/'));
});

gulp.task('bower:css', ['clean'], function () {
    return gulp.src('bower_components/**.min.css')
        .pipe(changed('vendor.min.css'))
        .pipe(concat('vendor.min.css'))
        .pipe(gulp.dest('dist/assets/'));
});

gulp.task('images', function () {
    return gulp.src('src/img/**')
        .pipe(changed('dist/assets/img'))
        .pipe(gulp.dest('dist/assets/img'));
});

// Development server @ localhost:8000
gulp.task('server', function () {
    return gulp.src('dist')
        .pipe(server({
            livereload: false,
            open: true,
            log: 'debug'
        }));
});

// Prompt
gulp.task('prompt', function () {
    return fs.readFile('prompt.txt', 'utf8', function (err, data) {
        if (err) {
            throw err;
        }
        console.log(data);
    });
});

// Wordpress tasks
gulp.task('wordpress:theme', ['build'], function() {
    return gulp.src('dist/assets/**')
        .pipe(gulp.dest('theme/assets'));
});

gulp.task('wordpress', ['wordpress:theme'], function () {
    return gulp.src('theme/**')
        .pipe(gulp.dest('wordpress/wp-content/themes/' + WORDPRESS_THEME));
});

// Watch for updates in files to recompile assets
gulp.task('watch', function () {
    gulp.watch('js/*.js', ['script']);
    gulp.watch('css/*.css', ['style']);
    gulp.watch('bower.json', ['bower']);
    gulp.watch('*.html', ['bower:wire']);
    gulp.watch('bower.json', ['bower:copy']);
});

gulp.task('build', ['script', 'style', 'bower', 'images']);
gulp.task('serve', ['build', 'watch', 'server']);
gulp.task('smash', ['prompt', 'serve']);
gulp.task('default', ['build']);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');

var $ = require('gulp-load-plugins')();

var wiredep = require('wiredep');

gulp.task('test', function() {
  var bowerDeps = wiredep({
    directory: 'src/bower_components',
    exclude: ['bootstrap-sass-official'],
    dependencies: true,
    devDependencies: true
  });

  var testFiles = bowerDeps.js.concat([
    'src/{app,components}/**/*.js',
    'test/unit/**/*.js'
  ]);

  return gulp.src(testFiles)
    .pipe($.karma({
      configFile: 'test/karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      // Make sure failed tests cause gulp to exit non-zero
      throw err;
    });
});
<commit_msg>fix wiredep conf for unit tests<commit_after>'use strict';

var gulp = require('gulp');

var $ = require('gulp-load-plugins')();

var wiredep = require('wiredep');

gulp.task('test', function() {
  var bowerDeps = wiredep({
    directory: 'bower_components',
    exclude: ['bootstrap-sass-official'],
    dependencies: true,
    devDependencies: true
  });

  var testFiles = bowerDeps.js.concat([
    'src/{app,components}/**/*.js',
    'test/unit/**/*.js'
  ]);

  return gulp.src(testFiles)
    .pipe($.karma({
      configFile: 'test/karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      // Make sure failed tests cause gulp to exit non-zero
      throw err;
    });
});
<|endoftext|>


<commit_before>module.exports = function(RED) {
    function RuuviTagNode(config) {
        RED.nodes.createNode(this,config);
        var node = this;
        node.on('input', function(msg) {
            //Expects noble manufacturer data
            if(!msg.advertisement || !msg.advertisement.manufacturerData){
              return null;
            }
            let manufacturerDataString = msg.advertisement.manufacturerData.toString('hex');
            let ruuviData = parseRuuviData(manufacturerDataString);
            if(!ruuviData){
              return null;
            }
            msg.payload = JSON.stringify(ruuviData);
            node.send(msg);
        });
    }
    RED.nodes.registerType("ruuvitag",RuuviTagNode);
}

var parseRuuviData = function(manufacturerDataString){

  let formatStart = 4;
  let formatEnd   = 6;
  let formatRAW   = "03";
  let dataFormat = manufacturerDataString.substring(formatStart, formatEnd);
  let dataObject = {};
  switch(dataFormat)
  {
    case formatRAW:
      dataObject = parseRawRuuvi(manufacturerDataString)
    break;

    default:
      //console.log("Unknown dataformat: " + dataFormat);
      dataObject = null;
  }

  return dataObject;
}

//https://github.com/ruuvi/ruuvi-sensor-protocols
var parseRawRuuvi = function(manufacturerDataString){
  let humidityStart      = 6;
  let humidityEnd        = 8;
  let temperatureStart   = 8;
  let temperatureEnd     = 12;
  let pressureStart      = 12;
  let pressureEnd        = 16;
  let accelerationXStart = 16;
  let accelerationXEnd   = 20;
  let accelerationYStart = 20;
  let accelerationYEnd   = 24;
  let accelerationZStart = 24;
  let accelerationZEnd   = 28;
  let batteryStart       = 28;
  let batteryEnd         = 32;

  let robject = {};

  let humidity = manufacturerDataString.substring(humidityStart, humidityEnd);
  //console.log(humidity);
  humidity = parseInt(humidity, 16);
  humidity/= 2; //scale
  robject.humidity = humidity;

  let temperatureString = manufacturerDataString.substring(temperatureStart, temperatureEnd);
  let temperature = parseInt(temperatureString.substring(0, 2), 16);  //Full degrees
  if(temperature > 128){
    temperature -= 256; //two's complement
  }
  temperature += parseInt(temperatureString.substring(2, 4), 16)/100; //Decimals
  robject.temperature = temperature;

  let pressure = parseInt(manufacturerDataString.substring(pressureStart, pressureEnd), 16);  // uint16_t pascals
  pressure += 50000; //Ruuvi format
  robject.pressure = pressure;

  let accelerationX = parseInt(manufacturerDataString.substring(accelerationXStart, accelerationXEnd), 16);  // milli-g
  if(accelerationX > 32767){ accelerationX -= 65536;}  //two's complement

  let accelerationY = parseInt(manufacturerDataString.substring(accelerationYStart, accelerationYEnd), 16);  // milli-g
  if(accelerationY > 32767){ accelerationY -= 65536;}  //two's complement

  let accelerationZ = parseInt(manufacturerDataString.substring(accelerationZStart, accelerationZEnd), 16);  // milli-g
  if(accelerationZ > 32767){ accelerationZ -= 65536;}  //two's complement

  robject.accelerationX = accelerationX;
  robject.accelerationY = accelerationY;
  robject.accelerationZ = accelerationZ;

  let battery = parseInt(manufacturerDataString.substring(batteryStart, batteryEnd), 16);  // milli-g
  robject.battery = battery;

  return robject;
}
<commit_msg>Fix temperature calculation<commit_after>module.exports = function(RED) {
    function RuuviTagNode(config) {
        RED.nodes.createNode(this,config);
        var node = this;
        node.on('input', function(msg) {
            //Expects noble manufacturer data
            if(!msg.advertisement || !msg.advertisement.manufacturerData){
              return null;
            }
            let manufacturerDataString = msg.advertisement.manufacturerData.toString('hex');
            let ruuviData = parseRuuviData(manufacturerDataString);
            if(!ruuviData){
              return null;
            }
            msg.payload = JSON.stringify(ruuviData);
            node.send(msg);
        });
    }
    RED.nodes.registerType("ruuvitag",RuuviTagNode);
}

var parseRuuviData = function(manufacturerDataString){

  let formatStart = 4;
  let formatEnd   = 6;
  let formatRAW   = "03";
  let dataFormat = manufacturerDataString.substring(formatStart, formatEnd);
  let dataObject = {};
  switch(dataFormat)
  {
    case formatRAW:
      dataObject = parseRawRuuvi(manufacturerDataString)
    break;

    default:
      //console.log("Unknown dataformat: " + dataFormat);
      dataObject = null;
  }

  return dataObject;
}

//https://github.com/ruuvi/ruuvi-sensor-protocols
var parseRawRuuvi = function(manufacturerDataString){
  let humidityStart      = 6;
  let humidityEnd        = 8;
  let temperatureStart   = 8;
  let temperatureEnd     = 12;
  let pressureStart      = 12;
  let pressureEnd        = 16;
  let accelerationXStart = 16;
  let accelerationXEnd   = 20;
  let accelerationYStart = 20;
  let accelerationYEnd   = 24;
  let accelerationZStart = 24;
  let accelerationZEnd   = 28;
  let batteryStart       = 28;
  let batteryEnd         = 32;

  let robject = {};

  let humidity = manufacturerDataString.substring(humidityStart, humidityEnd);
  //console.log(humidity);
  humidity = parseInt(humidity, 16);
  humidity/= 2; //scale
  robject.humidity = humidity;

  let temperatureString = manufacturerDataString.substring(temperatureStart, temperatureEnd);
  let temperature = parseInt(temperatureString.substring(0, 2), 16);  //Full degrees
  temperature += parseInt(temperatureString.substring(2, 4), 16)/100; //Decimals
  if(temperature > 128){           // Ruuvi format, sign bit + value
    temperature = temperature-128;
    temperature = 0 - temperature;
  }
  robject.temperature = temperature;

  let pressure = parseInt(manufacturerDataString.substring(pressureStart, pressureEnd), 16);  // uint16_t pascals
  pressure += 50000; //Ruuvi format
  robject.pressure = pressure;

  let accelerationX = parseInt(manufacturerDataString.substring(accelerationXStart, accelerationXEnd), 16);  // milli-g
  if(accelerationX > 32767){ accelerationX -= 65536;}  //two's complement

  let accelerationY = parseInt(manufacturerDataString.substring(accelerationYStart, accelerationYEnd), 16);  // milli-g
  if(accelerationY > 32767){ accelerationY -= 65536;}  //two's complement

  let accelerationZ = parseInt(manufacturerDataString.substring(accelerationZStart, accelerationZEnd), 16);  // milli-g
  if(accelerationZ > 32767){ accelerationZ -= 65536;}  //two's complement

  robject.accelerationX = accelerationX;
  robject.accelerationY = accelerationY;
  robject.accelerationZ = accelerationZ;

  let battery = parseInt(manufacturerDataString.substring(batteryStart, batteryEnd), 16);  // milli-g
  robject.battery = battery;

  return robject;
}
<|endoftext|>


<commit_before>import React from 'react';
import { Container } from 'react-bootstrap';

const About = () => (
  <Container>

Coordinate Commons

Welcome to Coordinate Commons! This is a very early stage application to keep track of places you've visited.  Places can be anything that can be represented geographically, but the things that
    I'm starting off with are:

    Countries, US States, and Canadian Provices

Next priority will be US Counties, which is the main reason I am writing this site! I've made it a life goal to visit as many different counties in the United States as I can and this site will allow me to keep track of that. Trying to visit more counties has made my personal and family vacations/trips more interesting and fun!

But eventually I'll get other things like highways, cities, mountains, etc

Coordinate Commons is a side project of Brent Sowers. I'm doing this partially because I really do want to build this product as I will find it useful for me, and I'm sure it will help others as well. I'm also doing it to get some good web development experience with React, node, lambdas, and AWS. I am a senior software engineering manager, and have done much web application development in my career, but do not have a lot of direct hands on coding experience with React and node, so I want to expand my skillset. What better way to do this than to build my own side project! You can see the source code for this at https://github.com/brentsowers1/coordinatecommons-frontend and https://github.com/brentsowers1/coordinatecommons-backend

Here's a rough roadmap of features and functionality and I am planning to implement (on no specific timeline!)

Persisting the login - ability to remember device

Forgot username and/or password functionality

Making the permanent URLs for subpages work (like /app/verify)

More/less precise places on the map when you zoom in/out

Counties

A "My Page" that lists all of your places across place types

Properly styled user interface

A shareable page of your places that doesn't require you to log in

Leaderboards

Defining your own categories to classify visits

Other place types like highways, cities, and mountains

  </Container>
);

export default About;
<commit_msg>Updated about page with latest changes<commit_after>import React from 'react';
import { Container } from 'react-bootstrap';

const About = () => (
  <Container>

Coordinate Commons

Welcome to Coordinate Commons! This is a very early stage application to keep track of places you've visited.  Places can be anything that can be represented geographically, but the things that
    I'm starting off with are:

    Countries, US States, and Canadian Provices

Next priority will be US Counties, which is the main reason I am writing this site! I've made it a life goal to visit as many different counties in the United States as I can and this site will allow me to keep track of that. Trying to visit more counties has made my personal and family vacations/trips more interesting and fun!

But eventually I'll get other things like highways, cities, mountains, etc

Coordinate Commons is a side project of Brent Sowers. I'm doing this partially because I really do want to build this product as I will find it useful for me, and I'm sure it will help others as well. I'm also doing it to get some good web development experience with React, node, lambdas, and AWS. I am a senior software engineering manager, and have done much web application development in my career, but do not have a lot of direct hands on coding experience with React and node, so I want to expand my skillset. What better way to do this than to build my own side project! You can see the source code for this at https://github.com/brentsowers1/coordinatecommons-frontend and https://github.com/brentsowers1/coordinatecommons-backend

Here's a rough roadmap of features and functionality and I am planning to implement (on no specific timeline!)

Persisting the login - ability to remember device

Forgot username and/or password functionality

More efficient loading of high res GeoJSON - currently this can cause the map to hang for several seconds

Counties

A "My Page" that lists all of your places across place types, and give you links to share with others

Properly styled user interface

Leaderboards

Defining your own categories to classify visits

Other place types like highways, cities, and mountains

  </Container>
);

export default About;
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync').create();
var reload = function() {
    browserSync.reload();
};

var src = {
    js: [
        'src/js/app.js'
    ],
    css: [
        'src/scss/app.scss'
    ]
};

var tasks = {};

tasks.js = function(done) {
    return gulp.src(src.js)
        .pipe($.plumber({
            errorHandler: $.notify.onError("Error:\n<%= error %>")
        }))
        .pipe($.sourcemaps.init())
        .pipe($.concat('app.js'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('public/content/js/'));
};

tasks.css = function(done) {
    return gulp.src(src.css)
        .pipe($.plumber({
            errorHandler: $.notify.onError("Error:\n<%= error %>")
        }))
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            errLogToConsole: true
        }))
        .pipe($.concat('app.css'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('public/content/css/'));
};

tasks.serve = function(done) {
    browserSync.init({
        server: {
            baseDir: "./public"
        }
    });

    return done();
};

gulp.task('js', tasks.js);
gulp.task('js-watch', ['js'], reload);

gulp.task('css', tasks.css);
gulp.task('css-watch', ['css'], reload);

gulp.task('serve', ['js', 'css'], tasks.serve);

gulp.task('watch', ['js', 'css', 'serve'], function() {
    gulp.watch(src.js, ['js-watch']);
    gulp.watch(src.css, ['css-watch']);
});

gulp.task('default', ['watch']);<commit_msg>BS port<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync').create();
var reload = function() {
    browserSync.reload();
};

var src = {
    js: [
        'src/js/app.js'
    ],
    css: [
        'src/scss/app.scss'
    ]
};

var tasks = {};

tasks.js = function(done) {
    return gulp.src(src.js)
        .pipe($.plumber({
            errorHandler: $.notify.onError("Error:\n<%= error %>")
        }))
        .pipe($.sourcemaps.init())
        .pipe($.concat('app.js'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('public/content/js/'));
};

tasks.css = function(done) {
    return gulp.src(src.css)
        .pipe($.plumber({
            errorHandler: $.notify.onError("Error:\n<%= error %>")
        }))
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            errLogToConsole: true
        }))
        .pipe($.concat('app.css'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('public/content/css/'));
};

tasks.serve = function(done) {
    browserSync.init({
        server: {
            baseDir: "./public"
        },
        ui: {
            port: 8080
        }
    });

    return done();
};

gulp.task('js', tasks.js);
gulp.task('js-watch', ['js'], reload);

gulp.task('css', tasks.css);
gulp.task('css-watch', ['css'], reload);

gulp.task('serve', ['js', 'css'], tasks.serve);

gulp.task('watch', ['js', 'css', 'serve'], function() {
    gulp.watch(src.js, ['js-watch']);
    gulp.watch(src.css, ['css-watch']);
    gulp.watch('public/**/*.html', reload);
});

gulp.task('default', ['watch']);<|endoftext|>


<commit_before>/**
 * Created by ndyumin on 02.10.2016.
 */

module.exports = function addStore(_store, initial) {
    const resetEvent = _store.eventCreatorFactory((s, u) => u.state);
    const devtool = window.devToolsExtension(function(s, u) {
        return u.type === '@@INIT' ? initial : u.reduce(s, u.update);
    });

    devtool.subscribe(()=> resetEvent({
        _type: '@@RESET',
        state: devtool.getState()
    }));

    _store._eventLog(ev => {
        if (ev.update._type !== '@@RESET') {
            devtool.dispatch(Object.assign(ev, {type: ev.reduce.name}))
        }
    });
};
<commit_msg>fix npe<commit_after>/**
 * Created by ndyumin on 02.10.2016.
 */

module.exports = function addStore(_store, initial) {
    const resetEvent = _store.eventCreatorFactory((s, u) => u.state);
    const devtool = window.devToolsExtension(function(s, u) {
        return u.type === '@@INIT' ? initial : u.reduce(s, u.update);
    });

    devtool.subscribe(()=> resetEvent({
        _type: '@@RESET',
        state: devtool.getState()
    }));

    _store._eventLog(ev => {
        if (ev.update && ev.update._type !== '@@RESET') {
            devtool.dispatch(Object.assign(ev, {type: ev.reduce.name}))
        }
    });

    return devtool;
};
<|endoftext|>


<commit_before>/**
 * Build system.
 * @module gulpfile
 */
'use strict';

// Module dependencies.
var browserify=require('browserify');
var child=require('child_process');
var del=require('del');
var gulp=require('gulp');
var loadPlugins=require('gulp-load-plugins');
var pkg=require('./package.json');
var util=require('util');

/**
 * Provides tasks for [Gulp.js](http://gulpjs.com) build system.
 * @class cli.Gulpfile
 * @static
 */

/**
 * The task settings.
 * @property config
 * @type Object
 */
var config={
  output: util.format('%s-%s.zip', pkg.yuidoc.name.toLowerCase(), pkg.version)
};

/**
 * The task plugins.
 * @property plugins
 * @type Object
 */
var plugins=loadPlugins({
  pattern: [ 'gulp-*', 'vinyl-*' ],
  replaceString: /^(gulp|vinyl)-/
});

/**
 * Runs the default tasks.
 * @method default
 */
gulp.task('default', [ 'css', 'js' ]);

/**
 * Checks the package dependencies.
 * @method check
 */
gulp.task('check', function() {
  return gulp.src('package.json')
    .pipe(plugins.david())
    .pipe(plugins.david.reporter);
});

/**
 * Deletes all generated files and reset any saved state.
 * @method clean
 */
gulp.task('clean', function(callback) {
  del('var/'+config.output, callback);
});

/**
 * Builds the stylesheets.
 * @method css
 */
gulp.task('css', function() {
  return gulp.src(require.resolve('mocha/mocha.css'))
    .pipe(gulp.dest('www/css'));
});

/**
 * Creates a distribution file for this program.
 * @method dist
 */
gulp.task('dist', [ 'default' ], function() {
  var sources=[
    '*.js',
    '*.json',
    '*.md',
    '*.txt',
    'bin/*',
    'lib/*.js',
    'test/*.js',
    'www/**/*',
    '!www/**/*.map'
  ];

  return gulp.src(sources, { base: '.' })
    .pipe(plugins.zip(config.output))
    .pipe(gulp.dest('var'));
});

/**
 * Builds the documentation.
 * @method doc
 */
gulp.task('doc', [ 'doc:assets' ]);

gulp.task('doc:assets', [ 'doc:build' ], function() {
  return gulp.src([ 'www/apple-touch-icon.png', 'www/favicon.ico' ])
    .pipe(gulp.dest('doc/api/assets'));
});

gulp.task('doc:build', function(callback) {
  _exec('docgen', callback);
});

/**
 * Builds the client scripts.
 * @method js
 */
gulp.task('js', [ 'js:tests' ], function() {
  return browserify({ debug: true, entries: [ './www/js/main.js' ] })
    .bundle()
    .pipe(plugins.sourceStream('tests.js'))
    .pipe(plugins.buffer())
    .pipe(plugins.sourcemaps.init({ loadMaps: true }))
    .pipe(plugins.uglify())
    .pipe(plugins.sourcemaps.write('.'))
    .pipe(gulp.dest('www/js'));
});

gulp.task('js:tests', function() {
  return gulp.src(require.resolve('mocha/mocha.js'))
    .pipe(plugins.uglify())
    .pipe(gulp.dest('www/js'));
});

/**
 * Performs static analysis of source code.
 * @method lint
 */
gulp.task('lint', [ 'lint:doc', 'lint:js' ]);

gulp.task('lint:doc', function(callback) {
  _exec('docgen --lint', callback);
});

gulp.task('lint:js', function() {
  return gulp.src([ '*.js', 'bin/*.js', 'lib/*.js', 'test/*.js', 'www/js/main.js' ])
    .pipe(plugins.jshint(pkg.jshintConfig))
    .pipe(plugins.jshint.reporter('default', { verbose: true }));
});

/**
 * Starts the Web server.
 * @method serve
 */
gulp.task('serve', function(callback) {
  if('_server' in config) {
    config._server.kill();
    delete config._server;
  }

  config._server=child.fork('bin/cli.js');
  callback();
});

/**
 * Runs the unit tests.
 * @method test
 */
gulp.task('test', [ 'test:env' ], function() {
  return gulp.src([ 'test/*.js' ], { read: false })
    .pipe(plugins.mocha());
});

gulp.task('test:env', function(callback) {
  if('AKISMET_API_KEY' in process.env) callback();
  else callback(new Error('AKISMET_API_KEY environment variable not set.'));
});

/**
 * Watches for file changes.
 * @method watch
 */
gulp.task('watch', [ 'js', 'serve' ], function() {
  gulp.watch('lib/*.js', [ 'js', 'serve' ]);
  gulp.watch([ 'test/*.js', 'www/js/main.js' ], [ 'js' ]);
});

/**
 * Runs a command and prints its output.
 * @method _exec
 * @param {String} command The command to run, with space-separated arguments.
 * @param {Function} callback The function to invoke when the task is over.
 * @async
 * @private
 */
function _exec(command, callback) {
  child.exec(command, function(err, stdout) {
    console.log(stdout.trim());
    if(err) console.error(err);
    callback();
  });
}
<commit_msg>Optimized the console output<commit_after>/**
 * Build system.
 * @module gulpfile
 */
'use strict';

// Module dependencies.
var browserify=require('browserify');
var child=require('child_process');
var del=require('del');
var gulp=require('gulp');
var loadPlugins=require('gulp-load-plugins');
var pkg=require('./package.json');
var util=require('util');

/**
 * Provides tasks for [Gulp.js](http://gulpjs.com) build system.
 * @class cli.Gulpfile
 * @static
 */

/**
 * The task settings.
 * @property config
 * @type Object
 */
var config={
  output: util.format('%s-%s.zip', pkg.yuidoc.name.toLowerCase(), pkg.version)
};

/**
 * The task plugins.
 * @property plugins
 * @type Object
 */
var plugins=loadPlugins({
  pattern: [ 'gulp-*', 'vinyl-*' ],
  replaceString: /^(gulp|vinyl)-/
});

/**
 * Runs the default tasks.
 * @method default
 */
gulp.task('default', [ 'css', 'js' ]);

/**
 * Checks the package dependencies.
 * @method check
 */
gulp.task('check', function() {
  return gulp.src('package.json')
    .pipe(plugins.david())
    .pipe(plugins.david.reporter);
});

/**
 * Deletes all generated files and reset any saved state.
 * @method clean
 */
gulp.task('clean', function(callback) {
  del('var/'+config.output, callback);
});

/**
 * Builds the stylesheets.
 * @method css
 */
gulp.task('css', function() {
  return gulp.src(require.resolve('mocha/mocha.css'))
    .pipe(gulp.dest('www/css'));
});

/**
 * Creates a distribution file for this program.
 * @method dist
 */
gulp.task('dist', [ 'default' ], function() {
  var sources=[
    '*.js',
    '*.json',
    '*.md',
    '*.txt',
    'bin/*',
    'lib/*.js',
    'test/*.js',
    'www/**/*',
    '!www/**/*.map'
  ];

  return gulp.src(sources, { base: '.' })
    .pipe(plugins.zip(config.output))
    .pipe(gulp.dest('var'));
});

/**
 * Builds the documentation.
 * @method doc
 */
gulp.task('doc', [ 'doc:assets' ]);

gulp.task('doc:assets', [ 'doc:build' ], function() {
  return gulp.src([ 'www/apple-touch-icon.png', 'www/favicon.ico' ])
    .pipe(gulp.dest('doc/api/assets'));
});

gulp.task('doc:build', function(callback) {
  _exec('docgen', callback);
});

/**
 * Builds the client scripts.
 * @method js
 */
gulp.task('js', [ 'js:tests' ], function() {
  return browserify({ debug: true, entries: [ './www/js/main.js' ] })
    .bundle()
    .pipe(plugins.sourceStream('tests.js'))
    .pipe(plugins.buffer())
    .pipe(plugins.sourcemaps.init({ loadMaps: true }))
    .pipe(plugins.uglify())
    .pipe(plugins.sourcemaps.write('.'))
    .pipe(gulp.dest('www/js'));
});

gulp.task('js:tests', function() {
  return gulp.src(require.resolve('mocha/mocha.js'))
    .pipe(plugins.uglify())
    .pipe(gulp.dest('www/js'));
});

/**
 * Performs static analysis of source code.
 * @method lint
 */
gulp.task('lint', [ 'lint:doc', 'lint:js' ]);

gulp.task('lint:doc', function(callback) {
  _exec('docgen --lint', callback);
});

gulp.task('lint:js', function() {
  return gulp.src([ '*.js', 'bin/*.js', 'lib/*.js', 'test/*.js', 'www/js/main.js' ])
    .pipe(plugins.jshint(pkg.jshintConfig))
    .pipe(plugins.jshint.reporter('default', { verbose: true }));
});

/**
 * Starts the Web server.
 * @method serve
 */
gulp.task('serve', function(callback) {
  if('_server' in config) {
    config._server.kill();
    delete config._server;
  }

  config._server=child.fork('bin/cli.js');
  callback();
});

/**
 * Runs the unit tests.
 * @method test
 */
gulp.task('test', [ 'test:env' ], function() {
  return gulp.src([ 'test/*.js' ], { read: false })
    .pipe(plugins.mocha());
});

gulp.task('test:env', function(callback) {
  if('AKISMET_API_KEY' in process.env) callback();
  else callback(new Error('AKISMET_API_KEY environment variable not set.'));
});

/**
 * Watches for file changes.
 * @method watch
 */
gulp.task('watch', [ 'js', 'serve' ], function() {
  gulp.watch('lib/*.js', [ 'js', 'serve' ]);
  gulp.watch([ 'test/*.js', 'www/js/main.js' ], [ 'js' ]);
});

/**
 * Runs a command and prints its output.
 * @method _exec
 * @param {String} command The command to run, with space-separated arguments.
 * @param {Function} callback The function to invoke when the task is over.
 * @async
 * @private
 */
function _exec(command, callback) {
  child.exec(command, function(err, stdout) {
    var output=stdout.trim();
    if(output.length) console.log(output);
    if(err) console.error(err);
    callback();
  });
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

 define((require, exports, module) => {
   'use strict';

   const $ = require('jquery');
   const Account = require('models/account');
   const { assert } = require('chai');
   const Backbone = require('backbone');
   const Broker = require('models/auth_brokers/base');
   const { FIREFOX_MOBILE_INSTALL } = require('lib/sms-message-ids');
   const Metrics = require('lib/metrics');
   const Notifier = require('lib/channels/notifier');
   const p = require('lib/promise');
   const Relier = require('models/reliers/relier');
   const SmsErrors = require('lib/sms-errors');
   const sinon = require('sinon');
   const View = require('views/sms_sent');

   describe('views/sms_sent', () => {
     let account;
     let metrics;
     let model;
     let view;

     beforeEach(() => {
       account = new Account();
       metrics = new Metrics();
       model = new Backbone.Model({
         account,
         country: 'US',
         normalizedPhoneNumber: '+11234567890'
       });

       view = new View({
         broker: new Broker({}),
         metrics,
         model,
         notifier: new Notifier(),
         relier: new Relier({ service: 'sync' }),
         viewName: 'sms-sent'
       });

       sinon.stub(view, 'checkAuthorization').callsFake(() => p(true));
     });

     afterEach(() => {
       metrics.destroy();
       metrics = null;

       view.destroy(true);
       view = null;
     });

     it('returns to `sms` if no `normalizedPhoneNumber`', () => {
       sinon.spy(view, 'navigate');

       model.unset('normalizedPhoneNumber');

       return view.render()
        .then(() => {
          assert.isTrue(view.navigate.calledOnce);
          assert.isTrue(view.navigate.calledWith('sms'));
        });
     });

     it('returns to `sms` if no `country`', () => {
       sinon.spy(view, 'navigate');

       model.unset('country');

       return view.render()
        .then(() => {
          assert.isTrue(view.navigate.calledOnce);
          assert.isTrue(view.navigate.calledWith('sms'));
        });
     });

     it('renders a US phone number correctly, shows marketing', () => {
       model.set({
         country: 'US',
         phoneNumber: '+11234567890'
       });

       return view.render()
        .then(() => {
          assert.include(view.$('.success').text(), '123-456-7890');
          assert.lengthOf(view.$('.marketing-link'), 2);

          // ensure clicks on the marketing links work as expected.
          sinon.spy(metrics, 'logMarketingClick');
          sinon.spy(view, 'logFlowEvent');
          $('#container').html(view.$el);

          view.$('.marketing-link-ios').click();
          assert.isTrue(metrics.logMarketingClick.calledOnce);
          assert.equal(metrics.logMarketingClick.args[0][0], 'autumn-2016-connect-another-device');
          assert.isTrue(view.logFlowEvent.calledOnce);
          assert.isTrue(view.logFlowEvent.calledWith('link.app-store.ios', 'sms-sent'));

          view.$('.marketing-link-android').click();
          assert.isTrue(metrics.logMarketingClick.calledTwice);
          assert.equal(metrics.logMarketingClick.args[1][0], 'autumn-2016-connect-another-device');
          assert.isTrue(view.logFlowEvent.calledTwice);
          assert.isTrue(view.logFlowEvent.calledWith('link.app-store.android', 'sms-sent'));
        });
     });

     it('renders a GB phone number correctly', () => {
       model.set({
         country: 'GB',
         normalizedPhoneNumber: '+441234567890'
       });

       return view.render()
        .then(() => {
          assert.include(view.$('.success').text(), '+44 1234 567890');
        });
     });

     it('resend success, displays the success message', () => {
       sinon.stub(account, 'sendSms').callsFake(() => p());
       sinon.spy(view, 'render');
       sinon.stub(view, 'getSmsFeatures').callsFake(() => ['signinCodes']);

       return view.resend()
         .then(() => {
           assert.isTrue(account.sendSms.calledOnce);
           assert.isTrue(account.sendSms.calledWith('+11234567890', FIREFOX_MOBILE_INSTALL, { features: ['signinCodes']}));

           assert.isTrue(view.getSmsFeatures.calledOnce);
           assert.isTrue(view.render.calledOnce);
           const successText = view.$('.success').text();
           assert.include(successText, 'resent');
           assert.include(successText, '123-456-7890');
         });
     });

     it('resend failure, displays the error message', () => {
       sinon.stub(account, 'sendSms').callsFake(() => p.reject(SmsErrors.toError('THROTTLED')));
       sinon.spy(view, 'displayError');
       sinon.stub(view, 'getSmsFeatures').callsFake(() => ['signinCodes']);

       // _resend is called instead of resend to test resend-mixin integration.
       return view._resend()
         .then(() => {
           assert.isTrue(account.sendSms.calledOnce);
           assert.isTrue(account.sendSms.calledWith('+11234567890', FIREFOX_MOBILE_INSTALL, { features: ['signinCodes']}));

           assert.isTrue(view.getSmsFeatures.calledOnce);
           assert.isTrue(view.displayError.calledOnce);
           assert.isTrue(SmsErrors.is(view.displayError.args[0][0], 'THROTTLED'));
         });
     });
   });
 });
<commit_msg>chore(test): Fix the spacing in sms_sent.js (#5616) r=@shane-tomlinson<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

define((require, exports, module) => {
  'use strict';

  const $ = require('jquery');
  const Account = require('models/account');
  const { assert } = require('chai');
  const Backbone = require('backbone');
  const Broker = require('models/auth_brokers/base');
  const { FIREFOX_MOBILE_INSTALL } = require('lib/sms-message-ids');
  const Metrics = require('lib/metrics');
  const Notifier = require('lib/channels/notifier');
  const p = require('lib/promise');
  const Relier = require('models/reliers/relier');
  const SmsErrors = require('lib/sms-errors');
  const sinon = require('sinon');
  const View = require('views/sms_sent');

  describe('views/sms_sent', () => {
    let account;
    let metrics;
    let model;
    let view;

    beforeEach(() => {
      account = new Account();
      metrics = new Metrics();
      model = new Backbone.Model({
        account,
        country: 'US',
        normalizedPhoneNumber: '+11234567890'
      });

      view = new View({
        broker: new Broker({}),
        metrics,
        model,
        notifier: new Notifier(),
        relier: new Relier({ service: 'sync' }),
        viewName: 'sms-sent'
      });

      sinon.stub(view, 'checkAuthorization').callsFake(() => p(true));
    });

    afterEach(() => {
      metrics.destroy();
      metrics = null;

      view.destroy(true);
      view = null;
    });

    it('returns to `sms` if no `normalizedPhoneNumber`', () => {
      sinon.spy(view, 'navigate');

      model.unset('normalizedPhoneNumber');

      return view.render()
       .then(() => {
         assert.isTrue(view.navigate.calledOnce);
         assert.isTrue(view.navigate.calledWith('sms'));
       });
    });

    it('returns to `sms` if no `country`', () => {
      sinon.spy(view, 'navigate');

      model.unset('country');

      return view.render()
       .then(() => {
         assert.isTrue(view.navigate.calledOnce);
         assert.isTrue(view.navigate.calledWith('sms'));
       });
    });

    it('renders a US phone number correctly, shows marketing', () => {
      model.set({
        country: 'US',
        phoneNumber: '+11234567890'
      });

      return view.render()
       .then(() => {
         assert.include(view.$('.success').text(), '123-456-7890');
         assert.lengthOf(view.$('.marketing-link'), 2);

         // ensure clicks on the marketing links work as expected.
         sinon.spy(metrics, 'logMarketingClick');
         sinon.spy(view, 'logFlowEvent');
         $('#container').html(view.$el);

         view.$('.marketing-link-ios').click();
         assert.isTrue(metrics.logMarketingClick.calledOnce);
         assert.equal(metrics.logMarketingClick.args[0][0], 'autumn-2016-connect-another-device');
         assert.isTrue(view.logFlowEvent.calledOnce);
         assert.isTrue(view.logFlowEvent.calledWith('link.app-store.ios', 'sms-sent'));

         view.$('.marketing-link-android').click();
         assert.isTrue(metrics.logMarketingClick.calledTwice);
         assert.equal(metrics.logMarketingClick.args[1][0], 'autumn-2016-connect-another-device');
         assert.isTrue(view.logFlowEvent.calledTwice);
         assert.isTrue(view.logFlowEvent.calledWith('link.app-store.android', 'sms-sent'));
       });
    });

    it('renders a GB phone number correctly', () => {
      model.set({
        country: 'GB',
        normalizedPhoneNumber: '+441234567890'
      });

      return view.render()
       .then(() => {
         assert.include(view.$('.success').text(), '+44 1234 567890');
       });
    });

    it('resend success, displays the success message', () => {
      sinon.stub(account, 'sendSms').callsFake(() => p());
      sinon.spy(view, 'render');
      sinon.stub(view, 'getSmsFeatures').callsFake(() => ['signinCodes']);

      return view.resend()
        .then(() => {
          assert.isTrue(account.sendSms.calledOnce);
          assert.isTrue(account.sendSms.calledWith('+11234567890', FIREFOX_MOBILE_INSTALL, { features: ['signinCodes']}));

          assert.isTrue(view.getSmsFeatures.calledOnce);
          assert.isTrue(view.render.calledOnce);
          const successText = view.$('.success').text();
          assert.include(successText, 'resent');
          assert.include(successText, '123-456-7890');
        });
    });

    it('resend failure, displays the error message', () => {
      sinon.stub(account, 'sendSms').callsFake(() => p.reject(SmsErrors.toError('THROTTLED')));
      sinon.spy(view, 'displayError');
      sinon.stub(view, 'getSmsFeatures').callsFake(() => ['signinCodes']);

      // _resend is called instead of resend to test resend-mixin integration.
      return view._resend()
        .then(() => {
          assert.isTrue(account.sendSms.calledOnce);
          assert.isTrue(account.sendSms.calledWith('+11234567890', FIREFOX_MOBILE_INSTALL, { features: ['signinCodes']}));

          assert.isTrue(view.getSmsFeatures.calledOnce);
          assert.isTrue(view.displayError.calledOnce);
          assert.isTrue(SmsErrors.is(view.displayError.args[0][0], 'THROTTLED'));
        });
    });
  });
});
<|endoftext|>


<commit_before>// This implements a single Group selection
// Multiple restrictions on the search query should be contained in separate GroupField objects
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types'
import AddAttribute from './AddAttribute';
import Button from 'react-md/lib/Buttons/Button';
import Subheader from 'react-md/lib/Subheaders';

let i = 0;

export default class Group extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      // selections represent a list of selected relation-attribute pairs specific to a single group
      selections: [
        {
          groupid: this.props.groupid,
          key: i
        }
      ]
    };

    this.onClick = this.onClick.bind(this);
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  }
  componentDidMount() {
    console.log(this.state)
  }
  onClick(){
    this.setState({
        selections: this.state.selections.concat([{
          groupid: this.props.groupid,
          key: i+1
        }])
      })
    i += 1;
  }
  render() {
    return (

        <Subheader primary primaryText={this.props.groupid} />
      {this.state.selections.map(selection =>

          <AddAttribute groupid={selection.groupid} key={selection.key} relations={this.props.relations} attributes={this.props.attributes}/>
          <Button flat label="Add a relation to this group" secondary onClick={this.onClick}>add</Button>

      )}

    );
  }
}
<commit_msg>FIX: moved the scope of the add relation button so it makes more sense<commit_after>// This implements a single Group selection
// Multiple restrictions on the search query should be contained in separate GroupField objects
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types'
import AddAttribute from './AddAttribute';
import Button from 'react-md/lib/Buttons/Button';
import Subheader from 'react-md/lib/Subheaders';

let i = 0;

export default class Group extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      // selections represent a list of selected relation-attribute pairs specific to a single group
      selections: [
        {
          groupid: this.props.groupid,
          key: i
        }
      ]
    };

    this.onClick = this.onClick.bind(this);
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  }
  componentDidMount() {
    console.log(this.state)
  }
  onClick(){
    this.setState({
        selections: this.state.selections.concat([{
          groupid: this.props.groupid,
          key: i+1
        }])
      })
    i += 1;
  }
  render() {
    return (

        <Subheader primary primaryText={this.props.groupid} />
        <Button flat label="Add another relation to this group" secondary onClick={this.onClick}>add</Button>
      {this.state.selections.map(selection =>

          <AddAttribute groupid={selection.groupid} key={selection.key} relations={this.props.relations} attributes={this.props.attributes}/>

      )}

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

// ########################################
// Modules
// ########################################
var gulp              = require('gulp'),
    del               = require('del'),
    mqpacker          = require('css-mqpacker'),
    autoprefixer      = require('autoprefixer-core'),
    // wiredep           = require('wiredep').stream,
    packager          = require('electron-packager');

var $ = require('gulp-load-plugins')({
  scope: ['devDependencies'],
  camelize: true,
  lazy: false,
});

var pkg = require('./package.json');

// ########################################
// Variables
// ########################################

// current enviroment
var env = process.env.NODE_ENV || 'development';

var IN_BASE   = 'src/';
var OUT_BASE  = 'prebuild/';
var OUT_BUILD = 'build/';
var BOWER     = 'bower_components/';

var IN = {
  CSS   : IN_BASE + 'scss/',
  JS    : IN_BASE + 'js/',
  IMG   : IN_BASE + 'img/',
  FONTS : IN_BASE + 'fonts/',
  HTML  : IN_BASE + 'html/'
};

var OUT = {
  CSS   : OUT_BASE + 'stylesheets/',
  JS    : OUT_BASE + 'javascripts/',
  IMG   : OUT_BASE + 'images/',
  FONTS : OUT_BASE + 'fonts/',
  HTML  : OUT_BASE + 'html/',
  ICONS : OUT_BASE + 'icons/'
};

// ########################################
// Helpers
// ########################################
var isProduction = function() {
  return env === 'production';
};

var isDevelopment = function() {
  return env === 'development';
};

gulp.task('clean', function(cb) {
  del([OUT_BASE], cb);
});

// ########################################
// Electron tasks
// ########################################
gulp.task('electron', function() {
  gulp.start('misc-files', 'node-modules');
});

gulp.task('misc-files', function() {
  return gulp.src([
    './package.json'
  ]).pipe(gulp.dest(OUT_BASE));
});

gulp.task('node-modules', function() {
  var dependencies = [];

  if(pkg.dependencies) {

    var depList = Object.keys(pkg.dependencies);

    depList.map(function(dep) {
      dependencies.push(dep);
    });
  }

  dependencies = dependencies.map(function(dep) {
    return './node_modules/' + dep;
  })

  return gulp.src(dependencies)
    .pipe(gulp.dest(OUT_BASE + 'node_modules/'));
});

// ####################
// CSS
// ####################
gulp.task('styles', function() {
  var processors = [
    // autoprefix css
    autoprefixer({
      browsers: ['> 5%'],
      cascade: true,
      remove: true,
    }),
    // combine identical media queries
    mqpacker({})
  ];

  return gulp.src(IN.CSS + '**/*.scss')
    .pipe($.plumber())
    .pipe($.sass({
      // includePaths: IN.CSS
    }).on('error', $.sass.logError))
    .pipe($.postcss(processors))
    .pipe($.if(isProduction(), $.minifyCss({
      keepSpecialComments: 0,
      processImport: true,
    })))
    .pipe(gulp.dest(OUT.CSS));
});

// ####################
// HTML
// ####################
gulp.task('html', function() {
  return gulp.src(IN.HTML + '**/*.html')
    .pipe($.if(isProduction(), $.minifyHtml({
      spare: true
    })))
    .pipe(gulp.dest(OUT.HTML));
});

// ####################
// IMAGES
// ####################
gulp.task('images', function() {
  return gulp.src(IN.IMG + '**/*')
    .pipe($.if(isProduction(), $.imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true,
      svgoPlugins: [
        {cleanupIDs: false}
      ]
      })))
    .pipe(gulp.dest(OUT.IMG));
});

// ####################
// FONTS
// ####################
gulp.task('fonts', function() {
  var fileTypes = '**/*.{eot,svg,ttf,woff,woff2}';

  return gulp.src(IN.FONTS + fileTypes)
    .pipe(gulp.dest(OUT.FONTS));
});

// ####################
// Javacript
// ####################
gulp.task('js', function() {
  return gulp.src(IN.JS + '**/*.js')
    .pipe($.plumber())
    .pipe($.babel())
    .pipe($.preprocess())
    // .on('error', function(e) {
    //   console.error(e);
    //   this.emit('end');
    // })
    .pipe(gulp.dest(OUT.JS));
});

// ####################
// Main TASKS
// ####################
gulp.task('default', ['clean'], function() {
  gulp.start('styles', 'images', 'fonts', 'js', 'html', 'electron', function(){

    // only launch in development
    if(isDevelopment()) {
      gulp.start('watch', function() {
        console.log('Listening for changes');
      });
    } else {
      console.log('build installation');
    }

  });
});

gulp.task('package', function(callback) {

  /**
   * Escape regex expression
   * Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters
   * @param  {String} string
   * @return {String}
   */
  var escapeRegExp = function(string){
    return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
  };

  // var ignoreList = [
  //   '/.git',
  //   '/tasks',
  //   '/sample-build.json'
  // ];

  // // Add development node modules to ignore list
  // if(typeof pkg.devDependencies) {
  //   var devDependencies = Object.keys(pkg.devDependencies);

  //   devDependencies.map(function(devPkg) {
  //     ignoreList.push('/node_modules/' + devPkg);
  //   });
  // };

  // // Escape regex for all ignored files
  // ignoreList = ignoreList.map(function(ignore) {
  //   return escapeRegExp(ignore)
  // });

  var opts = {
    dir: OUT_BASE,
    // ignore: new RegExp(ignoreList.join('|'), 'i'),
    name: pkg.appName,
    out: OUT_BUILD,
    platform: 'darwin',
    arch: 'x64',
    version: '0.30.4',
    overwrite: true,
    protocols: [
      {
        name: pkg.appName,
        schemes: [pkg.name]
      }
    ]
  };

  packager(opts, function(err, appPath) {
    callback(null);
  });
});

gulp.task('watch', function () {

  // bower.json
  // package.json
  gulp.watch(IN.FONTS + '**/*', ['fonts']);
  gulp.watch(IN.IMG + '**/*', ['images']);
  gulp.watch(IN.JS + '**/*.{js,jsx}', ['js']);
  gulp.watch(IN.CSS + '**/*.scss', ['styles']);
  gulp.watch(IN.HTML + '**/*.html', ['html']);
});
<commit_msg>Fix where node modules whernt actualy copied<commit_after>'use strict';

// ########################################
// Modules
// ########################################
var gulp              = require('gulp'),
    del               = require('del'),
    mqpacker          = require('css-mqpacker'),
    autoprefixer      = require('autoprefixer-core'),
    // wiredep           = require('wiredep').stream,
    packager          = require('electron-packager');

var $ = require('gulp-load-plugins')({
  scope: ['devDependencies'],
  camelize: true,
  lazy: false,
});

var pkg = require('./package.json');

// ########################################
// Variables
// ########################################

// current enviroment
var env = process.env.NODE_ENV || 'development';

var IN_BASE   = 'src/';
var OUT_BASE  = 'prebuild/';
var OUT_BUILD = 'build/';
var BOWER     = 'bower_components/';

var IN = {
  CSS   : IN_BASE + 'scss/',
  JS    : IN_BASE + 'js/',
  IMG   : IN_BASE + 'img/',
  FONTS : IN_BASE + 'fonts/',
  HTML  : IN_BASE + 'html/'
};

var OUT = {
  CSS   : OUT_BASE + 'stylesheets/',
  JS    : OUT_BASE + 'javascripts/',
  IMG   : OUT_BASE + 'images/',
  FONTS : OUT_BASE + 'fonts/',
  HTML  : OUT_BASE + 'html/',
  ICONS : OUT_BASE + 'icons/'
};

// ########################################
// Helpers
// ########################################
var isProduction = function() {
  return env === 'production';
};

var isDevelopment = function() {
  return env === 'development';
};

gulp.task('clean', function(cb) {
  del([OUT_BASE], cb);
});

// ########################################
// Electron tasks
// ########################################
gulp.task('electron', function() {
  gulp.start('misc-files', 'node-modules');
});

gulp.task('misc-files', function() {
  return gulp.src([
    './package.json'
  ]).pipe(gulp.dest(OUT_BASE));
});

gulp.task('node-modules', function() {
  var dependencies = [];

  if(pkg.dependencies) {

    var depList = Object.keys(pkg.dependencies);

    depList.map(function(dep) {
      dependencies.push(dep);
    });
  }

  dependencies = dependencies.map(function(dep) {
    return './node_modules/' + dep + '/**/*';
  })

  return gulp.src(dependencies, {
    base: './node_modules/'
  })
    .pipe(gulp.dest(OUT_BASE + 'node_modules/'));
});

// ####################
// CSS
// ####################
gulp.task('styles', function() {
  var processors = [
    // autoprefix css
    autoprefixer({
      browsers: ['> 5%'],
      cascade: true,
      remove: true,
    }),
    // combine identical media queries
    mqpacker({})
  ];

  return gulp.src(IN.CSS + '**/*.scss')
    .pipe($.plumber())
    .pipe($.sass({
      // includePaths: IN.CSS
    }).on('error', $.sass.logError))
    .pipe($.postcss(processors))
    .pipe($.if(isProduction(), $.minifyCss({
      keepSpecialComments: 0,
      processImport: true,
    })))
    .pipe(gulp.dest(OUT.CSS));
});

// ####################
// HTML
// ####################
gulp.task('html', function() {
  return gulp.src(IN.HTML + '**/*.html')
    .pipe($.if(isProduction(), $.minifyHtml({
      spare: true
    })))
    .pipe(gulp.dest(OUT.HTML));
});

// ####################
// IMAGES
// ####################
gulp.task('images', function() {
  return gulp.src(IN.IMG + '**/*')
    .pipe($.if(isProduction(), $.imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true,
      svgoPlugins: [
        {cleanupIDs: false}
      ]
      })))
    .pipe(gulp.dest(OUT.IMG));
});

// ####################
// FONTS
// ####################
gulp.task('fonts', function() {
  var fileTypes = '**/*.{eot,svg,ttf,woff,woff2}';

  return gulp.src(IN.FONTS + fileTypes)
    .pipe(gulp.dest(OUT.FONTS));
});

// ####################
// Javacript
// ####################
gulp.task('js', function() {
  return gulp.src(IN.JS + '**/*.js')
    .pipe($.plumber())
    .pipe($.babel())
    .pipe($.preprocess())
    // .on('error', function(e) {
    //   console.error(e);
    //   this.emit('end');
    // })
    .pipe(gulp.dest(OUT.JS));
});

// ####################
// Main TASKS
// ####################
gulp.task('default', ['clean'], function() {
  gulp.start('styles', 'images', 'fonts', 'js', 'html', 'electron', function(){

    // only launch in development
    if(isDevelopment()) {
      gulp.start('watch', function() {
        console.log('Listening for changes');
      });
    } else {
      console.log('build installation');
    }

  });
});

gulp.task('package', function(callback) {

  /**
   * Escape regex expression
   * Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters
   * @param  {String} string
   * @return {String}
   */
  var escapeRegExp = function(string){
    return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
  };

  // var ignoreList = [
  //   '/.git',
  //   '/tasks',
  //   '/sample-build.json'
  // ];

  // // Add development node modules to ignore list
  // if(typeof pkg.devDependencies) {
  //   var devDependencies = Object.keys(pkg.devDependencies);

  //   devDependencies.map(function(devPkg) {
  //     ignoreList.push('/node_modules/' + devPkg);
  //   });
  // };

  // // Escape regex for all ignored files
  // ignoreList = ignoreList.map(function(ignore) {
  //   return escapeRegExp(ignore)
  // });

  var opts = {
    dir: OUT_BASE,
    // ignore: new RegExp(ignoreList.join('|'), 'i'),
    name: pkg.appName,
    out: OUT_BUILD,
    platform: 'darwin',
    arch: 'x64',
    version: '0.30.4',
    overwrite: true,
    protocols: [
      {
        name: pkg.appName,
        schemes: [pkg.name]
      }
    ]
  };

  packager(opts, function(err, appPath) {
    callback(null);
  });
});

gulp.task('watch', function () {

  // bower.json
  // package.json
  gulp.watch(IN.FONTS + '**/*', ['fonts']);
  gulp.watch(IN.IMG + '**/*', ['images']);
  gulp.watch(IN.JS + '**/*.{js,jsx}', ['js']);
  gulp.watch(IN.CSS + '**/*.scss', ['styles']);
  gulp.watch(IN.HTML + '**/*.html', ['html']);
});
<|endoftext|>


<commit_before>var ticketController = angular.module('ticket.controllers', []);

ticketController.controller('ticketCtrl', function($state, $scope, ticketAPIservice, $http) {

  ticketAPIservice.getTicket().success(function(response, status) {
    $scope.ticketList = response;
  });

  $scope.gotoTicketDetail = function(id, title) {
    $state.go('detail',{id: id, title: title});
    console.log("it's ticket detail");
  };

});

ticketController.controller('ticketDetailCtrl', function($state, $scope, ticketAPIservice, $stateParams) {

  var id = $stateParams.id;
  $scope.staffModel = {};

  ticketAPIservice.getTicketDetail(id).success(function(response, status) {
    $scope.ticketDetail = response;
    ticketAPIservice.getClientDetail(response.customer).success(function(response, status) {
      $scope.clientDetail = response;
    });
    if (response.staff != null) {
      ticketAPIservice.getStaffDetail(response.staff).success(function(response, status) {
        $scope.staffDetail = response;
      });
    }
    else{
      ticketAPIservice.getStaff().success(function(response, status) {
        $scope.staffList = response;
        console.log($scope.staffList);
      });
    }
    var params = $scope.ticketDetail;

    $scope.assignTo = function(obj){
      params.staff = obj.id;
      params.status = "a";
      console.log(params);
      ticketAPIservice.resolveTicket(id, params);
    };
    $scope.solved = function(){
      params.resolved = true;
      params.status = 'c';
      ticketAPIservice.resolveTicket(id, params);
    };
  });
});

ticketController.controller('ticketCreateCtrl', function($state, $scope, ticketAPIservice){

  $scope.ticketModel = {};
  $scope.customerModel = {};
  var customer = $scope.customerModel;
  var params = $scope.ticketModel;

  $scope.createNewTicket = function(){
    customer.contact = "+91" + $scope.customerModel.contact;
    ticketAPIservice.postCustomerDetail(customer).success(function(response, status) {
      params.customer = response.id;
      ticketAPIservice.postTicketDetail(params).success(function(response, status) {
        console.log('created successfully');
      });
    })
  };

});
<commit_msg>changing .success to .then() | hence the response will be changed to response.data<commit_after>var ticketController = angular.module('ticket.controllers', []);

ticketController.controller('ticketCtrl', function($state, $scope, ticketAPIservice) {

  ticketAPIservice.getTicket().then(function(response) {
    $scope.ticketList = response.data;
  });

  $scope.gotoTicketDetail = function(id, title) {
    $state.go('detail',{id: id, title: title});
    console.log("it's ticket detail");
  };

});

ticketController.controller('ticketDetailCtrl', function($state, $scope, ticketAPIservice, $stateParams) {

  var id = $stateParams.id;
  $scope.staffModel = {};

  ticketAPIservice.getTicketDetail(id).then(function(response) {
    $scope.ticketDetail = response.data;
    ticketAPIservice.getClientDetail(response.data.customer).then(function(response) {
      $scope.clientDetail = response.data;
    });
    if (response.data.staff != null) {
      ticketAPIservice.getStaffDetail(response.data.staff).then(function(response) {
        $scope.staffDetail = response.data;
      });
    }
    else{
      ticketAPIservice.getStaff().then(function(response) {
        $scope.staffList = response.data;
        console.log($scope.staffList);
      });
    }
    var params = $scope.ticketDetail;

    $scope.assignTo = function(obj){
      params.staff = obj.id;
      params.status = "a";
      console.log(params);
      ticketAPIservice.resolveTicket(id, params);
    };
    $scope.solved = function(){
      params.resolved = true;
      params.status = 'c';
      ticketAPIservice.resolveTicket(id, params);
    };
  });
});

ticketController.controller('ticketCreateCtrl', function($state, $scope, ticketAPIservice){

  $scope.ticketModel = {};
  $scope.customerModel = {};
  var customer = $scope.customerModel;
  var params = $scope.ticketModel;

  $scope.createNewTicket = function(){
    customer.contact = "+91" + $scope.customerModel.contact;
    ticketAPIservice.postCustomerDetail(customer).then(function(response) {
      params.customer = response.data.id;
      ticketAPIservice.postTicketDetail(params).then(function(response) {
        console.log('created thenfully');
      });
    })
  };

});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserify = require('browserify');
var watchify = require('watchify');
var remapify = require('remapify');
var source = require('vinyl-source-stream');
var stylish = require('jshint-stylish');
var path = require('path');
var merge = require('merge-stream');
var buffer = require('vinyl-buffer');

var browserSync = require('browser-sync');
var reload = browserSync.reload;

var api = require('./api/api');

gulp.task('clean', function() {
  return gulp.src('app/tmp', {read: false})
    .pipe($.plumber())
    .pipe($.clean());
});

gulp.task('html', function() {
  return gulp.src('./src/index.html')
    .pipe($.plumber())
    .pipe(gulp.dest('./dist'));
});

gulp.task('styles', function() {
  return gulp.src('./src/main.less')
    .pipe($.less())
    .pipe($.autoprefixer())
    .pipe($.rename('bundle.css'))
    .pipe(gulp.dest('./dist'))
    .pipe(reload({ stream: true }));
});

var bundler;
function getBundler() {
  if (!bundler) {
    bundler = watchify(browserify('./src/main.js', { debug: true }), watchify.args);

    bundler.plugin(remapify, [{
      src: '**/*.js',
      expose: 'src',
      cwd: path.join(__dirname, 'src')
    }]);
  }
  return bundler;
};

function bundle() {
  return getBundler().bundle()
    .on('error', $.util.log)
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe($.sourcemaps.init({ loadMaps: true }))
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest('./dist'))
    .pipe(reload({ stream: true }));
}

gulp.task('scripts', function() {
  process.env.BROWSERIFYSWAP_ENV = 'dist';
  return bundle();
});

gulp.task('jshint', function() {
  return gulp.src(['./src/**/*.js', './test/**/*.js'])
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter(stylish));
});

gulp.task('symlink', function() {
  return gulp.src('./src')
    .pipe($.plumber())
    .pipe($.symlink('./node_modules'));
});

var reporter = 'spec';

gulp.task('mocha', ['jshint', 'symlink'], function() {
  return gulp.src([
    './test/setup/node.js',
    './test/setup/helpers.js',
    './test/unit/**/*.js'
  ], { read: false })
    .pipe($.plumber())
    .pipe($.mocha({ reporter: reporter }));
});

gulp.task('build', [
  'clean',
  'html',
  'styles',
  'scripts',
  'test'
]);

gulp.task('test', [
  'jshint',
  'mocha'
]);

gulp.task('watch', ['build'], function() {
  browserSync({
    server: {
      baseDir: 'dist',
      middleware: function(req, res, next) {
        api(req, res, next);
      }
    }
  });

  reporter = 'dot';
  getBundler().on('update', function() {
    gulp.start('scripts');
    gulp.start('test');
  });
  gulp.watch('./test/**/*.js', ['test']);
});

gulp.task('default', ['watch']);
<commit_msg>Fix watchify in gulp<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserify = require('browserify');
var watchify = require('watchify');
var remapify = require('remapify');
var source = require('vinyl-source-stream');
var stylish = require('jshint-stylish');
var path = require('path');
var merge = require('merge-stream');
var buffer = require('vinyl-buffer');
var _ = require('lodash');

var browserSync = require('browser-sync');
var reload = browserSync.reload;

var api = require('./api/api');

gulp.task('clean', function() {
  return gulp.src('app/tmp', {read: false})
    .pipe($.plumber())
    .pipe($.clean());
});

gulp.task('html', function() {
  return gulp.src('./src/index.html')
    .pipe($.plumber())
    .pipe(gulp.dest('./dist'));
});

gulp.task('styles', function() {
  return gulp.src('./src/main.less')
    .pipe($.less())
    .pipe($.autoprefixer())
    .pipe($.rename('bundle.css'))
    .pipe(gulp.dest('./dist'))
    .pipe(reload({ stream: true }));
});

var bundler;
function getBundler() {
  if (!bundler) {
    bundler = watchify(browserify('./src/main.js', _.extend({ debug: true }, watchify.args)));

    bundler.plugin(remapify, [{
      src: '**/*.js',
      expose: 'src',
      cwd: path.join(__dirname, 'src')
    }]);
  }
  return bundler;
};

function bundle() {
  return getBundler().bundle()
    .on('error', $.util.log)
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe($.sourcemaps.init({ loadMaps: true }))
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest('./dist'))
    .pipe(reload({ stream: true }));
}

gulp.task('scripts', function() {
  process.env.BROWSERIFYSWAP_ENV = 'dist';
  return bundle();
});

gulp.task('jshint', function() {
  return gulp.src(['./src/**/*.js', './test/**/*.js'])
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter(stylish));
});

gulp.task('symlink', function() {
  return gulp.src('./src')
    .pipe($.plumber())
    .pipe($.symlink('./node_modules'));
});

var reporter = 'spec';

gulp.task('mocha', ['jshint', 'symlink'], function() {
  return gulp.src([
    './test/setup/node.js',
    './test/setup/helpers.js',
    './test/unit/**/*.js'
  ], { read: false })
    .pipe($.plumber())
    .pipe($.mocha({ reporter: reporter }));
});

gulp.task('build', [
  'clean',
  'html',
  'styles',
  'scripts',
  'test'
]);

gulp.task('test', [
  'jshint',
  'mocha'
]);

gulp.task('watch', ['build'], function() {
  browserSync({
    server: {
      baseDir: 'dist',
      middleware: function(req, res, next) {
        api(req, res, next);
      }
    }
  });

  reporter = 'dot';
  getBundler().on('update', function() {
    gulp.start('scripts');
    gulp.start('test');
  });
  gulp.watch('./test/**/*.js', ['test']);
});

gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>class PortfolioIndexService {
  constructor () {
    'ngInject';

    this.data = [
      {
        title : 'Sony Wheel',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'Haygarth digital room',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'YSL Rock Chick',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'Layla Moran',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'Lambeth Advice Centre',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'The Association of Lancastrians in London',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'EUFN',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'Haygarth',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'Sony Demo Bay',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'Gulp emails',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'Think Differently',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'Waterleaf',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      },
      {
        title : 'AMBR Media',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg'
      }
    ];
  }

  getPortfolioIndexContent() {
    return this.data;
  }
}

export default PortfolioIndexService;
<commit_msg>App project links<commit_after>class PortfolioIndexService {
  constructor () {
    'ngInject';

    this.data = [
      {
        title : 'Sony Wheel',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'sony-wheel'
      },
      {
        title : 'Haygarth digital room',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'haygarth-digital-room'
      },
      {
        title : 'YSL Rock Chick',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'ysl-rock-chick'
      },
      {
        title : 'Layla Moran',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'layla-moran'
      },
      {
        title : 'Lambeth Advice Centre',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'lambeth-advice-centre'
      },
      {
        title : 'The Association of Lancastrians in London',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'lancastrians'
      },
      {
        title : 'EUFN',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'eufn'
      },
      {
        title : 'Haygarth',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'haygarth'
      },
      {
        title : 'Sony Demo Bay',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'sony-demo-bay'
      },
      {
        title : 'Gulp emails',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'gulp-emails'
      },
      {
        title : 'Think Differently',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'think-differently'
      },
      {
        title : 'Waterleaf',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'waterleaf'
      },
      {
        title : 'AMBR Media',
      	image : 'assets/images/saladin-logo-dark-with-diamond.svg',
        state  : 'ambr'
      }
    ];
  }

  getPortfolioIndexContent() {
    return this.data;
  }
}

export default PortfolioIndexService;
<|endoftext|>


<commit_before>
import React from 'react';
import { render } from 'react-dom';
import qs from 'qs';
import xhr from 'xhr';
import Select from 'react-select';
import {RaisedButton} from 'material-ui';
import _ from 'lodash';
import AceEditor from 'react-ace';
import brace from 'brace';
import 'brace/mode/javascript';
import 'brace/theme/monokai';
export default class Repos extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            branches: "",
            file: "",
            currentBranch: ""
        }
    }
    _authenticate() {
        const code = this.props.location.query.code;
        xhr({
            url: 'https://fork-explorer-lh.herokuapp.com/authenticate/' + code,
            json: true
        }, (err, req, body) => {
            console.log('re-authentication successful');
            window.localStorage.token = body.token;
        });
    }
    componentWillMount() {
        if (!window.localStorage.token || window.localStorage.token === 'undefined') {
            this._authenticate()
        }
    }

    _fetchUserData(params) {
        xhr({
            url: 'https://api.github.com/user',
            json: true,
            headers: {
               Authorization: 'token ' + window.localStorage.token
            }
        }, (err, req, body) => {
            console.log('data fetching successful');
            console.log('req');
            console.log(req);
            console.log('body');
            console.log(body)
        });
    }

    _fetchUserFile(params) {
        let selectedBranch =  this.state.currentBranch === "" ? 'master' : this.state.currentBranch;
        xhr({
            url: 'https://api.github.com/repos/hackreactor/2015-11-toy-problems/contents/primeTester/primeTester.js?'+
            qs.stringify({
                ref: selectedBranch
            }),
            json: true,
            headers: {
                Authorization: 'token ' + window.localStorage.token
            }
        }, (err, req, body) => {
            console.log('data fetching successful');
            //console.log('req');
            //console.log(req);
            //console.log('body');
            //console.log(body);
            //console.log(window.atob(body.content))
            console.log(body)
            this.setState({
                file: window.atob(body.content)
            })
        });
    }

    _fetchBranches (params) {
        xhr({
            url: 'https://api.github.com/repos/hackreactor/2015-11-toy-problems/branches?page=1&per_page=100',
            json: true,
            headers: {
                Authorization: 'token ' + window.localStorage.token
            }
        }, (err, req, body) => {
            console.log('data fetching successful');
            //console.log('req');
            //console.log(req);
            //console.log('body');
            //console.log(body);
            console.log(body)
            let branches = body.map((x) => x.name)
            this.setState({
                branches: branches
            });
        });
    }
    _onSelectBranch (val) {
        this.setState({
            currentBranch: val
        })
    }
    render() {
        let branchSelections = [{value: 'none', label: 'no branches'}]
        if (this.state.branches !== "") {
            branchSelections = _.map(this.state.branches, (d) => {
                return { value: d, label: d}
            })
        }
        return (

 Welcome!

 Selected Branch: {this.state.currentBranch}

                <RaisedButton label="fetch user data" onClick={this._fetchUserData.bind(this)}/>
                <RaisedButton label="fetch file data" onClick={this._fetchUserFile.bind(this)}/>
                <RaisedButton label="fetch branches" onClick={this._fetchBranches.bind(this)}/>

                    <Select name="some-branches"
                            placeholder="pick a branch"
                            options={branchSelections}
                            onChange={this._onSelectBranch.bind(this) }/>

code

                <AceEditor
                  mode="javascript"
                  theme="monokai"
                  name="ace"
                  height="50em"
                  width="100em"
                  value={this.state.file}
                />

        )
    }
}
<commit_msg>more code cleanup<commit_after>
import React from 'react';
import { render } from 'react-dom';
import qs from 'qs';
import xhr from 'xhr';
import Select from 'react-select';
import {RaisedButton} from 'material-ui';
import _ from 'lodash';
import AceEditor from 'react-ace';
import brace from 'brace';
import 'brace/mode/javascript';
import 'brace/theme/monokai';
export default class Repos extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            branches: "",
            file: "",
            currentBranch: ""
        }
    }
    _authenticate() {
        const code = this.props.location.query.code;
        xhr({
            url: 'https://fork-explorer-lh.herokuapp.com/authenticate/' + code,
            json: true
        }, (err, req, body) => {
            console.log('re-authentication successful');
            window.localStorage.token = body.token;
        });
    }
    componentWillMount() {
        if (!window.localStorage.token || window.localStorage.token === 'undefined') {
            this._authenticate()
        }
    }

    _fetchUserData(params) {
        xhr({
            url: 'https://api.github.com/user',
            json: true,
            headers: {
               Authorization: 'token ' + window.localStorage.token
            }
        }, (err, req, body) => {
            console.log('data fetching successful');
            console.log('req');
            console.log(req);
            console.log('body');
            console.log(body)
        });
    }

    _fetchUserFile(params) {
        let selectedBranch =  this.state.currentBranch === "" ? 'master' : this.state.currentBranch;
        xhr({
            url: 'https://api.github.com/repos/hackreactor/2015-11-toy-problems/contents/primeTester/primeTester.js?'+
            qs.stringify({
                ref: selectedBranch
            }),
            json: true,
            headers: {
                Authorization: 'token ' + window.localStorage.token
            }
        }, (err, req, body) => {
            console.log('data fetching successful');
            this.setState({
                file: window.atob(body.content)
            })
        });
    }

    _fetchBranches (params) {
        xhr({
            url: 'https://api.github.com/repos/hackreactor/2015-11-toy-problems/branches?page=1&per_page=100',
            json: true,
            headers: {
                Authorization: 'token ' + window.localStorage.token
            }
        }, (err, req, body) => {
            console.log('data fetching successful');
            //console.log('req');
            //console.log(req);
            //console.log('body');
            //console.log(body);
            console.log(body)
            let branches = body.map((x) => x.name)
            this.setState({
                branches: branches
            });
        });
    }
    _onSelectBranch (val) {
        this.setState({
            currentBranch: val
        })
    }
    render() {
        let branchSelections = [{value: 'none', label: 'no branches'}];
        if (this.state.branches !== "") {
            branchSelections = _.map(this.state.branches, (d) => {
                return { value: d, label: d}
            })
        }
        return (

 Welcome!

 Selected Branch: {this.state.currentBranch}

                <RaisedButton label="fetch user data" onClick={this._fetchUserData.bind(this)}/>
                <RaisedButton label="fetch file data" onClick={this._fetchUserFile.bind(this)}/>
                <RaisedButton label="fetch branches" onClick={this._fetchBranches.bind(this)}/>

                    <Select name="some-branches"
                            placeholder="pick a branch"
                            options={branchSelections}
                            onChange={this._onSelectBranch.bind(this) }/>

code

                <AceEditor
                  mode="javascript"
                  theme="monokai"
                  name="ace"
                  height="50em"
                  width="100em"
                  value={this.state.file}
                />

        )
    }
}
<|endoftext|>