<commit_before>//How big the grid is in pixels
var gridWidthPx = 800, gridHeightPx = 448;
var gridPx = 32;

//Grid size in actual units
var gridWidth = gridWidthPx / gridPx;
var gridHeight = gridHeightPx / gridPx;

//Storage for the current agents and obstacles
var agents = new Array();
var obstacles = new Array();

//Defines an agent that moves
Agent = function (pos) {
	this.position = pos;
	this.rotation = 0;

	this.velocity = Vector2.zero;

	this.maxForce = 5; //rate of acceleration
	this.maxSpeed = 4; //grid squares / second

	this.radius = 0.5;
	this.minSeparation = 0.8; // We'll move away from anyone nearer than this

	this.maxCohesion = 5.5; //We'll move closer to anyone within this bound
};

var destination = new Vector2(gridWidth - 2, gridHeight / 2); //middle right

//Called to start the game
function startGame() {
	agents.push(new Agent(new Vector2(1, gridHeight - 2)));
	agents.push(new Agent(new Vector2(1, gridHeight - 3)));
	agents.push(new Agent(new Vector2(1, gridHeight - 4)));
	agents.push(new Agent(new Vector2(1, gridHeight - 5)));

	agents.push(new Agent(new Vector2(2, gridHeight - 3)));
	agents.push(new Agent(new Vector2(2, gridHeight - 4)));
	agents.push(new Agent(new Vector2(2, gridHeight - 5)));

	stage.addEventListener('stagemouseup', function (ev) {
		destination.x = ev.stageX / gridPx - 0.5;
		destination.y = ev.stageY / gridPx - 0.5;
	});
}

function round(val) {
	return val.toFixed(1);
}

//called periodically to update the game
//dt is the change of time since the last update (in seconds)
function gameTick(dt) {
	var i, agent;

	//Calculate steering and flocking forces for all agents
	for (i = agents.length - 1; i >= 0; i--) {
		agent = agents[i];

		//Work out our behaviours
		var seek = steeringBehaviourSeek(agent, destination);
		var separation = steeringBehaviourSeparation(agent);
		var cohesion = steeringBehaviourCohesion(agent);
		var alignment = steeringBehaviourAlignment(agent);

		//if (i == 0) {
		//	console.log(round(seek.length()) + ' ' + round(separation.length()) + ' ' + round(cohesion.length()) + ' ' + round(alignment.length()) + ' : ' + round(agent.velocity.length()));
		//}

		//If there is significant separation going on, don't apply cohesion as they'll just fight each other
		if (separation.length() > 3) {
			cohesion = Vector2.zero;
		}

		agent.forceToApply = seek.plus(separation).plus(cohesion.mul(0.1)).plus(alignment).mul(dt);
	}

	//Move agents based on forces being applied (aka physics)
	for (i = agents.length - 1; i >= 0; i--) {
		agent = agents[i];

		//if (i == 0) {
		//	console.log(round(agent.velocity.length()) + ' ' + round(agent.velocity.x) + ',' + round(agent.velocity.y) + '    ' + round(agent.forceToApply.x) + ',' + round(agent.forceToApply.y));
		//}

		//Apply the force
		agent.velocity = agent.velocity.plus(agent.forceToApply);

		//Cap speed as required
		var speed = agent.velocity.length();
		if (speed > agent.maxSpeed) {
			agent.velocity = agent.velocity.mul(agent.maxSpeed / speed);
		}

		//Calculate our new movement angle
		agent.rotation = agent.velocity.angle();

		//Move a bit
		agent.position = agent.position.plus(agent.velocity.mul(dt));
	}
}

function steeringBehaviourSeek(agent, dest) {

	//Desired change of location
	var desired = dest.minus(agent.position);
	//Desired velocity (move there at maximum speed)
	desired = desired.mul(agent.maxSpeed / desired.length());
	//The velocity change we want
	var velocityChange = desired.minus(agent.velocity);
	//Convert to a force
	return velocityChange.mul(agent.maxForce / agent.maxSpeed);
}

function steeringBehaviourSeparation(agent) {
	var totalForce = Vector2.zero;
	var neighboursCount = 0;

	for (var i = 0; i < agents.length; i++) {
		var a = agents[i];
		if (a != agent) {
			var distance = agent.position.distanceTo(a.position);
			if (distance < agent.minSeparation && distance > 0) {
				//Vector to other agent
				var pushForce = agent.position.minus(a.position);
				totalForce = totalForce.plus(pushForce.div(agent.radius));
				neighboursCount++;
			}
		}
	}

	if (neighboursCount == 0) {
		return Vector2.zero;
	}

	totalForce = totalForce.div(neighboursCount);
	return totalForce.mul(agent.maxForce);
}

function steeringBehaviourCohesion(agent) {
	var centerOfMass = agent.position;
	var neighboursCount = 1;

	for (var i = 0; i < agents.length; i++) {
		var a = agents[i];
		if (a != agent) {
			var distance = agent.position.distanceTo(a.position);
			if (distance < agent.maxCohesion) {
				centerOfMass = centerOfMass.plus(a.position);
				neighboursCount++;
			}
		}
	}

	if (neighboursCount == 1) {
		return Vector2.zero;
	}

	centerOfMass = centerOfMass.div(neighboursCount);

	return steeringBehaviourSeek(agent, centerOfMass);
}

function steeringBehaviourAlignment(agent) {
	var averageHeading = agent.velocity.length() == 0 ? Vector2.zero : agent.velocity.normalize();
	var neighboursCount = 1;

	for (var i = 0; i < agents.length; i++) {
		var a = agents[i];
		if (a != agent) {
			var distance = agent.position.distanceTo(a.position);
			if (distance < agent.maxCohesion) {
				averageHeading = averageHeading.plus(a.velocity.length() == 0 ? Vector2.zero : a.velocity.normalize());
				neighboursCount++;
			}
		}
	}

	if (neighboursCount == 0) {
		return Vector2.zero;
	}

	averageHeading = averageHeading.div(neighboursCount);

	var desired = averageHeading.mul(agent.maxSpeed);
	var force = desired.minus(agent.velocity);
	return force.mul(agent.maxForce / agent.maxSpeed);
}<commit_msg>More comments and simplification of flocking<commit_after>//How big the grid is in pixels
var gridWidthPx = 800, gridHeightPx = 448;
var gridPx = 32;

//Grid size in actual units
var gridWidth = gridWidthPx / gridPx;
var gridHeight = gridHeightPx / gridPx;

//Storage for the current agents and obstacles
var agents = new Array();
var obstacles = new Array();

//Defines an agent that moves
Agent = function (pos) {
	this.position = pos;
	this.rotation = 0;

	this.velocity = Vector2.zero;

	this.maxForce = 5; //rate of acceleration
	this.maxSpeed = 4; //grid squares / second

	this.radius = 0.4;
	this.minSeparation = 0.8; // We'll move away from anyone nearer than this

	this.maxCohesion = 5.5; //We'll move closer to anyone within this bound
};

var destination = new Vector2(gridWidth - 2, gridHeight / 2); //middle right

//Called to start the game
function startGame() {
	agents.push(new Agent(new Vector2(1, gridHeight - 2)));
	agents.push(new Agent(new Vector2(1, gridHeight - 3)));
	agents.push(new Agent(new Vector2(1, gridHeight - 4)));
	agents.push(new Agent(new Vector2(1, gridHeight - 5)));

	agents.push(new Agent(new Vector2(2, gridHeight - 3)));
	agents.push(new Agent(new Vector2(2, gridHeight - 4)));
	agents.push(new Agent(new Vector2(2, gridHeight - 5)));

	stage.addEventListener('stagemouseup', function (ev) {
		destination.x = ev.stageX / gridPx - 0.5;
		destination.y = ev.stageY / gridPx - 0.5;
	});
}

function round(val) {
	return val.toFixed(1);
}

//called periodically to update the game
//dt is the change of time since the last update (in seconds)
function gameTick(dt) {
	var i, agent;

	//Calculate steering and flocking forces for all agents
	for (i = agents.length - 1; i >= 0; i--) {
		agent = agents[i];

		//Work out our behaviours
		var seek = steeringBehaviourSeek(agent, destination);
		var separation = steeringBehaviourSeparation(agent);
		var cohesion = steeringBehaviourCohesion(agent);
		var alignment = steeringBehaviourAlignment(agent);

		//if (i == 0) {
		//	console.log(round(seek.length()) + ' ' + round(separation.length()) + ' ' + round(cohesion.length()) + ' ' + round(alignment.length()) + ' : ' + round(agent.velocity.length()));
		//}

		//Combine them to come up with a total force to apply, decreasing the effect of cohesion
		agent.forceToApply = seek.plus(separation).plus(cohesion.mul(0.1)).plus(alignment);
	}

	//Move agents based on forces being applied (aka physics)
	for (i = agents.length - 1; i >= 0; i--) {
		agent = agents[i];

		//if (i == 0) {
		//	console.log(round(agent.velocity.length()) + ' ' + round(agent.velocity.x) + ',' + round(agent.velocity.y) + '    ' + round(agent.forceToApply.x) + ',' + round(agent.forceToApply.y));
		//}

		//Apply the force
		agent.velocity = agent.velocity.plus(agent.forceToApply.mul(dt));

		//Cap speed as required
		var speed = agent.velocity.length();
		if (speed > agent.maxSpeed) {
			agent.velocity = agent.velocity.mul(agent.maxSpeed / speed);
		}

		//Calculate our new movement angle
		agent.rotation = agent.velocity.angle();

		//Move a bit
		agent.position = agent.position.plus(agent.velocity.mul(dt));
	}
}

function steeringBehaviourSeek(agent, dest) {

	//Desired change of location
	var desired = dest.minus(agent.position);
	//Desired velocity (move there at maximum speed)
	desired = desired.mul(agent.maxSpeed / desired.length());
	//The velocity change we want
	var velocityChange = desired.minus(agent.velocity);
	//Convert to a force
	return velocityChange.mul(agent.maxForce / agent.maxSpeed);
}

function steeringBehaviourSeparation(agent) {
	var totalForce = Vector2.zero;
	var neighboursCount = 0;

	for (var i = 0; i < agents.length; i++) {
		var a = agents[i];
		if (a != agent) {
			var distance = agent.position.distanceTo(a.position);
			if (distance < agent.minSeparation && distance > 0) {
				//Vector to other agent
				var pushForce = agent.position.minus(a.position);
				totalForce = totalForce.plus(pushForce.div(agent.radius));
				neighboursCount++;
			}
		}
	}

	if (neighboursCount == 0) {
		return Vector2.zero;
	}

	totalForce = totalForce.div(neighboursCount);
	return totalForce.mul(agent.maxForce);
}

function steeringBehaviourCohesion(agent) {
	//Start with just our position
	var centerOfMass = agent.position;
	var neighboursCount = 1;

	for (var i = 0; i < agents.length; i++) {
		var a = agents[i];
		if (a != agent) {
			var distance = agent.position.distanceTo(a.position);
			if (distance < agent.maxCohesion) {
				//sum up the position of our neighbours
				centerOfMass = centerOfMass.plus(a.position);
				neighboursCount++;
			}
		}
	}

	if (neighboursCount == 1) {
		return Vector2.zero;
	}

	//Get the average position of ourself and our neighbours
	centerOfMass = centerOfMass.div(neighboursCount);

	//seek that position
	return steeringBehaviourSeek(agent, centerOfMass);
}

function steeringBehaviourAlignment(agent) {
	var averageHeading = Vector2.zero;
	var neighboursCount = 0;

	//for each of our neighbours (including ourself)
	for (var i = 0; i < agents.length; i++) {
		var a = agents[i];
		var distance = agent.position.distanceTo(a.position);
		//That are within the max distance and are moving
		if (distance < agent.maxCohesion && a.velocity.length() > 0) {
			//Sum up our headings
			averageHeading = averageHeading.plus(a.velocity.normalize());
			neighboursCount++;
		}
	}

	if (neighboursCount == 0) {
		return Vector2.zero;
	}

	//Divide to get the average heading
	averageHeading = averageHeading.div(neighboursCount);

	//Steer towards that heading
	var desired = averageHeading.mul(agent.maxSpeed);
	var force = desired.minus(agent.velocity);
	return force.mul(agent.maxForce / agent.maxSpeed);
}<|endoftext|>


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

    var path = require('path');

	// Load the package JSON file
	var pkg = grunt.file.readJSON('package.json');

	// get the root path of the project
	var projectRoot = 'src/' + pkg.name + '/';

	// Load information about the assembly
	var assembly = grunt.file.readJSON(projectRoot + 'Properties/AssemblyInfo.json');

	// Get the version of the package
	var version = assembly.informationalVersion ? assembly.informationalVersion : assembly.version;

	var os = require("os");
	var machineName = os.hostname();

	grunt.initConfig({
		pkg: pkg,
		clean: {
			files: [
				'releases/temp/**/*.*'
			]
		},
		copy: {
			binary: {
				files: [
					{
						expand: true,
						cwd: projectRoot + 'bin/',
						src: [
							pkg.name + '.dll',
							pkg.name + '.xml'
						],
						dest: 'releases/temp/bin/'
					}
				]
			},
			resources: {
			    files: [
					{
					    expand: true,
					    cwd: projectRoot + 'App_Plugins/' + pkg.name + '/',
					    src: ['**/*.*'],
					    dest: 'releases/temp/App_Plugins/' + pkg.name + '/'
					}
				]
			},
			nuget: {
			    files: [
					{
					    expand: true,
					    cwd: 'releases/nuget/',
					    src: [pkg.name + '.' + version + '.nupkg'],
					    dest: 'D:/NuGet/'
					}
				]
			}
		},
		nugetpack: {
			dist: {
				src: 'src/' + pkg.name + '/' + pkg.name + '.csproj',
				dest: 'releases/nuget/'
			}
		},
		zip: {
			release: {
			    router: function (filepath) {
			        var name = path.basename(filepath);
			        return name == 'LICENSE.html' ? name : filepath.replace('releases/temp/', '');
			    },
				src: [
					'releases/temp/**/*.*',
					projectRoot + '/LICENSE.html'
				],
				dest: 'releases/github/' + pkg.name + '.v' + version + '.zip'
			}
		},
		umbracoPackage: {
		    dist: {
		        src: 'releases/temp/',
		        dest: 'releases/umbraco',
		        options: {
		            name: pkg.name,
		            version: version,
		            url: pkg.url,
		            license: pkg.license.name,
		            licenseUrl: pkg.license.url,
		            author: pkg.author.name,
		            authorUrl: pkg.author.url,
		            readme: pkg.readme,
		            outputName: pkg.name + '.v' + version + '.zip'
		        }
		    }
		}
	});

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-nuget');
	grunt.loadNpmTasks('grunt-zip');
	grunt.loadNpmTasks('grunt-umbraco-package');

	grunt.registerTask('dev', ['clean', 'copy:binary', 'copy:resources', 'nugetpack', 'zip', 'umbracoPackage']);

	if (machineName == 'abjerner2') {
		grunt.registerTask('test', ['clean', 'copy:binary', 'copy:resources', 'nugetpack', 'zip', 'umbracoPackage', 'copy:nuget']);
	}

	grunt.registerTask('default', ['dev']);

};<commit_msg>#H5IS<commit_after>module.exports = function (grunt) {

    var path = require('path');

	// Load the package JSON file
	var pkg = grunt.file.readJSON('package.json');

	// get the root path of the project
	var projectRoot = 'src/' + pkg.name + '/';

	// Load information about the assembly
	var assembly = grunt.file.readJSON(projectRoot + 'Properties/AssemblyInfo.json');

	// Get the version of the package
	var version = assembly.informationalVersion ? assembly.informationalVersion : assembly.version;

	var os = require("os");
	var machineName = os.hostname();

	grunt.initConfig({
		pkg: pkg,
		clean: {
			files: [
				'releases/temp/**/*.*'
			]
		},
		copy: {
			binary: {
				files: [
					{
						expand: true,
						cwd: projectRoot + 'bin/',
						src: [
							pkg.name + '.dll',
							pkg.name + '.xml',
							'Skybrud.Umbraco.GridData.dll',
							'Skybrud.Umbraco.GridData.xml'
						],
						dest: 'releases/temp/bin/'
					}
				]
			},
			resources: {
			    files: [
					{
					    expand: true,
					    cwd: projectRoot + 'App_Plugins/' + pkg.name + '/',
					    src: ['**/*.*'],
					    dest: 'releases/temp/App_Plugins/' + pkg.name + '/'
					}
				]
			},
			nuget: {
			    files: [
					{
					    expand: true,
					    cwd: 'releases/nuget/',
					    src: [pkg.name + '.' + version + '.nupkg'],
					    dest: 'D:/NuGet/'
					}
				]
			}
		},
		nugetpack: {
			dist: {
				src: 'src/' + pkg.name + '/' + pkg.name + '.csproj',
				dest: 'releases/nuget/'
			}
		},
		zip: {
			release: {
			    router: function (filepath) {
			        var name = path.basename(filepath);
			        return name == 'LICENSE.html' ? name : filepath.replace('releases/temp/', '');
			    },
				src: [
					'releases/temp/**/*.*',
					projectRoot + '/LICENSE.html'
				],
				dest: 'releases/github/' + pkg.name + '.v' + version + '.zip'
			}
		},
		umbracoPackage: {
		    dist: {
		        src: 'releases/temp/',
		        dest: 'releases/umbraco',
		        options: {
		            name: pkg.name,
		            version: version,
		            url: pkg.url,
		            license: pkg.license.name,
		            licenseUrl: pkg.license.url,
		            author: pkg.author.name,
		            authorUrl: pkg.author.url,
		            readme: pkg.readme,
		            outputName: pkg.name + '.v' + version + '.zip'
		        }
		    }
		}
	});

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-nuget');
	grunt.loadNpmTasks('grunt-zip');
	grunt.loadNpmTasks('grunt-umbraco-package');

	grunt.registerTask('dev', ['clean', 'copy:binary', 'copy:resources', 'nugetpack', 'zip', 'umbracoPackage']);

	if (machineName == 'abjerner2') {
		grunt.registerTask('test', ['clean', 'copy:binary', 'copy:resources', 'nugetpack', 'zip', 'umbracoPackage', 'copy:nuget']);
	}

	grunt.registerTask('default', ['dev']);

};<|endoftext|>


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

})();<commit_msg>ES6 IIFE implemented<commit_after>{

}<|endoftext|>


<commit_before>/* Toggles selected option class, assumes the following structure
* .options > .block-label + .block-label > label > input[:radio || :checkbox]
*/

module.exports = (function() {

  var selectedOption = {},
  options = $('.options'),
  change_class = 'selected',
  focusblur_class = 'add-focus';

  selectedOption.init = function() {
    options.each(function(i, container){
      var input_group = $(container).find('.block-label');

      selectedOption.bindInputEvents(input_group);

    });
  };

  selectedOption.bindInputEvents = function(input_group) {
    input_group.each(function(i, blocklabel){
      var container = $(blocklabel),
      siblings = container.siblings().find('label'),
      input = container.find('input'),
      is_radio = input.is(':radio'),
      label = container.find('label');

      input.on('change', function(){
        var checked = input.is(':checked');

        if(checked && is_radio) {
          siblings.removeClass(change_class);
        }

        label.toggleClass(change_class, checked);

      })
      .on('focus', function(){
        label.addClass(focusblur_class);
      })
      .on('blur', function(){
        label.removeClass(focusblur_class);
      })
      .change();
    });
  };

  selectedOption.init();

  return selectedOption;

})();
<commit_msg>fixed some formatting in js file<commit_after>/* Toggles selected option class, assumes the following structure
* .options > .block-label + .block-label > label > input[:radio || :checkbox]
*/

module.exports = (function() {
  'use strict';

  var selectedOption = {},
    options = $('.options'),
    change_class = 'selected',
    focusblur_class = 'add-focus';

  selectedOption.init = function() {
    options.each(function(i, container){
      var input_group = $(container).find('.block-label');

      selectedOption.bindInputEvents(input_group);

    });
  };

  selectedOption.bindInputEvents = function(input_group) {
    input_group.each(function(i, blocklabel){
      var container = $(blocklabel),
        siblings = container.siblings().find('label'),
        input = container.find('input'),
        is_radio = input.is(':radio'),
        label = container.find('label');

      input.on('change', function(){
        var is_checked = input.is(':checked');

        if(is_checked && is_radio) {
          siblings.removeClass(change_class);
        }

        label.toggleClass(change_class, is_checked);

      })
      .on('focus', function(){
        label.addClass(focusblur_class);
      })
      .on('blur', function(){
        label.removeClass(focusblur_class);
      })
      .change();
    });
  };

  selectedOption.init();

  return selectedOption;

})();
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 * @emails oncall+relay
 */

'use strict';

const DataChecker = require('./DataChecker');
const RelayCore = require('./RelayCore');
const RelayDefaultHandlerProvider = require('../handlers/RelayDefaultHandlerProvider');
const RelayInMemoryRecordSource = require('./RelayInMemoryRecordSource');
const RelayModernQueryExecutor = require('./RelayModernQueryExecutor');
const RelayObservable = require('../network/RelayObservable');
const RelayPublishQueue = require('./RelayPublishQueue');

const invariant = require('invariant');
const normalizeRelayPayload = require('./normalizeRelayPayload');
const warning = require('warning');

import type {HandlerProvider} from '../handlers/RelayDefaultHandlerProvider';
import type {
  GraphQLResponse,
  Network,
  PayloadData,
  PayloadError,
  UploadableMap,
} from '../network/RelayNetworkTypes';
import type {
  Environment,
  OperationLoader,
  MissingFieldHandler,
  OperationDescriptor,
  OptimisticUpdate,
  NormalizationSelector,
  ReaderSelector,
  SelectorStoreUpdater,
  Snapshot,
  Store,
  StoreUpdater,
  UnstableEnvironmentCore,
  PublishQueue,
} from '../store/RelayStoreTypes';
import type {CacheConfig, Disposable} from '../util/RelayRuntimeTypes';
import type {TaskScheduler} from './RelayModernQueryExecutor';

export type EnvironmentConfig = {|
  +configName?: string,
  +handlerProvider?: HandlerProvider,
  +operationLoader?: OperationLoader,
  +network: Network,
  +scheduler?: TaskScheduler,
  +store: Store,
  +missingFieldHandlers?: $ReadOnlyArray<MissingFieldHandler>,
  +publishQueue?: PublishQueue,
|};

class RelayModernEnvironment implements Environment {
  _operationLoader: ?OperationLoader;
  _network: Network;
  _publishQueue: PublishQueue;
  _scheduler: ?TaskScheduler;
  _store: Store;
  configName: ?string;
  unstable_internal: UnstableEnvironmentCore;
  _missingFieldHandlers: ?$ReadOnlyArray<MissingFieldHandler>;

  constructor(config: EnvironmentConfig) {
    this.configName = config.configName;
    const handlerProvider = config.handlerProvider
      ? config.handlerProvider
      : RelayDefaultHandlerProvider;
    const operationLoader = config.operationLoader;
    if (__DEV__) {
      if (operationLoader != null) {
        invariant(
          typeof operationLoader === 'object' &&
            typeof operationLoader.get === 'function' &&
            typeof operationLoader.load === 'function',
          'RelayModernEnvironment: Expected `operationLoader` to be an object ' +
            'with get() and load() functions, got `%s`.',
          operationLoader,
        );
      }
    }
    this._operationLoader = operationLoader;
    this._network = config.network;
    this._publishQueue =
      config.publishQueue ??
      new RelayPublishQueue(config.store, handlerProvider);
    this._scheduler = config.scheduler ?? null;
    this._store = config.store;
    this.unstable_internal = RelayCore;

    (this: any).__setNet = newNet => (this._network = newNet);

    if (__DEV__) {
      const {inspect} = require('./StoreInspector');
      (this: any).DEBUG_inspect = (dataID: ?string) => inspect(this, dataID);
    }

    // Register this Relay Environment with Relay DevTools if it exists.
    // Note: this must always be the last step in the constructor.
    const _global =
      typeof global !== 'undefined'
        ? global
        : typeof window !== 'undefined'
        ? window
        : undefined;
    const devToolsHook = _global && _global.__RELAY_DEVTOOLS_HOOK__;
    if (devToolsHook) {
      devToolsHook.registerEnvironment(this);
    }
    if (config.missingFieldHandlers != null) {
      this._missingFieldHandlers = config.missingFieldHandlers;
    }
  }

  getStore(): Store {
    return this._store;
  }

  getNetwork(): Network {
    return this._network;
  }

  applyUpdate(optimisticUpdate: OptimisticUpdate): Disposable {
    const dispose = () => {
      this._publishQueue.revertUpdate(optimisticUpdate);
      this._publishQueue.run();
    };
    this._publishQueue.applyUpdate(optimisticUpdate);
    this._publishQueue.run();
    return {dispose};
  }

  revertUpdate(update: OptimisticUpdate): void {
    this._publishQueue.revertUpdate(update);
    this._publishQueue.run();
  }

  replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void {
    this._publishQueue.revertUpdate(update);
    this._publishQueue.applyUpdate(newUpdate);
    this._publishQueue.run();
  }

  applyMutation({
    operation,
    optimisticResponse,
    optimisticUpdater,
  }: {
    operation: OperationDescriptor,
    optimisticUpdater?: ?SelectorStoreUpdater,
    optimisticResponse?: Object,
  }): Disposable {
    return this.applyUpdate({
      operation,
      selectorStoreUpdater: optimisticUpdater,
      response: optimisticResponse || null,
    });
  }

  check(readSelector: NormalizationSelector): boolean {
    if (this._missingFieldHandlers == null) {
      return this._store.check(readSelector);
    }
    return this._checkSelectorAndHandleMissingFields(
      readSelector,
      this._missingFieldHandlers,
    );
  }

  commitPayload(
    operationDescriptor: OperationDescriptor,
    payload: PayloadData,
  ): void {
    // Do not handle stripped nulls when committing a payload
    const relayPayload = normalizeRelayPayload(
      operationDescriptor.root,
      payload,
    );
    this._publishQueue.commitPayload(operationDescriptor, relayPayload);
    this._publishQueue.run();
  }

  commitUpdate(updater: StoreUpdater): void {
    this._publishQueue.commitUpdate(updater);
    this._publishQueue.run();
  }

  lookup(readSelector: ReaderSelector, owner: ?OperationDescriptor): Snapshot {
    return this._store.lookup(readSelector, owner);
  }

  subscribe(
    snapshot: Snapshot,
    callback: (snapshot: Snapshot) => void,
  ): Disposable {
    return this._store.subscribe(snapshot, callback);
  }

  retain(selector: NormalizationSelector): Disposable {
    return this._store.retain(selector);
  }

  _checkSelectorAndHandleMissingFields(
    selector: NormalizationSelector,
    handlers: $ReadOnlyArray<MissingFieldHandler>,
  ): boolean {
    const target = new RelayInMemoryRecordSource();
    const result = DataChecker.check(
      this._store.getSource(),
      target,
      selector,
      handlers,
      this._operationLoader,
    );
    if (target.size() > 0) {
      this._publishQueue.commitSource(target);
      this._publishQueue.run();
    }
    return result;
  }

  /**
   * Returns an Observable of GraphQLResponse resulting from executing the
   * provided Query or Subscription operation, each result of which is then
   * normalized and committed to the publish queue.
   *
   * Note: Observables are lazy, so calling this method will do nothing until
   * the result is subscribed to: environment.execute({...}).subscribe({...}).
   */
  execute({
    operation,
    cacheConfig,
    updater,
  }: {
    operation: OperationDescriptor,
    cacheConfig?: ?CacheConfig,
    updater?: ?SelectorStoreUpdater,
  }): RelayObservable<GraphQLResponse> {
    return RelayObservable.create(sink => {
      const source = this._network.execute(
        operation.node.params,
        operation.variables,
        cacheConfig || {},
      );
      const executor = RelayModernQueryExecutor.execute({
        operation,
        operationLoader: this._operationLoader,
        optimisticUpdate: null,
        publishQueue: this._publishQueue,
        scheduler: this._scheduler,
        sink,
        source,
        updater,
      });
      return () => executor.cancel();
    });
  }

  /**
   * Returns an Observable of GraphQLResponse resulting from executing the
   * provided Mutation operation, the result of which is then normalized and
   * committed to the publish queue along with an optional optimistic response
   * or updater.
   *
   * Note: Observables are lazy, so calling this method will do nothing until
   * the result is subscribed to:
   * environment.executeMutation({...}).subscribe({...}).
   */
  executeMutation({
    operation,
    optimisticResponse,
    optimisticUpdater,
    updater,
    uploadables,
  }: {|
    operation: OperationDescriptor,
    optimisticUpdater?: ?SelectorStoreUpdater,
    optimisticResponse?: ?Object,
    updater?: ?SelectorStoreUpdater,
    uploadables?: ?UploadableMap,
  |}): RelayObservable<GraphQLResponse> {
    return RelayObservable.create(sink => {
      let optimisticUpdate;
      if (optimisticResponse || optimisticUpdater) {
        optimisticUpdate = {
          operation: operation,
          selectorStoreUpdater: optimisticUpdater,
          response: optimisticResponse ?? null,
        };
      }
      const source = this._network.execute(
        operation.node.params,
        operation.variables,
        {force: true},
        uploadables,
      );
      const executor = RelayModernQueryExecutor.execute({
        operation,
        operationLoader: this._operationLoader,
        optimisticUpdate,
        publishQueue: this._publishQueue,
        scheduler: this._scheduler,
        sink,
        source,
        updater,
      });
      return () => executor.cancel();
    });
  }

  /**
   * Returns an Observable of GraphQLResponse resulting from executing the
   * provided Query or Subscription operation responses, the result of which is
   * then normalized and comitted to the publish queue.
   *
   * Note: Observables are lazy, so calling this method will do nothing until
   * the result is subscribed to:
   * environment.executeWithSource({...}).subscribe({...}).
   */
  executeWithSource({
    operation,
    source,
  }: {|
    operation: OperationDescriptor,
    source: RelayObservable<GraphQLResponse>,
  |}): RelayObservable<GraphQLResponse> {
    return RelayObservable.create(sink => {
      const executor = RelayModernQueryExecutor.execute({
        operation,
        operationLoader: this._operationLoader,
        optimisticUpdate: null,
        publishQueue: this._publishQueue,
        sink,
        source,
      });
      return () => executor.cancel();
    });
  }

  /**
   * @deprecated Use Environment.execute().subscribe()
   */
  sendQuery({
    cacheConfig,
    onCompleted,
    onError,
    onNext,
    operation,
  }: {
    cacheConfig?: ?CacheConfig,
    onCompleted?: ?() => void,
    onError?: ?(error: Error) => void,
    onNext?: ?(payload: GraphQLResponse) => void,
    operation: OperationDescriptor,
  }): Disposable {
    warning(
      false,
      'environment.sendQuery() is deprecated. Update to the latest ' +
        'version of react-relay, and use environment.execute().',
    );
    return this.execute({operation, cacheConfig}).subscribeLegacy({
      onNext,
      onError,
      onCompleted,
    });
  }

  /**
   * @deprecated Use Environment.executeMutation().subscribe()
   */
  sendMutation({
    onCompleted,
    onError,
    operation,
    optimisticResponse,
    optimisticUpdater,
    updater,
    uploadables,
  }: {
    onCompleted?: ?(errors: ?Array<PayloadError>) => void,
    onError?: ?(error: Error) => void,
    operation: OperationDescriptor,
    optimisticUpdater?: ?SelectorStoreUpdater,
    optimisticResponse?: Object,
    updater?: ?SelectorStoreUpdater,
    uploadables?: UploadableMap,
  }): Disposable {
    warning(
      false,
      'environment.sendMutation() is deprecated. Update to the latest ' +
        'version of react-relay, and use environment.executeMutation().',
    );
    return this.executeMutation({
      operation,
      optimisticResponse,
      optimisticUpdater,
      updater,
      uploadables,
    }).subscribeLegacy({
      // NOTE: sendMutation has a non-standard use of onCompleted() by passing
      // it a value. When switching to use executeMutation(), the next()
      // Observer should be used to preserve behavior.
      onNext: payload => {
        onCompleted && onCompleted(payload.errors);
      },
      onError,
      onCompleted,
    });
  }

  toJSON(): mixed {
    return `RelayModernEnvironment(${this.configName ?? ''})`;
  }
}

// Add a sigil for detection by `isRelayModernEnvironment()` to avoid a
// realm-specific instanceof check, and to aid in module tree-shaking to
// avoid requiring all of RelayRuntime just to detect its environment.
(RelayModernEnvironment: any).prototype['@@RelayModernEnvironment'] = true;

module.exports = RelayModernEnvironment;
<commit_msg>Include scheduler with `executeWithSource`<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 * @emails oncall+relay
 */

'use strict';

const DataChecker = require('./DataChecker');
const RelayCore = require('./RelayCore');
const RelayDefaultHandlerProvider = require('../handlers/RelayDefaultHandlerProvider');
const RelayInMemoryRecordSource = require('./RelayInMemoryRecordSource');
const RelayModernQueryExecutor = require('./RelayModernQueryExecutor');
const RelayObservable = require('../network/RelayObservable');
const RelayPublishQueue = require('./RelayPublishQueue');

const invariant = require('invariant');
const normalizeRelayPayload = require('./normalizeRelayPayload');
const warning = require('warning');

import type {HandlerProvider} from '../handlers/RelayDefaultHandlerProvider';
import type {
  GraphQLResponse,
  Network,
  PayloadData,
  PayloadError,
  UploadableMap,
} from '../network/RelayNetworkTypes';
import type {
  Environment,
  OperationLoader,
  MissingFieldHandler,
  OperationDescriptor,
  OptimisticUpdate,
  NormalizationSelector,
  ReaderSelector,
  SelectorStoreUpdater,
  Snapshot,
  Store,
  StoreUpdater,
  UnstableEnvironmentCore,
  PublishQueue,
} from '../store/RelayStoreTypes';
import type {CacheConfig, Disposable} from '../util/RelayRuntimeTypes';
import type {TaskScheduler} from './RelayModernQueryExecutor';

export type EnvironmentConfig = {|
  +configName?: string,
  +handlerProvider?: HandlerProvider,
  +operationLoader?: OperationLoader,
  +network: Network,
  +scheduler?: TaskScheduler,
  +store: Store,
  +missingFieldHandlers?: $ReadOnlyArray<MissingFieldHandler>,
  +publishQueue?: PublishQueue,
|};

class RelayModernEnvironment implements Environment {
  _operationLoader: ?OperationLoader;
  _network: Network;
  _publishQueue: PublishQueue;
  _scheduler: ?TaskScheduler;
  _store: Store;
  configName: ?string;
  unstable_internal: UnstableEnvironmentCore;
  _missingFieldHandlers: ?$ReadOnlyArray<MissingFieldHandler>;

  constructor(config: EnvironmentConfig) {
    this.configName = config.configName;
    const handlerProvider = config.handlerProvider
      ? config.handlerProvider
      : RelayDefaultHandlerProvider;
    const operationLoader = config.operationLoader;
    if (__DEV__) {
      if (operationLoader != null) {
        invariant(
          typeof operationLoader === 'object' &&
            typeof operationLoader.get === 'function' &&
            typeof operationLoader.load === 'function',
          'RelayModernEnvironment: Expected `operationLoader` to be an object ' +
            'with get() and load() functions, got `%s`.',
          operationLoader,
        );
      }
    }
    this._operationLoader = operationLoader;
    this._network = config.network;
    this._publishQueue =
      config.publishQueue ??
      new RelayPublishQueue(config.store, handlerProvider);
    this._scheduler = config.scheduler ?? null;
    this._store = config.store;
    this.unstable_internal = RelayCore;

    (this: any).__setNet = newNet => (this._network = newNet);

    if (__DEV__) {
      const {inspect} = require('./StoreInspector');
      (this: any).DEBUG_inspect = (dataID: ?string) => inspect(this, dataID);
    }

    // Register this Relay Environment with Relay DevTools if it exists.
    // Note: this must always be the last step in the constructor.
    const _global =
      typeof global !== 'undefined'
        ? global
        : typeof window !== 'undefined'
        ? window
        : undefined;
    const devToolsHook = _global && _global.__RELAY_DEVTOOLS_HOOK__;
    if (devToolsHook) {
      devToolsHook.registerEnvironment(this);
    }
    if (config.missingFieldHandlers != null) {
      this._missingFieldHandlers = config.missingFieldHandlers;
    }
  }

  getStore(): Store {
    return this._store;
  }

  getNetwork(): Network {
    return this._network;
  }

  applyUpdate(optimisticUpdate: OptimisticUpdate): Disposable {
    const dispose = () => {
      this._publishQueue.revertUpdate(optimisticUpdate);
      this._publishQueue.run();
    };
    this._publishQueue.applyUpdate(optimisticUpdate);
    this._publishQueue.run();
    return {dispose};
  }

  revertUpdate(update: OptimisticUpdate): void {
    this._publishQueue.revertUpdate(update);
    this._publishQueue.run();
  }

  replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void {
    this._publishQueue.revertUpdate(update);
    this._publishQueue.applyUpdate(newUpdate);
    this._publishQueue.run();
  }

  applyMutation({
    operation,
    optimisticResponse,
    optimisticUpdater,
  }: {
    operation: OperationDescriptor,
    optimisticUpdater?: ?SelectorStoreUpdater,
    optimisticResponse?: Object,
  }): Disposable {
    return this.applyUpdate({
      operation,
      selectorStoreUpdater: optimisticUpdater,
      response: optimisticResponse || null,
    });
  }

  check(readSelector: NormalizationSelector): boolean {
    if (this._missingFieldHandlers == null) {
      return this._store.check(readSelector);
    }
    return this._checkSelectorAndHandleMissingFields(
      readSelector,
      this._missingFieldHandlers,
    );
  }

  commitPayload(
    operationDescriptor: OperationDescriptor,
    payload: PayloadData,
  ): void {
    // Do not handle stripped nulls when committing a payload
    const relayPayload = normalizeRelayPayload(
      operationDescriptor.root,
      payload,
    );
    this._publishQueue.commitPayload(operationDescriptor, relayPayload);
    this._publishQueue.run();
  }

  commitUpdate(updater: StoreUpdater): void {
    this._publishQueue.commitUpdate(updater);
    this._publishQueue.run();
  }

  lookup(readSelector: ReaderSelector, owner: ?OperationDescriptor): Snapshot {
    return this._store.lookup(readSelector, owner);
  }

  subscribe(
    snapshot: Snapshot,
    callback: (snapshot: Snapshot) => void,
  ): Disposable {
    return this._store.subscribe(snapshot, callback);
  }

  retain(selector: NormalizationSelector): Disposable {
    return this._store.retain(selector);
  }

  _checkSelectorAndHandleMissingFields(
    selector: NormalizationSelector,
    handlers: $ReadOnlyArray<MissingFieldHandler>,
  ): boolean {
    const target = new RelayInMemoryRecordSource();
    const result = DataChecker.check(
      this._store.getSource(),
      target,
      selector,
      handlers,
      this._operationLoader,
    );
    if (target.size() > 0) {
      this._publishQueue.commitSource(target);
      this._publishQueue.run();
    }
    return result;
  }

  /**
   * Returns an Observable of GraphQLResponse resulting from executing the
   * provided Query or Subscription operation, each result of which is then
   * normalized and committed to the publish queue.
   *
   * Note: Observables are lazy, so calling this method will do nothing until
   * the result is subscribed to: environment.execute({...}).subscribe({...}).
   */
  execute({
    operation,
    cacheConfig,
    updater,
  }: {
    operation: OperationDescriptor,
    cacheConfig?: ?CacheConfig,
    updater?: ?SelectorStoreUpdater,
  }): RelayObservable<GraphQLResponse> {
    return RelayObservable.create(sink => {
      const source = this._network.execute(
        operation.node.params,
        operation.variables,
        cacheConfig || {},
      );
      const executor = RelayModernQueryExecutor.execute({
        operation,
        operationLoader: this._operationLoader,
        optimisticUpdate: null,
        publishQueue: this._publishQueue,
        scheduler: this._scheduler,
        sink,
        source,
        updater,
      });
      return () => executor.cancel();
    });
  }

  /**
   * Returns an Observable of GraphQLResponse resulting from executing the
   * provided Mutation operation, the result of which is then normalized and
   * committed to the publish queue along with an optional optimistic response
   * or updater.
   *
   * Note: Observables are lazy, so calling this method will do nothing until
   * the result is subscribed to:
   * environment.executeMutation({...}).subscribe({...}).
   */
  executeMutation({
    operation,
    optimisticResponse,
    optimisticUpdater,
    updater,
    uploadables,
  }: {|
    operation: OperationDescriptor,
    optimisticUpdater?: ?SelectorStoreUpdater,
    optimisticResponse?: ?Object,
    updater?: ?SelectorStoreUpdater,
    uploadables?: ?UploadableMap,
  |}): RelayObservable<GraphQLResponse> {
    return RelayObservable.create(sink => {
      let optimisticUpdate;
      if (optimisticResponse || optimisticUpdater) {
        optimisticUpdate = {
          operation: operation,
          selectorStoreUpdater: optimisticUpdater,
          response: optimisticResponse ?? null,
        };
      }
      const source = this._network.execute(
        operation.node.params,
        operation.variables,
        {force: true},
        uploadables,
      );
      const executor = RelayModernQueryExecutor.execute({
        operation,
        operationLoader: this._operationLoader,
        optimisticUpdate,
        publishQueue: this._publishQueue,
        scheduler: this._scheduler,
        sink,
        source,
        updater,
      });
      return () => executor.cancel();
    });
  }

  /**
   * Returns an Observable of GraphQLResponse resulting from executing the
   * provided Query or Subscription operation responses, the result of which is
   * then normalized and comitted to the publish queue.
   *
   * Note: Observables are lazy, so calling this method will do nothing until
   * the result is subscribed to:
   * environment.executeWithSource({...}).subscribe({...}).
   */
  executeWithSource({
    operation,
    source,
  }: {|
    operation: OperationDescriptor,
    source: RelayObservable<GraphQLResponse>,
  |}): RelayObservable<GraphQLResponse> {
    return RelayObservable.create(sink => {
      const executor = RelayModernQueryExecutor.execute({
        operation,
        operationLoader: this._operationLoader,
        optimisticUpdate: null,
        publishQueue: this._publishQueue,
        scheduler: this._scheduler,
        sink,
        source,
      });
      return () => executor.cancel();
    });
  }

  /**
   * @deprecated Use Environment.execute().subscribe()
   */
  sendQuery({
    cacheConfig,
    onCompleted,
    onError,
    onNext,
    operation,
  }: {
    cacheConfig?: ?CacheConfig,
    onCompleted?: ?() => void,
    onError?: ?(error: Error) => void,
    onNext?: ?(payload: GraphQLResponse) => void,
    operation: OperationDescriptor,
  }): Disposable {
    warning(
      false,
      'environment.sendQuery() is deprecated. Update to the latest ' +
        'version of react-relay, and use environment.execute().',
    );
    return this.execute({operation, cacheConfig}).subscribeLegacy({
      onNext,
      onError,
      onCompleted,
    });
  }

  /**
   * @deprecated Use Environment.executeMutation().subscribe()
   */
  sendMutation({
    onCompleted,
    onError,
    operation,
    optimisticResponse,
    optimisticUpdater,
    updater,
    uploadables,
  }: {
    onCompleted?: ?(errors: ?Array<PayloadError>) => void,
    onError?: ?(error: Error) => void,
    operation: OperationDescriptor,
    optimisticUpdater?: ?SelectorStoreUpdater,
    optimisticResponse?: Object,
    updater?: ?SelectorStoreUpdater,
    uploadables?: UploadableMap,
  }): Disposable {
    warning(
      false,
      'environment.sendMutation() is deprecated. Update to the latest ' +
        'version of react-relay, and use environment.executeMutation().',
    );
    return this.executeMutation({
      operation,
      optimisticResponse,
      optimisticUpdater,
      updater,
      uploadables,
    }).subscribeLegacy({
      // NOTE: sendMutation has a non-standard use of onCompleted() by passing
      // it a value. When switching to use executeMutation(), the next()
      // Observer should be used to preserve behavior.
      onNext: payload => {
        onCompleted && onCompleted(payload.errors);
      },
      onError,
      onCompleted,
    });
  }

  toJSON(): mixed {
    return `RelayModernEnvironment(${this.configName ?? ''})`;
  }
}

// Add a sigil for detection by `isRelayModernEnvironment()` to avoid a
// realm-specific instanceof check, and to aid in module tree-shaking to
// avoid requiring all of RelayRuntime just to detect its environment.
(RelayModernEnvironment: any).prototype['@@RelayModernEnvironment'] = true;

module.exports = RelayModernEnvironment;
<|endoftext|>


<commit_before>define([
  'angular',
  'lodash',
],
function (angular, _) {
  'use strict';

  var module = angular.module('grafana.controllers');

  module.controller('ImportCtrl', function($scope, $http, backendSrv, datasourceSrv) {

    $scope.init = function() {
      $scope.datasources = [];
      $scope.sourceName = 'grafana';
      $scope.destName = 'grafana';
      $scope.imported = [];
      $scope.dashboards = [];
      $scope.infoText = '';
      $scope.importing = false;

      _.each(datasourceSrv.getAll(), function(ds) {
        if (ds.type === 'influxdb' || ds.type === 'elasticsearch') {
          $scope.sourceName = ds.name;
          $scope.datasources.push(ds.name);
        } else if (ds.type === 'grafana') {
          $scope.datasources.push(ds.name);
        }
      });
    };

    $scope.startImport = function() {
      $scope.sourceDs = datasourceSrv.get($scope.sourceName);
      $scope.destDs = datasourceSrv.get($scope.destName);

      $scope.sourceDs.searchDashboards('title:').then(function(results) {
        $scope.dashboards = results.dashboards;

        if ($scope.dashboards.length === 0) {
          $scope.infoText = 'No dashboards found';
          return;
        }

        $scope.importing = true;
        $scope.imported = [];
        $scope.next();
      });
    };

    $scope.next = function() {
      if ($scope.dashboards.length === 0) {
        $scope.infoText = "Done! Imported " + $scope.imported.length + " dashboards";
      }

      var dash = $scope.dashboards.shift();
      if (!dash.title) {
        console.log(dash);
        return;
      }

      var infoObj = {name: dash.title, info: 'Importing...'};
      $scope.imported.push(infoObj);
      $scope.infoText = "Importing " + $scope.imported.length + '/' + ($scope.imported.length + $scope.dashboards.length);

      $scope.sourceDs.getDashboard(dash.id).then(function(loadedDash) {
        $scope.destDs.saveDashboard(loadedDash).then(function() {
          infoObj.info = "Done!";
          $scope.next();
        }, function(err) {
          infoObj.info = "Error: " + err;
          $scope.next();
        });
      });
    };

    $scope.init();

  });
});
<commit_msg>Added error handling to dashboard imports, #1493<commit_after>define([
  'angular',
  'lodash',
],
function (angular, _) {
  'use strict';

  var module = angular.module('grafana.controllers');

  module.controller('ImportCtrl', function($scope, $http, backendSrv, datasourceSrv) {

    $scope.init = function() {
      $scope.datasources = [];
      $scope.sourceName = 'grafana';
      $scope.destName = 'grafana';
      $scope.imported = [];
      $scope.dashboards = [];
      $scope.infoText = '';
      $scope.importing = false;

      _.each(datasourceSrv.getAll(), function(ds) {
        if (ds.type === 'influxdb' || ds.type === 'elasticsearch') {
          $scope.sourceName = ds.name;
          $scope.datasources.push(ds.name);
        } else if (ds.type === 'grafana') {
          $scope.datasources.push(ds.name);
        }
      });
    };

    $scope.startImport = function() {
      $scope.sourceDs = datasourceSrv.get($scope.sourceName);
      $scope.destDs = datasourceSrv.get($scope.destName);

      $scope.sourceDs.searchDashboards('title:').then(function(results) {
        $scope.dashboards = results.dashboards;

        if ($scope.dashboards.length === 0) {
          $scope.infoText = 'No dashboards found';
          return;
        }

        $scope.importing = true;
        $scope.imported = [];
        $scope.next();
      }, function(err) {
        var resp = err.message || err.statusText || 'Unknown error';
        var message = "Failed to load dashboards from selected data source, response from server was: " + resp;
        $scope.appEvent('alert-error', ['Import failed', message]);
      });
    };

    $scope.next = function() {
      if ($scope.dashboards.length === 0) {
        $scope.infoText = "Done! Imported " + $scope.imported.length + " dashboards";
      }

      var dash = $scope.dashboards.shift();
      if (!dash.title) {
        console.log(dash);
        return;
      }

      var infoObj = {name: dash.title, info: 'Importing...'};
      $scope.imported.push(infoObj);
      $scope.infoText = "Importing " + $scope.imported.length + '/' + ($scope.imported.length + $scope.dashboards.length);

      $scope.sourceDs.getDashboard(dash.id).then(function(loadedDash) {
        $scope.destDs.saveDashboard(loadedDash).then(function() {
          infoObj.info = "Done!";
          $scope.next();
        }, function(err) {
          infoObj.info = "Error: " + err;
          $scope.next();
        });
      });
    };

    $scope.init();

  });
});
<|endoftext|>


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

    /* Task configuration */

    grunt.initConfig({

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

        watch: {

            src: {

                files: [ 'Gruntfile.js', 'src/**/*.js' ],
                tasks: [ 'jshint:src', 'build' ],

            },

            spec: {

                files: 'spec/**/*.js',
                tasks: 'jshint:spec',

            }
        },

        concat: {

            dist: {

                src: [ 'src/tmc-web-client.js', 'src/*.js' ],
                dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.js',
                options: {

                    separator: ';'

                }
            }
        },

        uglify: {

            dist: {

                files: {

                    'dist/<%= pkg.name %>-<%= pkg.version %>-min.js': 'dist/<%= pkg.name %>-<%= pkg.version %>.js'

                },

                options: {

                    report: 'min'

                }
            }
        },

        jshint: {

            src: {

                src: [ 'Gruntfile.js', 'src/**/*.js' ],
                options: {

                    jshintrc: 'jshint.json'

                }
            },

            spec: {

                src: 'spec/**/*.js',
                options: {

                    jshintrc: 'spec/jshint.json'

                }
            }
        },

        jasmine: {

            src: 'src/**/*.js',
            options: {

                specs: 'spec/**/*-spec.js',
                template: require('grunt-template-jasmine-istanbul'),
                templateOptions: {

                    coverage: 'coverage/coverage.json',
                    report: {

                        type: 'lcov',
                        options: {

                            dir: 'coverage/'

                        }
                    }
                }
            }
        },

        sass: {

            dist: {

                files: {

                    'demo/assets/css/tmc-web-client.css': 'src/css/tmc-web-client.scss'

                }
            }
        },

        copy: {

            assets: {

                expand: true,
                flatten: true,
                src: 'dist/*.js',
                dest: 'demo/assets/js/',
                filter: 'isFile'

            }
        }
    });

    /* Load tasks */

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-copy');

    /* Register tasks */

    grunt.registerTask('test', [ 'jshint', 'jasmine' ]);
    grunt.registerTask('build', [ 'concat', 'uglify', 'sass', 'copy' ]);
    grunt.registerTask('default', [ 'test', 'build' ]);
}
<commit_msg>Include order for Jasmine tests<commit_after>module.exports = function (grunt) {

    /* Task configuration */

    grunt.initConfig({

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

        watch: {

            src: {

                files: [ 'Gruntfile.js', 'src/**/*.js' ],
                tasks: [ 'jshint:src', 'build' ],

            },

            spec: {

                files: 'spec/**/*.js',
                tasks: 'jshint:spec',

            }
        },

        concat: {

            dist: {

                src: [ 'src/tmc-web-client.js', 'src/*.js' ],
                dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.js',
                options: {

                    separator: ';'

                }
            }
        },

        uglify: {

            dist: {

                files: {

                    'dist/<%= pkg.name %>-<%= pkg.version %>-min.js': 'dist/<%= pkg.name %>-<%= pkg.version %>.js'

                },

                options: {

                    report: 'min'

                }
            }
        },

        jshint: {

            src: {

                src: [ 'Gruntfile.js', 'src/**/*.js' ],
                options: {

                    jshintrc: 'jshint.json'

                }
            },

            spec: {

                src: 'spec/**/*.js',
                options: {

                    jshintrc: 'spec/jshint.json'

                }
            }
        },

        jasmine: {

            src: [ 'src/tmc-web-client.js', 'src/*.js' ],
            options: {

                specs: 'spec/**/*-spec.js',
                template: require('grunt-template-jasmine-istanbul'),
                templateOptions: {

                    coverage: 'coverage/coverage.json',
                    report: {

                        type: 'lcov',
                        options: {

                            dir: 'coverage/'

                        }
                    }
                }
            }
        },

        sass: {

            dist: {

                files: {

                    'demo/assets/css/tmc-web-client.css': 'src/css/tmc-web-client.scss'

                }
            }
        },

        copy: {

            assets: {

                expand: true,
                flatten: true,
                src: 'dist/*.js',
                dest: 'demo/assets/js/',
                filter: 'isFile'

            }
        }
    });

    /* Load tasks */

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-copy');

    /* Register tasks */

    grunt.registerTask('test', [ 'jshint', 'jasmine' ]);
    grunt.registerTask('build', [ 'concat', 'uglify', 'sass', 'copy' ]);
    grunt.registerTask('default', [ 'test', 'build' ]);
}
<|endoftext|>


<commit_before>describe('ch8',function(){
  it('nested functions and keyword "this"',function(){
    var o = {
      m: function(){
        expect(this).toBe(o);
        var self = this;
        expect(this).toBe(self);
        f();
        function f(){
          'use strict';
          expect(this).not.toBe(o);
          expect(this).toBeUndefined(); // 'this is global object in non strict'
          expect(self).toBe(o);
        }
      }
    };
    o.m();
  });

  it('higher order functions', function(){
    function not(f){
      return function(){
        return !f.apply(this, arguments);
      };
    }
    var even = function(x){ return x % 2 === 0; };
    var odd = not(even);

    expect([1,3,5].every(odd)).toBe(true);
  });
});
<commit_msg>added call and apply<commit_after>describe('ch8',function(){
  it('nested functions and keyword "this"',function(){
    var o = {
      m: function(){
        expect(this).toBe(o);
        var self = this;
        expect(this).toBe(self);
        f();
        function f(){
          'use strict';
          expect(this).not.toBe(o);
          expect(this).toBeUndefined(); // 'this is global object in non strict'
          expect(self).toBe(o);
        }
      }
    };
    o.m();
  });

  it('higher order functions', function(){
    function not(f){
      return function(){
        return !f.apply(this, arguments);
      };
    }
    var even = function(x){ return x % 2 === 0; };
    var odd = not(even);

    expect([1,3,5].every(odd)).toBe(true);
  });

  it('function with apply', function(){
    var john = {age: 14};
    var addName = function(name){
      this.name = name;
      return this;
    };

    var returned = addName.apply(john, ['John']);
    expect(returned).toBe(john);
    expect(john.name).toBe('John');
  });

  it('function with call', function(){
    var john = {age: 14};
    var addName = function(name){
      this.name = name;
      return this;
    };

    var returned = addName.call(john, 'John');
    expect(returned).toBe(john);
    expect(john.name).toBe('John');
  });

});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import $ from 'jquery'; // Import jQuery.
import TimerNewForm from './TimerNewForm';
import TimerFetch from './TimerFetch';
import FontAwesome from 'react-fontawesome';

class TimerTermTimer extends Component {
  constructor(props) {
    super(props);

    this._setHover = this._setHover.bind(this);
    this._unsetHover = this._unsetHover.bind(this);
    this._editThisTimer = this._editThisTimer.bind(this);
    this._theTimer = this._theTimer.bind(this);
    this._reloadTimer = this._reloadTimer.bind(this);
    this._cancelEditTimerControls = this._cancelEditTimerControls.bind(this);
    this._goBackToTheTimer = this._goBackToTheTimer.bind(this);

    this.state = {
      isHovered: false,
      onEditTimerClick: props.onEditTimerClick || null,
      view: this._theTimer(),
      controls: this._editTimerControls(),
    }
  }

  render() {
    return (

        {this.state.controls}
        {this.state.view}

    );
  }

  _theTimer(timer) {
    timer = timer || this.props.timer
    return(

          {timer.title.rendered}

            {this._formatDate( timer.date )}

              {this.props.projectName}

              {timer.pwptt_hours} hrs

    );
  }

  _editTimerControls() {
    let _ui = '';
      _ui =

          <FontAwesome
          name="pencil" />

;

    return _ui;
  }

  _cancelEditTimerControls() {
    return(

          <FontAwesome
          name="close" />

    );
  }

  _editThisTimer(e) {
    e.preventDefault();
    this.setState({
      controls: this._cancelEditTimerControls(),
      view: <TimerNewForm
      post={this.props.timer.id}
      total={this.props.timer.pwptt_hours}
      onSaved={this._reloadTimer} />,
    });
  }

  _goBackToTheTimer(e) {
    e.preventDefault();
    this._reloadTimer();
  }

  _reloadTimer() {
    TimerFetch.getPost( this.props.timer.id )
    .then( post => {
      this.setState({
        view: this._theTimer(post),
        controls: this._editTimerControls(),
      });
    });
  }

  _setHover() {
    console.log('Mouse Entered');
    this.setState({
      isHovered: true,
    });
  }
  _unsetHover() {
    console.log('Mouse Left');
    this.setState({
      isHovered: false,
    });
  }

  _formatDate( date ) {
    const dayNames = [
      "Monday", "Tuesday", "Wednesday",
      "Thursday", "Friday", "Saturday", "Sunday"
    ];

    date = new Date( date );

    const day = date.getDate();
    const dayIndex = date.getDay();
    const monthIndex = date.getMonth();
    const year = date.getFullYear();

    return dayNames[dayIndex] + ' ' + (monthIndex + 1) + '/' + day  + '/' + year;
  }

  _formatDescription( description ) {
    // Strip tags!
    description = $(description).text();

    // 4 lines max.
    if ( description.length > 36 *3 ) {
      description = description.slice(0, (36*3 - 3) ) + '...';
    }

    return { __html: description };
  }
}

export default TimerTermTimer;
<commit_msg>fixed updates to the project or client on the timers<commit_after>import React, { Component } from 'react';
import $ from 'jquery'; // Import jQuery.
import TimerNewForm from './TimerNewForm';
import TimerFetch from './TimerFetch';
import TimerDB from './TimerDB';
import FontAwesome from 'react-fontawesome';

class TimerTermTimer extends Component {
  constructor(props) {
    super(props);

    this._setHover = this._setHover.bind(this);
    this._unsetHover = this._unsetHover.bind(this);
    this._editThisTimer = this._editThisTimer.bind(this);
    this._theTimer = this._theTimer.bind(this);
    this._reloadTimer = this._reloadTimer.bind(this);
    this._cancelEditTimerControls = this._cancelEditTimerControls.bind(this);
    this._goBackToTheTimer = this._goBackToTheTimer.bind(this);

    this.state = {
      isHovered: false,
      onEditTimerClick: props.onEditTimerClick || null,
      view: this._theTimer(),
      controls: this._editTimerControls(),
      onEdit: props.onEdit || null,
    }
  }

  render() {
    return (

        {this.state.controls}
        {this.state.view}

    );
  }

  _theTimer(timer) {
    timer = timer || this.props.timer;

    let projectName;

    const _taxName = this.props.taxonomyName;
    const _otherTax = ('client' === _taxName) ? 'project' : 'client';

    if (timer['premise_time_tracker_'+_otherTax].length) {

      const _otherTaxCollection = TimerDB.get(_otherTax)
      .find(function(_tax){
        return _tax.id === timer['premise_time_tracker_'+_otherTax][0];
      });
      projectName = ('undefined' !== typeof _otherTaxCollection)
      ? _otherTaxCollection.name
      : '';
    }

    return(

          {timer.title.rendered}

            {this._formatDate( timer.date )}

              {projectName}

              {timer.pwptt_hours} hrs

    );
  }

  _editTimerControls() {
    let _ui = '';
      _ui =

          <FontAwesome
          name="pencil" />

;

    return _ui;
  }

  _cancelEditTimerControls() {
    return(

          <FontAwesome
          name="close" />

    );
  }

  _editThisTimer(e) {
    e.preventDefault();
    this.setState({
      controls: this._cancelEditTimerControls(),
      view: <TimerNewForm
      post={this.props.timer.id}
      total={this.props.timer.pwptt_hours}
      onSaved={this._reloadTimer} />,
    });
  }

  _goBackToTheTimer(e) {
    e.preventDefault();
    this._reloadTimer();
  }

  _reloadTimer() {
    TimerFetch.getPost( this.props.timer.id )
    .then( post => {
      this.setState({
        view: this._theTimer(post),
        controls: this._editTimerControls(),
      });
    });
  }

  _setHover() {
    console.log('Mouse Entered');
    this.setState({
      isHovered: true,
    });
  }
  _unsetHover() {
    console.log('Mouse Left');
    this.setState({
      isHovered: false,
    });
  }

  _formatDate( date ) {
    const dayNames = [
      "Monday", "Tuesday", "Wednesday",
      "Thursday", "Friday", "Saturday", "Sunday"
    ];

    date = new Date( date );

    const day = date.getDate();
    const dayIndex = date.getDay();
    const monthIndex = date.getMonth();
    const year = date.getFullYear();

    return dayNames[dayIndex] + ' ' + (monthIndex + 1) + '/' + day  + '/' + year;
  }

  _formatDescription( description ) {
    // Strip tags!
    description = $(description).text();

    // 4 lines max.
    if ( description.length > 36 *3 ) {
      description = description.slice(0, (36*3 - 3) ) + '...';
    }

    return { __html: description };
  }
}

export default TimerTermTimer;
<|endoftext|>


<commit_before>/*  BLE Configuration Service
    deviceNameCharacteristic - write/write without response - max 10 byte - ascii string
    advertisingParamCharacteristic - write/write without response - 3 bytes - uint16_t adv interval in ms - uint8_t adv timeout in s
    appearanceCharacteristic - write/write without response - 2 bytes - uint16_t appearance
    connectionParamCharacteristic - write/write without response - 8 bytes - uint16_t min conn interval - uint16_t max conn interval - uint16_t slave latency - uint16_t supervision timeout
*/
var configurationService = 'ef680001-9b35-4933-9b10-52ffa9740042';
var deviceNameCharacteristic = 'EF680002-9B35-4933-9B10-52FFA9740042';
var advertisingParamCharacteristic = 'EF680003-9B35-4933-9B10-52FFA9740042';
var appearanceCharacteristic = 'EF680004-9B35-4933-9B10-52FFA9740042';
var connectionParamCharacteristic = 'EF680005-9B35-4933-9B10-52FFA9740042';

/*  Weather Station Service
    temperatureCharacteristic - notify/read - 2 bytes - uint8_t integer - uint8_t decimal
    pressureCharacteristic - notify/read - 3 bytes - uint16_t integer - uint8_t decimal
    humidityCharacteristic - notify/read - 1 byte - uint8_t
    configurationCharacteristic - write/write without response - 7 bytes - uint16_t temp interval in ms - uint16_t pressure interval in ms - uint16_t humidity interval in ms - uint8_t pressure mode (0=barometer, 1=altimeter)
*/
var weatherStationService = '20080001-e36f-4648-91c6-9e86ead38764';
var temperatureCharacteristic = '20080002-e36f-4648-91c6-9e86ead38764';
var pressureCharacteristic = '20080003-e36f-4648-91c6-9e86ead38764';
var humidityCharacteristic = '20080004-e36f-4648-91c6-9e86ead38764';
var configurationCharacteristic = '20080005-e36f-4648-91c6-9e86ead38764';

/*  User Interface Service
    ledCharacteristic - write/read - 4 bytes - uint32_t - LED ID - Red - Green - Blue (LSB)
    buttonCharacteristic - write/read - 2 bytes - uint16_t - Button 2 state - Button 1 state (LSB)
*/
var userInterfaceService = 'C7AE0001-3266-4A5C-859F-0F4799146BB5';
var ledCharacteristic = 'C7AE0002-3266-4A5C-859F-0F4799146BB5';
var buttonCharacteristic = 'C7AE0003-3266-4A5C-859F-0F4799146BB5';

var isConnecting = false;
var isConnected = false;
var sInterval;
var sTimeout;
var sServer;
var Device;
var GATT;
var myCharacteristic;
var myService;
var humidity;
var temperature;
var pressure;
var bleDevice;
var bleServer;
var bleService;

window.onload = function(){
  document.querySelector('#connect').addEventListener('click', getAll);
  document.querySelector('#disconnect').addEventListener('click', disconnectDevice);
  document.querySelector('#disconnect').style.display = "hide";
  document.querySelector('#humidity').addEventListener('click', getHumidity);
  document.querySelector('#temperature').addEventListener('click', getTemperature);
  document.querySelector('#pressure').addEventListener('click', getPressure);
};

function log(text) {
    document.querySelector('#log').textContent += text + '\n';
}

function setConnecting(connecting) {
    isConnecting = connecting;
    if (connecting) {
        document.querySelector('#connect').style.display = "none";
    }
    else {
        document.querySelector('#connect').style.display = "block";
    }
}

function setConnected(connected) {
    isConnected = connected;
    if (connected) {
        document.querySelector('#connect').style.display = "none";
        document.querySelector('#disconnect').style.display = "block";
    }
    else {
        document.querySelector('#connect').style.display = "block";
        document.querySelector('#disconnect').style.display = "none";
        sServer.disconnect();
    }
}

function connect() {
    'use strict';

    if (!navigator.bluetooth) {
        log('Web Bluetooth API is not available.\n' +
            'Please make sure the Web Bluetooth flag is enabled.');
        return;
    }

    if (isConnecting) {
        log('Connecting. Please wait.');
        return;
    }

    log('Requesting Bluetooth Device...');

    setConnecting(true);
    navigator.bluetooth.requestDevice({
        filters: [{
            services:[weatherStationService]
        }]
    })
    .then(device => {
        log('Device name: ' + device.name);
        log('Gatt server UUIDs: ' + device.uuids);
        connect2(device, 0);
    })
    .catch(error => {
        setConnecting(false);
        log(error);
    });
}

function connect2(device, retryCount) {
    'use strict';

    device.connectGATT()
    .then(server => {
        log('Got GATT server');
        sServer = server;
        return server.getPrimaryService(weatherStationService);
    })
    .then(service => {
        log('Got service');
        return service.getCharacteristic(humidityCharacteristic);
     })
    .then(characteristic => {
        log('Got characteristic');
        setConnecting(false);
        setConnected(true);
        myCharacteristic = characteristic;
        return myCharacteristic.startNotifications();
    })
    .then(() => {
          log('Notifications started');
          myCharacteristic.addEventListener('characteristicvaluechanged', 'handleNotifications');
    })
    .catch(error => {
        log(error);
        if (retryCount < 5) {
            log('Retrying...');
            connect2(device, retryCount + 1);
        } else {
            setConnecting(false);
        }
    });
}

function getHumidity() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters: [{services: [weatherStationService]}]})
  .then(device => device.connectGATT())
  .then(server => server.getPrimaryService(weatherStationService))
  .then(service => service.getCharacteristic(humidityCharacteristic))
  .then(characteristic => {
    humidity = characteristic;
    return humidity.startNotifications().then(() => {
      log('> Notifications started');
      humidity.addEventListener('characteristicvaluechanged',
        handleNotifyHumidity);
    });
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

function getTemperature() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters: [{services: [weatherStationService]}]})
  .then(device => device.connectGATT())
  .then(server => server.getPrimaryService(weatherStationService))
  .then(service => service.getCharacteristic(temperatureCharacteristic))
  .then(characteristic => {
    temperature = characteristic;
    return temperature.startNotifications().then(() => {
      log('> Notifications started');
      temperature.addEventListener('characteristicvaluechanged',
        handleNotifyTemperature);
    });
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

function getPressure() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters: [{services: [weatherStationService]}]})
  .then(device => device.connectGATT())
  .then(server => server.getPrimaryService(weatherStationService))
  .then(service => service.getCharacteristic(pressureCharacteristic))
  .then(characteristic => {
    pressure = characteristic;
    return pressure.startNotifications().then(() => {
      log('> Notifications started');
      pressure.addEventListener('characteristicvaluechanged',
        handleNotifyPressure);
    });
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

function getAll() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters: [{services: [weatherStationService]}]})
  .then(device => device.connectGATT())
  .then(server => server.getPrimaryService(weatherStationService))
  .then(service => {
    return Promise.all([
      service.getCharacteristic(pressureCharacteristic).then(handlePressure),
      service.getCharacteristic(humidityCharacteristic).then(handleHumidity),
      service.getCharacteristic(temperatureCharacteristic).then(handleTemperature),
    ])
    .catch(error => {
    log('> getAll() ' + error);
    });
  });
}

function handlePressure(characteristic){
  log('> handlePressure()');
  characteristic.addEventListener('characteristicvaluechanged',handleNotifyPressure);
  return characteristic.startNotifications();
}

function handleTemperature(characteristic){
  log('> handleTemperature()');
  characteristic.addEventListener('characteristicvaluechanged',handleNotifyTemperature);
  return characteristic.startNotifications();
}

function handleHumidity(characteristic){
  log('> handleHumidity()');
  characteristic.addEventListener('characteristicvaluechanged',handleNotifyHumidity);
  return characteristic.startNotifications();
}

function onStopButtonClick() {
  if (myCharacteristic) {
    myCharacteristic.stopNotifications().then(() => {
      log('> Notifications stopped');
      myCharacteristic.removeEventListener('characteristicvaluechanged',
        handleNotifications);
    });
  }
}

function handleNotifyHumidity(event) {
  let value = event.target.value;
  value = value.buffer ? value : new DataView(value);
  humidity_int = value.getUint8(0);
  log('Humidity is ' + humidity_int + '%');
  document.getElementById("humidity_reading").innerHTML = humidity_int +"%";
  logObject(event);
}

function handleNotifyTemperature(event) {
  let value = event.target.value;
  value = value.buffer ? value : new DataView(value);
  temperature_int = value.getUint8(0);
  temperature_dec = value.getUint8(1);
  log('Temperature is ' + temperature_int + '.' + temperature_dec + 'C');
  document.getElementById("temperature_reading").innerHTML = temperature_int + '.' + temperature_dec + 'C';
}

function handleNotifyPressure(event) {
  let value = event.target.value;
  let name = event.target;
  log('Target is: ' + name);
  logObject(name);
  pressure_pascal = value.getInt32(0);
  pressure_pascal = swap32(pressure_pascal);
  pressure_decimal = value.getUint8(4);
  log('Pressure is ' + pressure_pascal + '.' + pressure_decimal + 'Pa');
  document.getElementById("pressure_reading").innerHTML = pressure_pascal + 'Pa';

  let a = [];
  // Convert raw data bytes to hex values just for the sake of showing something.
  // In the "real" world, you'd use data.getUint8, data.getUint16 or even
  // TextDecoder to process raw data bytes.
  for (var i = 0; i < value.byteLength; i++) {
    a.push(('00' + value.getUint8(i).toString(16)).slice(-2));
  }
  log('> ' + a.join(''));
}

// Swap byte order of 32bit value
function swap32(val) {
    return ((val & 0xFF) << 24)
           | ((val & 0xFF00) << 8)
           | ((val >> 8) & 0xFF00)
           | ((val >> 24) & 0xFF);
}

function logObject(obj){
  log('> logObject');
  // Logging property names and values using Array.forEach
  Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
    log(val + ' -> ' + obj[val]);
  });
}

function move(event, direction) {
    log("move(" + event + ", " + direction + ")");
    try {
        switch (direction) {
        case "forward":
            sCharacteristic.writeValue(new Uint8Array([1, 0, 0, 0, 0, 0]));
            break;
        case "backward":
            sCharacteristic.writeValue(new Uint8Array([0, 1, 0, 0, 0, 0]));
            break;
        case "left":
            sCharacteristic.writeValue(new Uint8Array([0, 0, 1, 0, 0, 0]));
            break;
        case "right":
            sCharacteristic.writeValue(new Uint8Array([0, 0, 0, 1, 0, 0]));
            break;
        case "up":
            sCharacteristic.writeValue(new Uint8Array([0, 0, 0, 0, 1, 0]));
            break;
        case "down":
            sCharacteristic.writeValue(new Uint8Array([0, 0, 0, 0, 0, 1]));
            break;
        }
        event.preventDefault();
    } catch (error) {
        setConnected(false);
        log(error);
    }
}

function stop(event) {
    log("stop(" + event + ")");
    try {
        sCharacteristic.writeValue(new Uint8Array([0, 0, 0, 0, 0, 0]));
        event.preventDefault();
    } catch (error) {
        log(error);
    }
}

function disconnectDevice(){
  document.querySelector('#connect').style.display = "block";
  document.querySelector('#disconnect').style.display = "none";
  sServer.disconnect();
  log("Disconnected.");
}<commit_msg>minor fix<commit_after>/*  BLE Configuration Service
    deviceNameCharacteristic - write/write without response - max 10 byte - ascii string
    advertisingParamCharacteristic - write/write without response - 3 bytes - uint16_t adv interval in ms - uint8_t adv timeout in s
    appearanceCharacteristic - write/write without response - 2 bytes - uint16_t appearance
    connectionParamCharacteristic - write/write without response - 8 bytes - uint16_t min conn interval - uint16_t max conn interval - uint16_t slave latency - uint16_t supervision timeout
*/
var configurationService = 'ef680001-9b35-4933-9b10-52ffa9740042';
var deviceNameCharacteristic = 'EF680002-9B35-4933-9B10-52FFA9740042';
var advertisingParamCharacteristic = 'EF680003-9B35-4933-9B10-52FFA9740042';
var appearanceCharacteristic = 'EF680004-9B35-4933-9B10-52FFA9740042';
var connectionParamCharacteristic = 'EF680005-9B35-4933-9B10-52FFA9740042';

/*  Weather Station Service
    temperatureCharacteristic - notify/read - 2 bytes - uint8_t integer - uint8_t decimal
    pressureCharacteristic - notify/read - 3 bytes - uint16_t integer - uint8_t decimal
    humidityCharacteristic - notify/read - 1 byte - uint8_t
    configurationCharacteristic - write/write without response - 7 bytes - uint16_t temp interval in ms - uint16_t pressure interval in ms - uint16_t humidity interval in ms - uint8_t pressure mode (0=barometer, 1=altimeter)
*/
var weatherStationService = '20080001-e36f-4648-91c6-9e86ead38764';
var temperatureCharacteristic = '20080002-e36f-4648-91c6-9e86ead38764';
var pressureCharacteristic = '20080003-e36f-4648-91c6-9e86ead38764';
var humidityCharacteristic = '20080004-e36f-4648-91c6-9e86ead38764';
var configurationCharacteristic = '20080005-e36f-4648-91c6-9e86ead38764';

/*  User Interface Service
    ledCharacteristic - write/read - 4 bytes - uint32_t - LED ID - Red - Green - Blue (LSB)
    buttonCharacteristic - write/read - 2 bytes - uint16_t - Button 2 state - Button 1 state (LSB)
*/
var userInterfaceService = 'C7AE0001-3266-4A5C-859F-0F4799146BB5';
var ledCharacteristic = 'C7AE0002-3266-4A5C-859F-0F4799146BB5';
var buttonCharacteristic = 'C7AE0003-3266-4A5C-859F-0F4799146BB5';

var isConnecting = false;
var isConnected = false;
var sInterval;
var sTimeout;
var sServer;
var Device;
var GATT;
var myCharacteristic;
var myService;
var humidity;
var temperature;
var pressure;
var bleDevice;
var bleServer;
var bleService;

window.onload = function(){
  document.querySelector('#connect').addEventListener('click', getAll);
  document.querySelector('#disconnect').addEventListener('click', disconnectDevice);
  document.querySelector('#disconnect').style.display = "hide";
  document.querySelector('#humidity').addEventListener('click', getHumidity);
  document.querySelector('#temperature').addEventListener('click', getTemperature);
  document.querySelector('#pressure').addEventListener('click', getPressure);
};

function log(text) {
    document.querySelector('#log').textContent += text + '\n';
}

function setConnecting(connecting) {
    isConnecting = connecting;
    if (connecting) {
        document.querySelector('#connect').style.display = "none";
    }
    else {
        document.querySelector('#connect').style.display = "block";
    }
}

function setConnected(connected) {
    isConnected = connected;
    if (connected) {
        document.querySelector('#connect').style.display = "none";
        document.querySelector('#disconnect').style.display = "block";
    }
    else {
        document.querySelector('#connect').style.display = "block";
        document.querySelector('#disconnect').style.display = "none";
        sServer.disconnect();
    }
}

function connect() {
    'use strict';

    if (!navigator.bluetooth) {
        log('Web Bluetooth API is not available.\n' +
            'Please make sure the Web Bluetooth flag is enabled.');
        return;
    }

    if (isConnecting) {
        log('Connecting. Please wait.');
        return;
    }

    log('Requesting Bluetooth Device...');

    setConnecting(true);
    navigator.bluetooth.requestDevice({
        filters: [{
            services:[weatherStationService]
        }]
    })
    .then(device => {
        log('Device name: ' + device.name);
        log('Gatt server UUIDs: ' + device.uuids);
        connect2(device, 0);
    })
    .catch(error => {
        setConnecting(false);
        log(error);
    });
}

function connect2(device, retryCount) {
    'use strict';

    device.connectGATT()
    .then(server => {
        log('Got GATT server');
        sServer = server;
        return server.getPrimaryService(weatherStationService);
    })
    .then(service => {
        log('Got service');
        return service.getCharacteristic(humidityCharacteristic);
     })
    .then(characteristic => {
        log('Got characteristic');
        setConnecting(false);
        setConnected(true);
        myCharacteristic = characteristic;
        return myCharacteristic.startNotifications();
    })
    .then(() => {
          log('Notifications started');
          myCharacteristic.addEventListener('characteristicvaluechanged', 'handleNotifications');
    })
    .catch(error => {
        log(error);
        if (retryCount < 5) {
            log('Retrying...');
            connect2(device, retryCount + 1);
        } else {
            setConnecting(false);
        }
    });
}

function getHumidity() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters: [{services: [weatherStationService]}]})
  .then(device => device.connectGATT())
  .then(server => server.getPrimaryService(weatherStationService))
  .then(service => service.getCharacteristic(humidityCharacteristic))
  .then(characteristic => {
    humidity = characteristic;
    return humidity.startNotifications().then(() => {
      log('> Notifications started');
      humidity.addEventListener('characteristicvaluechanged',
        handleNotifyHumidity);
    });
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

function getTemperature() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters: [{services: [weatherStationService]}]})
  .then(device => device.connectGATT())
  .then(server => server.getPrimaryService(weatherStationService))
  .then(service => service.getCharacteristic(temperatureCharacteristic))
  .then(characteristic => {
    temperature = characteristic;
    return temperature.startNotifications().then(() => {
      log('> Notifications started');
      temperature.addEventListener('characteristicvaluechanged',
        handleNotifyTemperature);
    });
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

function getPressure() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters: [{services: [weatherStationService]}]})
  .then(device => device.connectGATT())
  .then(server => server.getPrimaryService(weatherStationService))
  .then(service => service.getCharacteristic(pressureCharacteristic))
  .then(characteristic => {
    pressure = characteristic;
    return pressure.startNotifications().then(() => {
      log('> Notifications started');
      pressure.addEventListener('characteristicvaluechanged',
        handleNotifyPressure);
    });
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

function getAll() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters: [{services: [weatherStationService]}]})
  .then(device => device.gatt.connect())
  .then(server => server.getPrimaryService(weatherStationService))
  .then(service => {
    return Promise.all([
      service.getCharacteristic(pressureCharacteristic)
      .then(handlePressure),
      service.getCharacteristic(humidityCharacteristic)
      .then(handleHumidity),
      service.getCharacteristic(temperatureCharacteristic)
      .then(handleTemperature),
    ])
    .catch(error => {
    log('> getAll() ' + error);
    });
  });
}

function handlePressure(characteristic){
  log('> handlePressure()');
  characteristic.addEventListener('characteristicvaluechanged',handleNotifyPressure);
  return characteristic.startNotifications();
}

function handleTemperature(characteristic){
  log('> handleTemperature()');
  characteristic.addEventListener('characteristicvaluechanged',handleNotifyTemperature);
  return characteristic.startNotifications();
}

function handleHumidity(characteristic){
  log('> handleHumidity()');
  characteristic.addEventListener('characteristicvaluechanged',handleNotifyHumidity);
  return characteristic.startNotifications();
}

function onStopButtonClick() {
  if (myCharacteristic) {
    myCharacteristic.stopNotifications().then(() => {
      log('> Notifications stopped');
      myCharacteristic.removeEventListener('characteristicvaluechanged',
        handleNotifications);
    });
  }
}

function handleNotifyHumidity(event) {
  let value = event.target.value;
  value = value.buffer ? value : new DataView(value);
  humidity_int = value.getUint8(0);
  log('Humidity is ' + humidity_int + '%');
  document.getElementById("humidity_reading").innerHTML = humidity_int +"%";
  logObject(event);
}

function handleNotifyTemperature(event) {
  let value = event.target.value;
  value = value.buffer ? value : new DataView(value);
  temperature_int = value.getUint8(0);
  temperature_dec = value.getUint8(1);
  log('Temperature is ' + temperature_int + '.' + temperature_dec + 'C');
  document.getElementById("temperature_reading").innerHTML = temperature_int + '.' + temperature_dec + 'C';
}

function handleNotifyPressure(event) {
  let value = event.target.value;
  let name = event.target;
  log('Target is: ' + name);
  logObject(name);
  pressure_pascal = value.getInt32(0);
  pressure_pascal = swap32(pressure_pascal);
  pressure_decimal = value.getUint8(4);
  log('Pressure is ' + pressure_pascal + '.' + pressure_decimal + 'Pa');
  document.getElementById("pressure_reading").innerHTML = pressure_pascal + 'Pa';

  let a = [];
  // Convert raw data bytes to hex values just for the sake of showing something.
  // In the "real" world, you'd use data.getUint8, data.getUint16 or even
  // TextDecoder to process raw data bytes.
  for (var i = 0; i < value.byteLength; i++) {
    a.push(('00' + value.getUint8(i).toString(16)).slice(-2));
  }
  log('> ' + a.join(''));
}

// Swap byte order of 32bit value
function swap32(val) {
    return ((val & 0xFF) << 24)
           | ((val & 0xFF00) << 8)
           | ((val >> 8) & 0xFF00)
           | ((val >> 24) & 0xFF);
}

function logObject(obj){
  log('> logObject');
  // Logging property names and values using Array.forEach
  Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
    log(val + ' -> ' + obj[val]);
  });
}

function move(event, direction) {
    log("move(" + event + ", " + direction + ")");
    try {
        switch (direction) {
        case "forward":
            sCharacteristic.writeValue(new Uint8Array([1, 0, 0, 0, 0, 0]));
            break;
        case "backward":
            sCharacteristic.writeValue(new Uint8Array([0, 1, 0, 0, 0, 0]));
            break;
        case "left":
            sCharacteristic.writeValue(new Uint8Array([0, 0, 1, 0, 0, 0]));
            break;
        case "right":
            sCharacteristic.writeValue(new Uint8Array([0, 0, 0, 1, 0, 0]));
            break;
        case "up":
            sCharacteristic.writeValue(new Uint8Array([0, 0, 0, 0, 1, 0]));
            break;
        case "down":
            sCharacteristic.writeValue(new Uint8Array([0, 0, 0, 0, 0, 1]));
            break;
        }
        event.preventDefault();
    } catch (error) {
        setConnected(false);
        log(error);
    }
}

function stop(event) {
    log("stop(" + event + ")");
    try {
        sCharacteristic.writeValue(new Uint8Array([0, 0, 0, 0, 0, 0]));
        event.preventDefault();
    } catch (error) {
        log(error);
    }
}

function disconnectDevice(){
  document.querySelector('#connect').style.display = "block";
  document.querySelector('#disconnect').style.display = "none";
  sServer.disconnect();
  log("Disconnected.");
}<|endoftext|>


<commit_before>import fs from 'fs';
import { resolve, dirname } from 'path';

const ROOT_PATH = dirname(dirname(dirname(__dirname)));
const EXAMPLE_DEFINITION_PATH = resolve(ROOT_PATH, 'examples', 'examples.json');
const EXAMPLE_OUTPUT_PATH = resolve(ROOT_PATH, 'examples', 'ExampleList.jsx');

const ITEM_TEMPLATE = fs.readFileSync(resolve(__dirname, 'templates', 'ListItem.txt')).toString();
const LIST_TEMPLATE = fs.readFileSync(resolve(__dirname, 'templates', 'List.txt')).toString();

function bootstrap() {
    const examplesData = fs.readFileSync(EXAMPLE_DEFINITION_PATH);
    const examples = JSON.parse(examplesData);

    const imports = [];
    const usages = [];

    examples.forEach((data, index) => {
        const importName = `Example${index}`;

        imports.push(`import ${importName} from './${data.example}';`);

        usages.push(ITEM_TEMPLATE
            .replace('##id##', data.id)
            .replace('##headline##', data.title)
            .replace('##examplePath##', data.example)
            .replace('##readme##', data.readme ? 'true' : 'false')
            .replace('##importName##', importName));
    });

    const outputData = LIST_TEMPLATE
        .replace('##imports##', imports.join('\n'))
        .replace('##children##', usages.join('\n'));

    fs.writeFileSync(EXAMPLE_OUTPUT_PATH, outputData);

    console.log('Generated example files');
}

bootstrap();
<commit_msg>:sparkles: Add sorting of examples<commit_after>import fs from 'fs';
import { resolve, dirname } from 'path';

const ROOT_PATH = dirname(dirname(dirname(__dirname)));
const EXAMPLE_DEFINITION_PATH = resolve(ROOT_PATH, 'examples', 'examples.json');
const EXAMPLE_OUTPUT_PATH = resolve(ROOT_PATH, 'examples', 'ExampleList.jsx');

const ITEM_TEMPLATE = fs.readFileSync(resolve(__dirname, 'templates', 'ListItem.txt')).toString();
const LIST_TEMPLATE = fs.readFileSync(resolve(__dirname, 'templates', 'List.txt')).toString();

function bootstrap() {
    const examplesData = fs.readFileSync(EXAMPLE_DEFINITION_PATH);
    const examples = JSON.parse(examplesData);

    const imports = [];
    const usages = [];

    examples.sort((a, b) => a.title.localeCompare(b.title)).forEach((data, index) => {
        const importName = `Example${index}`;

        imports.push(`import ${importName} from './${data.example}';`);

        usages.push(ITEM_TEMPLATE
            .replace('##id##', data.id)
            .replace('##headline##', data.title)
            .replace('##examplePath##', data.example)
            .replace('##readme##', data.readme ? 'true' : 'false')
            .replace('##importName##', importName));
    });

    const outputData = LIST_TEMPLATE
        .replace('##imports##', imports.join('\n'))
        .replace('##children##', usages.join('\n'));

    fs.writeFileSync(EXAMPLE_OUTPUT_PATH, outputData);

    console.log('Generated example files');
}

bootstrap();
<|endoftext|>


<commit_before>rf.StandaloneDashboard(function(db){
	var chart = new ChartComponent();
	chart.setDimensions (8, 6);
	chart.setCaption("Visits from search engines");
	chart.setLabels (["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]);
	chart.setYAxis("", {
		numberPrefix: "$"
	});
	chart.addSeries ("Google", "Google", [3040, 2794, 3026, 3341, 2800, 2507, 3701, 2671, 2980, 2041, 1813, 1691], {
		seriesStacked: true,
		seriesDisplayType: "column"
	});
	chart.addSeries ("Yahoo", "Yahoo", [1200, 1124, 1006, 921, 1500, 1007, 921, 971, 1080, 1041, 1113, 1091], {
		seriesStacked: true,
		seriesDisplayType: "column"
	});
	chart.addSeries ("MSN", "MSN", [600, 724, 806, 621, 700, 907, 821, 671, 880, 641, 913, 691], {
		seriesStacked: true,
		seriesDisplayType: "column"
	});
	chart.addSeries ("Others", "Others", [965, 771, 732, 611, 700, 607, 621, 751, 800, 741, 813, 791], {
		seriesStacked: true,
		seriesDisplayType: "column"
	});
	db.addComponent (chart);
});<commit_msg>fixed stacked column RF-95 #resolve<commit_after>rf.StandaloneDashboard(function(db){
	var chart = new ChartComponent();
	chart.setDimensions (8, 6);
	chart.setCaption("Most useful search engines for website traffic");
	chart.setLabels (["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]);
	chart.setYAxis("no. of unique visits", {
	});
	chart.addSeries ("Google", "Google", [3040, 2794, 3026, 3341, 2800, 2507, 3701, 2671, 2980, 2041, 1813, 1691], {
		seriesStacked: true,
		seriesDisplayType: "column"
	});
	chart.addSeries ("Yahoo", "Yahoo", [1200, 1124, 1006, 921, 1500, 1007, 921, 971, 1080, 1041, 1113, 1091], {
		seriesStacked: true,
		seriesDisplayType: "column"
	});
	chart.addSeries ("MSN", "MSN", [600, 724, 806, 621, 700, 907, 821, 671, 880, 641, 913, 691], {
		seriesStacked: true,
		seriesDisplayType: "column"
	});
	chart.addSeries ("Others", "Others", [965, 771, 732, 611, 700, 607, 621, 751, 800, 741, 813, 791], {
		seriesStacked: true,
		seriesDisplayType: "column"
	});
	db.addComponent (chart);
});<|endoftext|>


<commit_before>import React from 'react';

import IconButton from '@ichef/gypcrete/src/IconButton';
import FlexRow from 'utils/FlexRow';

export default {
    title: '@ichef/gypcrete|IconButton',
    component: IconButton,
};

export function BasicUsage() {
    return (
        <IconButton icon="printer" />
    );
}

export function WithStatus() {
    return (
        <FlexRow>
            <IconButton
                icon="printer"
                status="loading" />

            <IconButton
                icon="printer"
                status="success"
                statusOptions={{ autohide: false }} />

            <IconButton
                icon="printer"
                status="error"
                errorMsg="Cannot add printer." />
        </FlexRow>
    );
}
<commit_msg>Add Button into IconButton storybook subcomponents<commit_after>import React from 'react';

import Button from '@ichef/gypcrete/src/Button';
import IconButton from '@ichef/gypcrete/src/IconButton';
import FlexRow from 'utils/FlexRow';

export default {
    title: '@ichef/gypcrete|IconButton',
    component: IconButton,
    subcomponents: {
        Button,
    },
};

export function BasicUsage() {
    return (
        <FlexRow>
            <IconButton icon="printer" />
        </FlexRow>
    );
}

export function WithStatus() {
    return (
        <FlexRow>
            <IconButton
                icon="printer"
                status="loading" />

            <IconButton
                icon="printer"
                status="success"
                statusOptions={{ autohide: false }} />

            <IconButton
                icon="printer"
                status="error"
                errorMsg="Cannot add printer." />
        </FlexRow>
    );
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-concat');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';'
      },
      dist: {
        src: ['src/*.js'],
        dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>-<%= pkg.version %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    jshint: {
      options: {
        node: true
      },
      all: [
        'Gruntfile.js',
        'src/*.js'
      ]
    },
    watch: {
      files: ['<%= jshint.all %>'],
      tasks: ['jshint']
    }
  });

  grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
};
<commit_msg>Removing unused plugin<commit_after>'use strict';

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-concat');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';'
      },
      dist: {
        src: ['src/*.js'],
        dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>-<%= pkg.version %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    jshint: {
      options: {
        node: true
      },
      all: [
        'Gruntfile.js',
        'src/*.js'
      ]
    },
    watch: {
      files: ['<%= jshint.all %>'],
      tasks: ['jshint']
    }
  });

  grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
};
<|endoftext|>