<commit_before>const convert = require('node-unit-conversion');

function parse_316(data) {
	let parse = {
		arbid     : '0x316',
		msg       : data.msg_f,
		rpm       : parseFloat((parseInt('0x' + data.msg[3].toString(16) + data.msg[2].toString(16)) / 6.4).toFixed(0)),
		ac_clutch : bitmask.test(data.msg[0], 0x40),
		key       : {
			acc   : bitmask.test(data.msg[0], 0x01),
			run   : bitmask.test(data.msg[0], 0x04),
			start : bitmask.test(data.msg[0], 0x10),
		},
		torque : {
			after_interventions  : parseFloat((data.msg[1] / 2.54).toFixed(1)),
			before_interventions : parseFloat((data.msg[4] / 2.54).toFixed(1)),
			loss                 : parseFloat((data.msg[5] / 2.54).toFixed(1)),
			output               : parseFloat((data.msg[7] / 2.54).toFixed(1)),
		},
	};

	update.status('engine.speed',     parse.rpm, false);
	update.status('engine.ac_clutch', parse.ac_clutch);

	update.status('engine.torque.after_interventions',  parse.torque.after_interventions,  false);
	update.status('engine.torque.before_interventions', parse.torque.before_interventions, false);
	update.status('engine.torque.loss',                 parse.torque.loss,                 false);
	update.status('engine.torque.output',               parse.torque.output,               false);
}

function parse_329(data) {
	let parse = {
		msg    : '0x329',
		engine : {
			throttle : {
				cruise : parseFloat((data.msg[4] / 2.54).toFixed(2)),
				pedal  : parseFloat((data.msg[5] / 2.54).toFixed(2)),
			},
			atmospheric_pressure : {
				mbar : (data.msg[2] * 2) + 597,
				mmhg : null,
				psi  : null,
			},
		},
		temperature : {
			coolant : {
				c : parseFloat(((data.msg[1] * 0.75) - 48.373).toFixed(2)),
				f : null,
			},
		},
		vehicle : {
			brake    : bitmask.test(data.msg[6], 0x01),
			clutch   : bitmask.test(data.msg[3], 0x01),
			kickdown : bitmask.test(data.msg[6], 0x08),
			cruise   : {
				button : {
					resume : bitmask.test(data.msg[3], 0x40) && bitmask.test(data.msg[3], 0x20),
					minus  : bitmask.test(data.msg[3], 0x40) && !bitmask.test(data.msg[3], 0x20),
					onoff  : bitmask.test(data.msg[3], 0x80),
					plus   : bitmask.test(data.msg[3], 0x20) && !bitmask.test(data.msg[3], 0x40),
					unk1   : bitmask.test(data.msg[3], 0x01),
				},
				status : {
					activating : bitmask.test(data.msg[6], 0x20),
					active     : bitmask.test(data.msg[6], 0x08),
					resume     : bitmask.test(data.msg[6], 0x10),
					unk1       : bitmask.test(data.msg[6], 0x01),
				},
			},
		},
	};

	// Calculate mmhg and psi atmospheric pressure values
	parse.engine.atmospheric_pressure.mmhg = parseFloat((parse.engine.atmospheric_pressure.mbar * 0.75006157818041).toFixed(2));
	parse.engine.atmospheric_pressure.psi  = parseFloat((parse.engine.atmospheric_pressure.mbar * 0.01450377380072).toFixed(2));

	// Calculate fahrenheit temperature values
	parse.temperature.coolant.f = parseFloat(convert(parse.temperature.coolant.c).from('celsius').to('fahrenheit'));

	// Round temperature values
	parse.temperature.coolant.c = Math.round(parse.temperature.coolant.c);
	parse.temperature.coolant.f = Math.round(parse.temperature.coolant.f);

	// Update status object
	update.status('engine.atmospheric_pressure.mbar', parse.engine.atmospheric_pressure.mbar);
	update.status('engine.atmospheric_pressure.mmhg', parse.engine.atmospheric_pressure.mmhg);
	update.status('engine.atmospheric_pressure.psi',  parse.engine.atmospheric_pressure.psi);

	update.status('vehicle.cruise.button.minus', parse.vehicle.cruise.button.minus);
	update.status('vehicle.cruise.button.onoff', parse.vehicle.cruise.button.onoff);
	update.status('vehicle.cruise.button.plus',  parse.vehicle.cruise.button.plus);
	update.status('vehicle.cruise.button.unk1',  parse.vehicle.cruise.button.unk1);

	update.status('vehicle.cruise.status.activating', parse.vehicle.cruise.status.activating);
	update.status('vehicle.cruise.status.active',     parse.vehicle.cruise.status.active);
	update.status('vehicle.cruise.status.resume',     parse.vehicle.cruise.status.resume);
	update.status('vehicle.cruise.status.unk1',       parse.vehicle.cruise.status.unk1);

	update.status('engine.throttle.cruise', parse.engine.throttle.cruise);
	update.status('engine.throttle.pedal',  parse.engine.throttle.pedal);

	update.status('temperature.coolant.f', parse.temperature.coolant.f);

	// Trigger a HUD refresh if coolant temp is updated
	if (update.status('temperature.coolant.c', parse.temperature.coolant.c)) IKE.hud_refresh();

	update.status('vehicle.brake',  parse.vehicle.brake);
	update.status('vehicle.clutch', parse.vehicle.clutch);
}

function parse_545(data) {
	let consumption_current = parseFloat((parseInt('0x' + data.msg[2].toString(16) + data.msg[1].toString(16))).toFixed(0));

	if (consumption_current === DME1.consumption_last) return;

	let parse = {
		msg  : '0x545',
		fuel : {
			consumption : consumption_current - DME1.consumption_last,
		},
	};

	DME1.consumption_last = consumption_current;

	// update.status('fuel.consumption', parse.fuel.consumption);
}

function parse_613(data) {
	let parse = {
		msg  : '0x613',
		fuel : {
			level  : null,
			liters : (data.msg[2] >= 0x80) && data.msg[2] - 0x80 || data.msg[2],
		},
	};

	parse.fuel.level = Math.round((parse.fuel.liters / config.fuel.liters_max) * 100);
	if (parse.fuel.level < 0)   parse.fuel.level = 0;
	if (parse.fuel.level > 100) parse.fuel.level = 100;

	update.status('fuel.level',  parse.fuel.level);
	update.status('fuel.liters', parse.fuel.liters);
}

function parse_615(data) {
	let parse = {
		msg    : '0x615',
		engine : {
			ac_request    : data.msg[0],
			aux_fan_speed : data.msg[1],
		},
		temperature : {
			exterior : {
				c : (data.msg[3] >= 0x80) && data.msg[3] - 0x80 || data.msg[3],
				f : null,
			},
			// This isn't right
			intake : {
				c : (data.msg[6] >= 0x80) && data.msg[6] - 0x80 || data.msg[6],
				f : null,
			},
		},
		vehicle : {
			handbrake : bitmask.test(data.msg[4], 0x02),
		},
	};

	// Calculate fahrenheit temperature values
	parse.temperature.exterior.f = parseFloat(convert(parse.temperature.exterior.c).from('celsius').to('fahrenheit'));
	parse.temperature.intake.f   = parseFloat(convert(parse.temperature.intake.c).from('celsius').to('fahrenheit'));

	// Round temperature values
	parse.temperature.exterior.c = Math.round(parse.temperature.exterior.c);
	parse.temperature.exterior.f = Math.round(parse.temperature.exterior.f);
	parse.temperature.intake.c   = Math.round(parse.temperature.intake.c);
	parse.temperature.intake.f   = Math.round(parse.temperature.intake.f);

	// Update status object
	update.status('engine.ac_request',    parse.engine.ac_request);
	update.status('engine.aux_fan_speed', parse.engine.aux_fan_speed);

	update.status('temperature.exterior.c', parse.temperature.exterior.c);
	update.status('temperature.exterior.f', parse.temperature.exterior.f);

	update.status('vehicle.handbrake', parse.vehicle.handbrake);

	// update.status('temperature.intake.c', parse.temperature.intake.c);
	// update.status('temperature.intake.f', parse.temperature.intake.f);
}

// Parse data sent from module
function parse_out(data) {
	data.command = 'bro';

	switch (data.src.id) {
		case 0x316:
			data.value = 'AC clutch/Throttle/RPM';
			parse_316(data);
			break;

		case 0x329:
			data.value = 'Temp/Brake pedal depressed/Throttle position';
			parse_329(data);
			break;

		case 0x545:
			parse_545(data);
			data.value = 'CEL/Fuel cons/Overheat/Oil temp/Charging/Brake light switch/Cruise control';
			break;

		case 0x610:
			data.value = 'VIN/info';
			break;

		case 0x613:
			data.value = 'Odometer/Running clock/Fuel level [0x615 ACK]';
			parse_613(data);
			break;

		case 0x615:
			data.value = 'A/C request/Outside air temp/Intake air temp/Parking brake/door contacts';
			parse_615(data);
			break;

		default:
			data.value = data.src.id.toString(16);
	}

	// log.bus(data);
}

module.exports = {
	consumption_last : 0,

	parse_out : (data) => { parse_out(data); },
};
<commit_msg>Update<commit_after>const convert = require('node-unit-conversion');

function parse_316(data) {
	let parse = {
		arbid     : '0x316',
		msg       : data.msg_f,
		rpm       : parseFloat((parseInt('0x' + data.msg[3].toString(16) + data.msg[2].toString(16)) / 6.4).toFixed(0)),
		ac_clutch : bitmask.test(data.msg[0], 0x40),
		key       : {
			acc   : bitmask.test(data.msg[0], 0x01),
			run   : bitmask.test(data.msg[0], 0x04),
			start : bitmask.test(data.msg[0], 0x10),
		},
		torque : {
			after_interventions  : parseFloat((data.msg[1] / 2.54).toFixed(1)),
			before_interventions : parseFloat((data.msg[4] / 2.54).toFixed(1)),
			loss                 : parseFloat((data.msg[5] / 2.54).toFixed(1)),
			output               : parseFloat((data.msg[7] / 2.54).toFixed(1)),
		},
	};

	// Occasionally the RPM is parses as something less than 50.. no idea why
	if (parse.rpm > 300) update.status('engine.speed', parse.rpm, false);

	update.status('engine.ac_clutch', parse.ac_clutch);

	update.status('engine.torque.after_interventions',  parse.torque.after_interventions,  false);
	update.status('engine.torque.before_interventions', parse.torque.before_interventions, false);
	update.status('engine.torque.loss',                 parse.torque.loss,                 false);
	update.status('engine.torque.output',               parse.torque.output,               false);
}

function parse_329(data) {
	let parse = {
		msg    : '0x329',
		engine : {
			throttle : {
				cruise : parseFloat((data.msg[4] / 2.54).toFixed(2)),
				pedal  : parseFloat((data.msg[5] / 2.54).toFixed(2)),
			},
			atmospheric_pressure : {
				mbar : (data.msg[2] * 2) + 597,
				mmhg : null,
				psi  : null,
			},
		},
		temperature : {
			coolant : {
				c : parseFloat(((data.msg[1] * 0.75) - 48.373).toFixed(2)),
				f : null,
			},
		},
		vehicle : {
			brake    : bitmask.test(data.msg[6], 0x01),
			clutch   : bitmask.test(data.msg[3], 0x01),
			kickdown : bitmask.test(data.msg[6], 0x08),
			cruise   : {
				button : {
					resume : bitmask.test(data.msg[3], 0x40) && bitmask.test(data.msg[3], 0x20),
					minus  : bitmask.test(data.msg[3], 0x40) && !bitmask.test(data.msg[3], 0x20),
					onoff  : bitmask.test(data.msg[3], 0x80),
					plus   : bitmask.test(data.msg[3], 0x20) && !bitmask.test(data.msg[3], 0x40),
					unk1   : bitmask.test(data.msg[3], 0x01),
				},
				status : {
					activating : bitmask.test(data.msg[6], 0x20),
					active     : bitmask.test(data.msg[6], 0x08),
					resume     : bitmask.test(data.msg[6], 0x10),
					unk1       : bitmask.test(data.msg[6], 0x01),
				},
			},
		},
	};

	// Calculate mmhg and psi atmospheric pressure values
	parse.engine.atmospheric_pressure.mmhg = parseFloat((parse.engine.atmospheric_pressure.mbar * 0.75006157818041).toFixed(2));
	parse.engine.atmospheric_pressure.psi  = parseFloat((parse.engine.atmospheric_pressure.mbar * 0.01450377380072).toFixed(2));

	// Calculate fahrenheit temperature values
	parse.temperature.coolant.f = parseFloat(convert(parse.temperature.coolant.c).from('celsius').to('fahrenheit'));

	// Round temperature values
	parse.temperature.coolant.c = Math.round(parse.temperature.coolant.c);
	parse.temperature.coolant.f = Math.round(parse.temperature.coolant.f);

	// Update status object
	update.status('engine.atmospheric_pressure.mbar', parse.engine.atmospheric_pressure.mbar);
	update.status('engine.atmospheric_pressure.mmhg', parse.engine.atmospheric_pressure.mmhg);
	update.status('engine.atmospheric_pressure.psi',  parse.engine.atmospheric_pressure.psi);

	update.status('vehicle.cruise.button.minus', parse.vehicle.cruise.button.minus);
	update.status('vehicle.cruise.button.onoff', parse.vehicle.cruise.button.onoff);
	update.status('vehicle.cruise.button.plus',  parse.vehicle.cruise.button.plus);
	update.status('vehicle.cruise.button.unk1',  parse.vehicle.cruise.button.unk1);

	update.status('vehicle.cruise.status.activating', parse.vehicle.cruise.status.activating);
	update.status('vehicle.cruise.status.active',     parse.vehicle.cruise.status.active);
	update.status('vehicle.cruise.status.resume',     parse.vehicle.cruise.status.resume);
	update.status('vehicle.cruise.status.unk1',       parse.vehicle.cruise.status.unk1);

	update.status('engine.throttle.cruise', parse.engine.throttle.cruise);
	update.status('engine.throttle.pedal',  parse.engine.throttle.pedal);

	update.status('temperature.coolant.f', parse.temperature.coolant.f);

	// Trigger a HUD refresh if coolant temp is updated
	if (update.status('temperature.coolant.c', parse.temperature.coolant.c)) IKE.hud_refresh();

	update.status('vehicle.brake',  parse.vehicle.brake);
	update.status('vehicle.clutch', parse.vehicle.clutch);
}

function parse_545(data) {
	let consumption_current = parseFloat((parseInt('0x' + data.msg[2].toString(16) + data.msg[1].toString(16))).toFixed(0));

	if (consumption_current === DME1.consumption_last) return;

	let parse = {
		msg  : '0x545',
		fuel : {
			consumption : consumption_current - DME1.consumption_last,
		},
	};

	DME1.consumption_last = consumption_current;

	// update.status('fuel.consumption', parse.fuel.consumption);
}

function parse_613(data) {
	let parse = {
		msg  : '0x613',
		fuel : {
			level  : null,
			liters : (data.msg[2] >= 0x80) && data.msg[2] - 0x80 || data.msg[2],
		},
	};

	parse.fuel.level = Math.round((parse.fuel.liters / config.fuel.liters_max) * 100);
	if (parse.fuel.level < 0)   parse.fuel.level = 0;
	if (parse.fuel.level > 100) parse.fuel.level = 100;

	update.status('fuel.level',  parse.fuel.level);
	update.status('fuel.liters', parse.fuel.liters);
}

function parse_615(data) {
	let parse = {
		msg    : '0x615',
		engine : {
			ac_request    : data.msg[0],
			aux_fan_speed : data.msg[1],
		},
		temperature : {
			exterior : {
				c : (data.msg[3] >= 0x80) && data.msg[3] - 0x80 || data.msg[3],
				f : null,
			},
			// This isn't right
			intake : {
				c : (data.msg[6] >= 0x80) && data.msg[6] - 0x80 || data.msg[6],
				f : null,
			},
		},
		vehicle : {
			handbrake : bitmask.test(data.msg[4], 0x02),
		},
	};

	// Calculate fahrenheit temperature values
	parse.temperature.exterior.f = parseFloat(convert(parse.temperature.exterior.c).from('celsius').to('fahrenheit'));
	parse.temperature.intake.f   = parseFloat(convert(parse.temperature.intake.c).from('celsius').to('fahrenheit'));

	// Round temperature values
	parse.temperature.exterior.c = Math.round(parse.temperature.exterior.c);
	parse.temperature.exterior.f = Math.round(parse.temperature.exterior.f);
	parse.temperature.intake.c   = Math.round(parse.temperature.intake.c);
	parse.temperature.intake.f   = Math.round(parse.temperature.intake.f);

	// Update status object
	update.status('engine.ac_request',    parse.engine.ac_request);
	update.status('engine.aux_fan_speed', parse.engine.aux_fan_speed);

	update.status('temperature.exterior.c', parse.temperature.exterior.c);
	update.status('temperature.exterior.f', parse.temperature.exterior.f);

	update.status('vehicle.handbrake', parse.vehicle.handbrake);

	// update.status('temperature.intake.c', parse.temperature.intake.c);
	// update.status('temperature.intake.f', parse.temperature.intake.f);
}

// Parse data sent from module
function parse_out(data) {
	data.command = 'bro';

	switch (data.src.id) {
		case 0x316:
			data.value = 'AC clutch/Throttle/RPM';
			parse_316(data);
			break;

		case 0x329:
			data.value = 'Temp/Brake pedal depressed/Throttle position';
			parse_329(data);
			break;

		case 0x545:
			parse_545(data);
			data.value = 'CEL/Fuel cons/Overheat/Oil temp/Charging/Brake light switch/Cruise control';
			break;

		case 0x610:
			data.value = 'VIN/info';
			break;

		case 0x613:
			data.value = 'Odometer/Running clock/Fuel level [0x615 ACK]';
			parse_613(data);
			break;

		case 0x615:
			data.value = 'A/C request/Outside air temp/Intake air temp/Parking brake/door contacts';
			parse_615(data);
			break;

		default:
			data.value = data.src.id.toString(16);
	}

	// log.bus(data);
}

module.exports = {
	consumption_last : 0,

	parse_out : (data) => { parse_out(data); },
};
<|endoftext|>


<commit_before>'use strict';
import db from './';
import config from '../config';

const DEBUG = config.debug;

export function dropProjects () {
  DEBUG && console.log('Dropping table: projects');
  return db.schema.dropTableIfExists('projects');
}

export function dropProjectsFiles () {
  DEBUG && console.log('Dropping table: projects_files');
  return db.schema.dropTableIfExists('projects_files');
}

export function dropProjectsAA () {
  DEBUG && console.log('Dropping table: projects_aa');
  return db.schema.dropTableIfExists('projects_aa');
}

export function dropScenarios () {
  DEBUG && console.log('Dropping table: scenarios');
  return db.schema.dropTableIfExists('scenarios');
}

export function dropScenariosFiles () {
  DEBUG && console.log('Dropping table: scenarios_files');
  return db.schema.dropTableIfExists('scenarios_files');
}

export function dropScenariosSettings () {
  DEBUG && console.log('Dropping table: scenarios_settings');
  return db.schema.dropTableIfExists('scenarios_settings');
}

export function dropOperations () {
  DEBUG && console.log('Dropping table: operations');
  return db.schema.dropTableIfExists('operations');
}

export function dropOperationsLogs () {
  DEBUG && console.log('Dropping table: operations_logs');
  return db.schema.dropTableIfExists('operations_logs');
}

export function dropResults () {
  DEBUG && console.log('Dropping table: results');
  return db.schema.dropTableIfExists('results');
}

export function dropResultsPoi () {
  DEBUG && console.log('Dropping table: results_poi');
  return db.schema.dropTableIfExists('results_poi');
}

export function dropProjectsOrigins () {
  DEBUG && console.log('Dropping table: projects_origins');
  return db.schema.dropTableIfExists('projects_origins');
}

export function dropProjectsOriginsIndicators () {
  DEBUG && console.log('Dropping table: projects_origins_indicators');
  return db.schema.dropTableIfExists('projects_origins_indicators');
}

export function dropProjectsSourceData () {
  DEBUG && console.log('Dropping table: projects_source_data');
  return db.schema.dropTableIfExists('projects_source_data');
}

export function dropScenariosSourceData () {
  DEBUG && console.log('Dropping table: scenarios_source_data');
  return db.schema.dropTableIfExists('scenarios_source_data');
}

export function dropWbCatalogResources () {
  DEBUG && console.log('Dropping table: wbcatalog_resources');
  return db.schema.dropTableIfExists('wbcatalog_resources');
}

export function createProjectsTable () {
  DEBUG && console.log('Creating table: projects');
  return db.schema.createTable('projects', table => {
    table.increments('id').primary();
    table.string('name');
    table.text('description');
    table.string('status');
    table.json('bbox');
    table.timestamps();

    table.unique('name');
  });
}

export function createProjectsFilesTable () {
  DEBUG && console.log('Creating table: projects_files');
  return db.schema.createTable('projects_files', table => {
    table.increments('id').primary();
    table.string('name');
    table.string('type');
    table.string('path');
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.json('data');
    table.timestamps();
  });
}

export function createProjectsAATable () {
  DEBUG && console.log('Creating table: projects_aa');
  return db.schema.createTable('projects_aa', table => {
    table.increments('id').primary();
    table.string('name');
    table.string('type');
    table.json('geometry');
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
  });
}

export function createScenariosTable () {
  DEBUG && console.log('Creating table: scenarios');
  return db.schema.createTable('scenarios', table => {
    table.increments('id').primary();
    table.string('name');
    table.text('description');
    table.string('status');
    table.boolean('master').defaultTo(false);
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.json('admin_areas');
    table.timestamps();

    table.unique(['project_id', 'name']);
  });
}

export function createScenariosFilesTable () {
  DEBUG && console.log('Creating table: scenarios_files');
  return db.schema.createTable('scenarios_files', table => {
    table.increments('id').primary();
    table.string('name');
    table.string('type');
    table.string('subtype');
    table.string('path');
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.timestamps();
  });
}

export function createScenariosSettingsTable () {
  DEBUG && console.log('Creating table: scenarios_settings');
  return db.schema.createTable('scenarios_settings', table => {
    table.string('key');
    table.text('value');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.timestamps();
    table.primary(['scenario_id', 'key']);
  });
}

export function createOperationsTable () {
  DEBUG && console.log('Creating table: operations');
  return db.schema.createTable('operations', table => {
    table.increments('id').primary();
    table.string('name');
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.string('status');
    table.timestamps();
  });
}

export function createOperationsLogsTable () {
  DEBUG && console.log('Creating table: operations_logs');
  return db.schema.createTable('operations_logs', table => {
    table.increments('id').primary();
    table.integer('operation_id').unsigned();
    table.foreign('operation_id')
      .references('operations.id')
      .onDelete('CASCADE');
    table.string('code');
    table.json('data');
    table.timestamp('created_at').defaultTo(db.fn.now());
  });
}

export function createResultsTable () {
  DEBUG && console.log('Creating table: results');
  return db.schema.createTable('results', table => {
    table.increments('id').primary();
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.integer('origin_id').unsigned();
    table.foreign('origin_id')
      .references('projects_origins.id')
      .onDelete('CASCADE');
    table.integer('project_aa_id').unsigned();
    table.foreign('project_aa_id')
      .references('projects_aa.id')
      .onDelete('CASCADE');

    table.index(['project_id', 'scenario_id']);
  });
}

export function createResultsPoiTable () {
  DEBUG && console.log('Creating table: results_poi');
  return db.schema.createTable('results_poi', table => {
    table.increments('id').primary();
    table.integer('result_id').unsigned();
    table.foreign('result_id')
      .references('results.id')
      .onDelete('CASCADE');
    table.string('type');
    table.integer('time');

    table.index('type');
  });
}

export function createProjectsOriginsTable () {
  DEBUG && console.log('Creating table: projects_origins');
  return db.schema.createTable('projects_origins', table => {
    table.increments('id').primary();
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.string('name');
    table.json('coordinates');

    table.index('project_id');
  });
}

export function createProjectsOriginsIndicatorsTable () {
  DEBUG && console.log('Creating table: projects_origins_indicators');
  return db.schema.createTable('projects_origins_indicators', table => {
    table.increments('id').primary();
    table.integer('origin_id').unsigned();
    table.foreign('origin_id')
      .references('projects_origins.id')
      .onDelete('CASCADE');
    table.string('key');
    table.string('label');
    table.integer('value');

    table.index('origin_id');
    table.index('key');
  });
}

export function createProjectsSourceData () {
  DEBUG && console.log('Creating table: projects_source_data');
  return db.schema.createTable('projects_source_data', table => {
    table.increments('id').primary();
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.string('name');
    table.string('type');
    table.json('data');
  });
}

export function createScenariosSourceData () {
  DEBUG && console.log('Creating table: scenarios_source_data');
  return db.schema.createTable('scenarios_source_data', table => {
    table.increments('id').primary();
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.string('name');
    table.string('type');
    table.json('data');
  });
}

export function createWbCatalogResources () {
  DEBUG && console.log('Creating table: wbcatalog_resources');
  return db.schema.createTable('wbcatalog_resources', table => {
    table.increments('id').primary();
    table.string('type');
    table.string('name');
    table.timestamp('created_at').defaultTo(db.fn.now());
    table.string('resource_id');
    table.string('resource_url');
    table.json('data');
  });
}

export function setupStructure () {
  return dropScenariosFiles()
  .then(() => dropProjectsFiles())
  .then(() => dropResultsPoi())
  .then(() => dropResults())
  .then(() => dropProjectsAA())
  .then(() => dropOperationsLogs())
  .then(() => dropOperations())
  .then(() => dropScenariosSettings())
  .then(() => dropScenariosSourceData())
  .then(() => dropScenarios())
  .then(() => dropProjectsSourceData())
  .then(() => dropProjectsOriginsIndicators())
  .then(() => dropProjectsOrigins())
  .then(() => dropProjects())
  .then(() => dropWbCatalogResources())
  .then(() => createProjectsTable())
  .then(() => createProjectsAATable())
  .then(() => createScenariosTable())
  .then(() => createScenariosSettingsTable())
  .then(() => createOperationsTable())
  .then(() => createOperationsLogsTable())
  .then(() => createProjectsFilesTable())
  .then(() => createScenariosFilesTable())
  .then(() => createProjectsOriginsTable())
  .then(() => createProjectsOriginsIndicatorsTable())
  .then(() => createResultsTable())
  .then(() => createResultsPoiTable())
  .then(() => createScenariosSourceData())
  .then(() => createProjectsSourceData())
  .then(() => createWbCatalogResources());
}
<commit_msg>Add index to column result_if of result_poi table<commit_after>'use strict';
import db from './';
import config from '../config';

const DEBUG = config.debug;

export function dropProjects () {
  DEBUG && console.log('Dropping table: projects');
  return db.schema.dropTableIfExists('projects');
}

export function dropProjectsFiles () {
  DEBUG && console.log('Dropping table: projects_files');
  return db.schema.dropTableIfExists('projects_files');
}

export function dropProjectsAA () {
  DEBUG && console.log('Dropping table: projects_aa');
  return db.schema.dropTableIfExists('projects_aa');
}

export function dropScenarios () {
  DEBUG && console.log('Dropping table: scenarios');
  return db.schema.dropTableIfExists('scenarios');
}

export function dropScenariosFiles () {
  DEBUG && console.log('Dropping table: scenarios_files');
  return db.schema.dropTableIfExists('scenarios_files');
}

export function dropScenariosSettings () {
  DEBUG && console.log('Dropping table: scenarios_settings');
  return db.schema.dropTableIfExists('scenarios_settings');
}

export function dropOperations () {
  DEBUG && console.log('Dropping table: operations');
  return db.schema.dropTableIfExists('operations');
}

export function dropOperationsLogs () {
  DEBUG && console.log('Dropping table: operations_logs');
  return db.schema.dropTableIfExists('operations_logs');
}

export function dropResults () {
  DEBUG && console.log('Dropping table: results');
  return db.schema.dropTableIfExists('results');
}

export function dropResultsPoi () {
  DEBUG && console.log('Dropping table: results_poi');
  return db.schema.dropTableIfExists('results_poi');
}

export function dropProjectsOrigins () {
  DEBUG && console.log('Dropping table: projects_origins');
  return db.schema.dropTableIfExists('projects_origins');
}

export function dropProjectsOriginsIndicators () {
  DEBUG && console.log('Dropping table: projects_origins_indicators');
  return db.schema.dropTableIfExists('projects_origins_indicators');
}

export function dropProjectsSourceData () {
  DEBUG && console.log('Dropping table: projects_source_data');
  return db.schema.dropTableIfExists('projects_source_data');
}

export function dropScenariosSourceData () {
  DEBUG && console.log('Dropping table: scenarios_source_data');
  return db.schema.dropTableIfExists('scenarios_source_data');
}

export function dropWbCatalogResources () {
  DEBUG && console.log('Dropping table: wbcatalog_resources');
  return db.schema.dropTableIfExists('wbcatalog_resources');
}

export function createProjectsTable () {
  DEBUG && console.log('Creating table: projects');
  return db.schema.createTable('projects', table => {
    table.increments('id').primary();
    table.string('name');
    table.text('description');
    table.string('status');
    table.json('bbox');
    table.timestamps();

    table.unique('name');
  });
}

export function createProjectsFilesTable () {
  DEBUG && console.log('Creating table: projects_files');
  return db.schema.createTable('projects_files', table => {
    table.increments('id').primary();
    table.string('name');
    table.string('type');
    table.string('path');
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.json('data');
    table.timestamps();
  });
}

export function createProjectsAATable () {
  DEBUG && console.log('Creating table: projects_aa');
  return db.schema.createTable('projects_aa', table => {
    table.increments('id').primary();
    table.string('name');
    table.string('type');
    table.json('geometry');
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
  });
}

export function createScenariosTable () {
  DEBUG && console.log('Creating table: scenarios');
  return db.schema.createTable('scenarios', table => {
    table.increments('id').primary();
    table.string('name');
    table.text('description');
    table.string('status');
    table.boolean('master').defaultTo(false);
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.json('admin_areas');
    table.timestamps();

    table.unique(['project_id', 'name']);
  });
}

export function createScenariosFilesTable () {
  DEBUG && console.log('Creating table: scenarios_files');
  return db.schema.createTable('scenarios_files', table => {
    table.increments('id').primary();
    table.string('name');
    table.string('type');
    table.string('subtype');
    table.string('path');
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.timestamps();
  });
}

export function createScenariosSettingsTable () {
  DEBUG && console.log('Creating table: scenarios_settings');
  return db.schema.createTable('scenarios_settings', table => {
    table.string('key');
    table.text('value');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.timestamps();
    table.primary(['scenario_id', 'key']);
  });
}

export function createOperationsTable () {
  DEBUG && console.log('Creating table: operations');
  return db.schema.createTable('operations', table => {
    table.increments('id').primary();
    table.string('name');
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.string('status');
    table.timestamps();
  });
}

export function createOperationsLogsTable () {
  DEBUG && console.log('Creating table: operations_logs');
  return db.schema.createTable('operations_logs', table => {
    table.increments('id').primary();
    table.integer('operation_id').unsigned();
    table.foreign('operation_id')
      .references('operations.id')
      .onDelete('CASCADE');
    table.string('code');
    table.json('data');
    table.timestamp('created_at').defaultTo(db.fn.now());
  });
}

export function createResultsTable () {
  DEBUG && console.log('Creating table: results');
  return db.schema.createTable('results', table => {
    table.increments('id').primary();
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.integer('origin_id').unsigned();
    table.foreign('origin_id')
      .references('projects_origins.id')
      .onDelete('CASCADE');
    table.integer('project_aa_id').unsigned();
    table.foreign('project_aa_id')
      .references('projects_aa.id')
      .onDelete('CASCADE');

    table.index(['project_id', 'scenario_id']);
  });
}

export function createResultsPoiTable () {
  DEBUG && console.log('Creating table: results_poi');
  return db.schema.createTable('results_poi', table => {
    table.increments('id').primary();
    table.integer('result_id').unsigned();
    table.foreign('result_id')
      .references('results.id')
      .onDelete('CASCADE');
    table.string('type');
    table.integer('time');

    table.index('type');
    table.index('result_id');
  });
}

export function createProjectsOriginsTable () {
  DEBUG && console.log('Creating table: projects_origins');
  return db.schema.createTable('projects_origins', table => {
    table.increments('id').primary();
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.string('name');
    table.json('coordinates');

    table.index('project_id');
  });
}

export function createProjectsOriginsIndicatorsTable () {
  DEBUG && console.log('Creating table: projects_origins_indicators');
  return db.schema.createTable('projects_origins_indicators', table => {
    table.increments('id').primary();
    table.integer('origin_id').unsigned();
    table.foreign('origin_id')
      .references('projects_origins.id')
      .onDelete('CASCADE');
    table.string('key');
    table.string('label');
    table.integer('value');

    table.index('origin_id');
    table.index('key');
  });
}

export function createProjectsSourceData () {
  DEBUG && console.log('Creating table: projects_source_data');
  return db.schema.createTable('projects_source_data', table => {
    table.increments('id').primary();
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.string('name');
    table.string('type');
    table.json('data');
  });
}

export function createScenariosSourceData () {
  DEBUG && console.log('Creating table: scenarios_source_data');
  return db.schema.createTable('scenarios_source_data', table => {
    table.increments('id').primary();
    table.integer('project_id').unsigned();
    table.foreign('project_id')
      .references('projects.id')
      .onDelete('CASCADE');
    table.integer('scenario_id').unsigned();
    table.foreign('scenario_id')
      .references('scenarios.id')
      .onDelete('CASCADE');
    table.string('name');
    table.string('type');
    table.json('data');
  });
}

export function createWbCatalogResources () {
  DEBUG && console.log('Creating table: wbcatalog_resources');
  return db.schema.createTable('wbcatalog_resources', table => {
    table.increments('id').primary();
    table.string('type');
    table.string('name');
    table.timestamp('created_at').defaultTo(db.fn.now());
    table.string('resource_id');
    table.string('resource_url');
    table.json('data');
  });
}

export function setupStructure () {
  return dropScenariosFiles()
  .then(() => dropProjectsFiles())
  .then(() => dropResultsPoi())
  .then(() => dropResults())
  .then(() => dropProjectsAA())
  .then(() => dropOperationsLogs())
  .then(() => dropOperations())
  .then(() => dropScenariosSettings())
  .then(() => dropScenariosSourceData())
  .then(() => dropScenarios())
  .then(() => dropProjectsSourceData())
  .then(() => dropProjectsOriginsIndicators())
  .then(() => dropProjectsOrigins())
  .then(() => dropProjects())
  .then(() => dropWbCatalogResources())
  .then(() => createProjectsTable())
  .then(() => createProjectsAATable())
  .then(() => createScenariosTable())
  .then(() => createScenariosSettingsTable())
  .then(() => createOperationsTable())
  .then(() => createOperationsLogsTable())
  .then(() => createProjectsFilesTable())
  .then(() => createScenariosFilesTable())
  .then(() => createProjectsOriginsTable())
  .then(() => createProjectsOriginsIndicatorsTable())
  .then(() => createResultsTable())
  .then(() => createResultsPoiTable())
  .then(() => createScenariosSourceData())
  .then(() => createProjectsSourceData())
  .then(() => createWbCatalogResources());
}
<|endoftext|>


<commit_before>/**
 * TODO(developer):
 * Add your service key to the current folder.
 * Uncomment and fill in these variables.
 */
// const slackSigningSecret = '...';
// const slackToken = 'xoxb-...';
// const projectId = 'my-project';
// const locationId = 'global';
// const agentId = 'my-agent';
// const languageCode = 'en';

const structProtoToJson = require('../../botlib/proto_to_json.js').structProtoToJson;

const { WebClient } = require('@slack/web-api');
const { createEventAdapter } = require('@slack/events-api');

const slackEvents = createEventAdapter(slackSigningSecret);
const slackClient = new WebClient(slackToken);

// Imports the Google Cloud Some API library
const {SessionsClient} = require('@google-cloud/dialogflow-cx');
/**
 * Example for regional endpoint:
 *   const locationId = 'us-central1'
 *   const client = new SessionsClient({apiEndpoint: 'us-central1-dialogflow.googleapis.com'})
 */
const client = new SessionsClient({apiEndpoint: locationId + '-dialogflow.googleapis.com'});

/**
 * Converts Slack request to a detectIntent request.
 */
function slackToDetectIntent(slackRequest, sessionPath){
    const request = {
        session: sessionPath,
        queryInput: {
            text: {
                text: slackRequest.text,
            },
            languageCode,
        },
    };

    return request;
}

/**
 * Takes as input a request from Slack and converts the request to
 * detectIntent request which is used to call the detectIntent() function
 * and finally output the response given by detectIntent().
 */
async function detectIntentResponse(slackRequest) {
    const sessionId = slackRequest.channel;
    const sessionPath = client.projectLocationAgentSessionPath(
        projectId,
        locationId,
        agentId,
        sessionId
    );
    console.info(sessionPath);

    request = slackToDetectIntent(slackRequest, sessionPath);
    const [response] = await client.detectIntent(request);

    return response;
};

async function convertToSlackMessage(responses, channel_id) {
    let replies = [];

    for(let response of responses.queryResult.responseMessages) {
        let reply;

        switch(true) {
            case response.hasOwnProperty('text'): {
                reply = {
                    channel: channel_id,
                    text: response.text.text.join()
                };
            }
            break;
            /**
             * For image responses the message format can be found
             * at https://api.slack.com/reference/block-kit/block-elements#image
             * For button responses the message format can be found at
             * https://api.slack.com/legacy/message-buttons
             */
            case response.hasOwnProperty('payload'): {
                var output = structProtoToJson(response.payload)
                if(response.payload.fields.hasOwnProperty('image_url')){
                    reply = {
                        channel: channel_id,
                        blocks: [output]
                    }
                }else if(response.payload.fields.hasOwnProperty('attachments')){
                    reply = output
                    reply['channel'] = channel_id
                }
            }
            break;

            default:
        }
        if (reply) {
            replies.push(reply);
        }
    }

    return replies;
}

/**
 * Checks if the request is coming from a bot and if it is not
 * it will call detectIntentResponse() with the request as the input
 * and outputs the response. The initial check to make
 * sure the request is not from a bot is there to prevent the Integration
 * from replying to its own messages.
 */
async function eventToRequest(event, channel_id) {
    if(event.bot_id == '' || event.bot_id == null){
        const response = await detectIntentResponse(event);
        var requests = await convertToSlackMessage(response, channel_id);
        for(req of requests){
            try {
                await slackClient.chat.postMessage(req)
            } catch (error) {
                console.log(error.data)
            }
        }
    };
};

// Listens for messages posted in instant messages.
slackEvents.on('message', (event) => {
    (async () => {
        await eventToRequest(event, event.user);
    })();
});

// Listens for messages that mention the Slack App in channals
slackEvents.on('app_mention', (event) => {
    (async () => {
        await eventToRequest(event, event.channel);
    })();
});

slackEvents.on('error', console.error);

slackEvents.start(process.env.PORT).then(() => {
    console.log(`Server started on port ${process.env.PORT}`)
});

module.exports = {slackToDetectIntent, convertToSlackMessage};
<commit_msg>Update server.js<commit_after>/**
 * TODO(developer):
 * Add your service key to the current folder.
 * Uncomment and fill in these variables.
 */
// const slackSigningSecret = '...';
// const slackToken = 'xoxb-...';
// const projectId = 'my-project';
// const locationId = 'global';
// const agentId = 'my-agent';
// const languageCode = 'en';

const structProtoToJson = require('../../botlib/proto_to_json.js').structProtoToJson;

const { WebClient } = require('@slack/web-api');
const { createEventAdapter } = require('@slack/events-api');

const slackEvents = createEventAdapter(slackSigningSecret);
const slackClient = new WebClient(slackToken);

// Imports the Google Cloud Some API library
const {SessionsClient} = require('@google-cloud/dialogflow-cx');
/**
 * Example for regional endpoint:
 *   const locationId = 'us-central1'
 *   const client = new SessionsClient({apiEndpoint: 'us-central1-dialogflow.googleapis.com'})
 */
const client = new SessionsClient({apiEndpoint: locationId + '-dialogflow.googleapis.com'});

/**
 * Converts Slack request to a detectIntent request.
 */
function slackToDetectIntent(slackRequest, sessionPath){
    const request = {
        session: sessionPath,
        queryInput: {
            text: {
                text: slackRequest.text,
            },
            languageCode,
        },
    };

    return request;
}

/**
 * Takes as input a request from Slack and converts the request to
 * detectIntent request which is used to call the detectIntent() function
 * and finally output the response given by detectIntent().
 */
async function detectIntentResponse(slackRequest) {
    const sessionId = slackRequest.channel;
    const sessionPath = client.projectLocationAgentSessionPath(
        projectId,
        locationId,
        agentId,
        sessionId
    );
    console.info(sessionPath);

    request = slackToDetectIntent(slackRequest, sessionPath);
    const [response] = await client.detectIntent(request);

    return response;
};

async function convertToSlackMessage(responses, channel_id) {
    let replies = [];

    for(let response of responses.queryResult.responseMessages) {
        let reply;

        switch(true) {
            case response.hasOwnProperty('text'): {
                reply = {
                    channel: channel_id,
                    text: response.text.text.join()
                };
            }
            break;

            /**
             * For image responses the message format can be found
             * at https://api.slack.com/reference/block-kit/block-elements#image
             * For button responses the message format can be found at
             * https://api.slack.com/legacy/message-buttons
             */
            case response.hasOwnProperty('payload'): {
                reply = await structProtoToJson(response.payload);
                reply['channel'] = channel_id;
            }
            break;

            default:
        }
        if (reply) {
            replies.push(reply);
        }
    }

    return replies;
}

/**
 * Checks if the request is coming from a bot and if it is not
 * it will call detectIntentResponse() with the request as the input
 * and outputs the response. The initial check to make
 * sure the request is not from a bot is there to prevent the Integration
 * from replying to its own messages.
 */
async function eventToRequest(event, channel_id) {
    if(event.bot_id == '' || event.bot_id == null){
        const response = await detectIntentResponse(event);
        var requests = await convertToSlackMessage(response, channel_id);
        for(req of requests){
            try {
                await slackClient.chat.postMessage(req)
            } catch (error) {
                console.log(error.data)
            }
        }
    };
};

// Listens for messages posted in instant messages.
slackEvents.on('message', (event) => {
    (async () => {
        await eventToRequest(event, event.user);
    })();
});

// Listens for messages that mention the Slack App in channals
slackEvents.on('app_mention', (event) => {
    (async () => {
        await eventToRequest(event, event.channel);
    })();
});

slackEvents.on('error', console.error);

slackEvents.start(process.env.PORT).then(() => {
    console.log(`Server started on port ${process.env.PORT}`)
});

module.exports = {slackToDetectIntent, convertToSlackMessage};
<|endoftext|>


<commit_before>
var app = angular.module('mainModule', []);
// var app = angular.module('mainModule',[]);
app.controller('myCtrl', function($scope, $http){

    $scope.temp;
    // stages.html
    $scope.listOfDevice = {};
    $scope.listOfInitNode = [];
    $scope.listOfLastNode = [];
    $scope.list = [];
    $scope.listOfRoadMap = [];
    $scope.listOfRunningRoadMap = [];
    $scope.tree;
    $scope.nodeIds;
    $scope.loadTarget ={};
    $scope.getTarget;

    // settings.html
    $scope.brokerList=[];
    $scope.currentDeviceList;
    $scope.currentBroker={
        brokerId:""
    };
    $scope.settings={};
    $scope.newnode ={};
    $scope.newdevice={};
    $scope.file ={
        "ca":"",
        "hostCrt":"",
        "hostKey":""
    };
    // dashboard.html
    $scope.data={
        'x': 10,
        'y': 20
    };
    // statistics.html
    $scope.log;

    // ------------------------------------------

    $scope.addFile = function(){
        var files = [];
        $scope.temp = [];
        for(var i =1; i<= 3; ++i){
            files.push(document.getElementById('addSecurityFile'+i).files[0]);
        }
        setTimeout(function(){
            $.each(files, function(i, j){
                var reader = new FileReader();
                reader.readAsText(files[i]);
                reader.onload = function(e){
                    $scope.temp.push(reader.result);
                }
            });
            setTimeout(function(){
                $scope.file['caFile'] = $scope.temp[0];
                $scope.file['crtFile'] = $scope.temp[1];
                $scope.file['keyFile'] = $scope.temp[2];
                }, 1000);
        }, 1000);
    };

    $scope.saveDataBase = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/post_db",
            headers: {'Content-Type': 'application/json'},
            data: $scope.tree,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.runRoadMap = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/alive_check",
            headers: {'Content-Type': 'application/json'},
            data: $scope.tree,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(response.data.includes('0')){
                alert('no ack from devices');
            }else{
                $http({
                    withCredentials: false,
                    method: 'post',
                    url: "/run_db",
                    headers: {'Content-Type': 'application/json'},
                    data: $scope.tree,
                    contentType : 'application/json',
                    dataType: "json"
                })
            }
        });
    }
    $scope.killRoadMap = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/kill_db",
            headers: {'Content-Type': 'application/json'},
            data: $scope.tree,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.addBroker = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/add_broker",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newnode,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.addSecure = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/add_secure",
            headers: {'Content-Type': 'application/json'},
            data: $scope.file,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.loadRoadMap = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/load_roadmap",
            headers: {'Content-Type': 'application/json'},
            data: $scope.loadTarget,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.getTarget = response.data;
            }
        });
    }
    $scope.postUrlSettings = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/post_url_settings",
            headers: {'Content-Type': 'application/json'},
            data: $scope.settings,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.addDevice = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/add_device",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newdevice,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.findDevice = function(option){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/find_device",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newdevice,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(option=="add"){
                if(response.data=="no_connect"){
                    alert('Connect failed. Check MongoDB Url, Port.');
                }else{
                    if(response.data.length==0){
                        $scope.addDevice();
                    }else{
                        alert('deviceId already exist.');
                    }
                }
            }else if(option=="delete"){
                if(response.data=="no_connect"){
                    alert('Connect failed. Check MongoDB Url, Port.');
                }else{
                    if(response.data.length==1){
                        $scope.deleteDevice();
                    }
                }
            }
        });
    }
    $scope.deleteDevice = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/delete_device",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newdevice,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.deleteBroker = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/delete_broker",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newnode,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.findBroker = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/find_broker",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newnode,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                if(response.data.length==0){
                    $scope.addBroker();
                }else{
                    alert('brokerId already exist.');
                }
            }
        });
    }
    $scope.getBroker = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/get_broker",
            headers: {'Content-Type': 'application/json'},
            data: $scope.currentBroker,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.currentDeviceList = response.data[0]['deviceId'];
            }
        });
    }
    // get
    $scope.getBrokers = function(){
        $http({
            withCredentials: false,
            method: 'get',
            url: "/get_brokers"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.brokerList = response.data;
            }
        });
    }
    $scope.getSettings = function(){
        $http({
            withCredentials: false,
            method: 'get',
            url: "/get_settings"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.settings = response.data;
            }
        });
    }
    $scope.getRoadMaps = function(){
        $http({
            withCredentials: false,
            method: 'get',
            url: "/get_roadmaps"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.listOfRoadMap = response.data;
            }
        });
    }
    $scope.getRunningRoadMaps = function(){
        $http({
            withCredentials: false,
            method: 'get',
            url: "/get_running_roadmaps"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.listOfRunningRoadMap = response.data;
            }
        });
    }

    $scope.changeToTree = function (arrayList) {
        Object.setPrototypeOf(arrayList, Object.prototype);
        var rootNodes = {};

        var insert_incoming = function (list){
            rootNodes.incomingNode[list.target] = rootNodes.incomingNode[list.target] || [];
            rootNodes.incomingNode[list.target].push(list.source);
        }
        var insert_outcoming = function (list){
            rootNodes.outingNode[list.source] = rootNodes.outingNode[list.source] || [];
            rootNodes.outingNode[list.source].push(list.target);
        }
        if(this.getTarget){
            rootNodes.roadMapId = this.getTarget[0]['roadMapId'] || "";
        }
        else{
            rootNodes.roadMapId = "";
        }

        rootNodes.orderNode = this.orderNode['key'];
        rootNodes.initNode = this.listOfInitNode;
        rootNodes.lastNode = this.listOfLastNode;
        rootNodes.isInput = false;
        rootNodes.isOutput = false;
        rootNodes.incomingNode = rootNodes.incomingNode || {};
        rootNodes.outingNode = rootNodes.outingNode || {};
        rootNodes.nodeIds = this.nodeIds || {};
        for(var i=0; i<arrayList.length; ++i){
            insert_incoming(arrayList[i]);
            insert_outcoming(arrayList[i]);
        }
        // $scope.tree = rootNodes;
        $scope.tree = JSON.stringify(rootNodes, null, '   ');
        return rootNodes;
    };

});
<commit_msg>ssl  format  working<commit_after>
var app = angular.module('mainModule', []);
// var app = angular.module('mainModule',[]);
app.controller('myCtrl', function($scope, $http){

    $scope.temp;
    // stages.html
    $scope.listOfDevice = {};
    $scope.listOfInitNode = [];
    $scope.listOfLastNode = [];
    $scope.list = [];
    $scope.listOfRoadMap = [];
    $scope.listOfRunningRoadMap = [];
    $scope.tree;
    $scope.nodeIds;
    $scope.loadTarget ={};
    $scope.getTarget;

    // settings.html
    $scope.brokerList=[];
    $scope.currentDeviceList;
    $scope.currentBroker={
        brokerId:""
    };
    $scope.settings={};
    $scope.newnode ={};
    $scope.newdevice={};
    $scope.file ={
        "ca":"",
        "hostCrt":"",
        "hostKey":""
    };
    // dashboard.html
    $scope.data={
        'x': 10,
        'y': 20
    };
    // statistics.html
    $scope.log;

    // ------------------------------------------

    $scope.addFile = function(){
        var files = [];
        $scope.temp = [];
        for(var i =1; i<= 3; ++i){
            files.push(document.getElementById('addSecurityFile'+i).files[0]);
        }
        setTimeout(function(){
            $.each(files, function(i, j){
                var reader = new FileReader();
                reader.readAsText(files[i]);
                reader.read(files[i]);
                reader.onload = function(e){
                    $scope.temp.push(reader.result);
                }
            });
            setTimeout(function(){
                $scope.file['caFile'] = $scope.temp[0];
                $scope.file['crtFile'] = $scope.temp[1];
                $scope.file['keyFile'] = $scope.temp[2];
                }, 1000);
        }, 1000);
        console.log($scope.file);
    };

    $scope.saveDataBase = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/post_db",
            headers: {'Content-Type': 'application/json'},
            data: $scope.tree,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.runRoadMap = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/alive_check",
            headers: {'Content-Type': 'application/json'},
            data: $scope.tree,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(response.data.includes('0')){
                alert('no ack from devices');
            }else{
                $http({
                    withCredentials: false,
                    method: 'post',
                    url: "/run_db",
                    headers: {'Content-Type': 'application/json'},
                    data: $scope.tree,
                    contentType : 'application/json',
                    dataType: "json"
                })
            }
        });
    }
    $scope.killRoadMap = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/kill_db",
            headers: {'Content-Type': 'application/json'},
            data: $scope.tree,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.addBroker = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/add_broker",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newnode,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.addSecure = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/add_secure",
            headers: {'Content-Type': 'application/json'},
            data: $scope.file,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.loadRoadMap = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/load_roadmap",
            headers: {'Content-Type': 'application/json'},
            data: $scope.loadTarget,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.getTarget = response.data;
            }
        });
    }
    $scope.postUrlSettings = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/post_url_settings",
            headers: {'Content-Type': 'application/json'},
            data: $scope.settings,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.addDevice = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/add_device",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newdevice,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.findDevice = function(option){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/find_device",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newdevice,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(option=="add"){
                if(response.data=="no_connect"){
                    alert('Connect failed. Check MongoDB Url, Port.');
                }else{
                    if(response.data.length==0){
                        $scope.addDevice();
                    }else{
                        alert('deviceId already exist.');
                    }
                }
            }else if(option=="delete"){
                if(response.data=="no_connect"){
                    alert('Connect failed. Check MongoDB Url, Port.');
                }else{
                    if(response.data.length==1){
                        $scope.deleteDevice();
                    }
                }
            }
        });
    }
    $scope.deleteDevice = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/delete_device",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newdevice,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.deleteBroker = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/delete_broker",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newnode,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
        });
    }
    $scope.findBroker = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/find_broker",
            headers: {'Content-Type': 'application/json'},
            data: $scope.newnode,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                if(response.data.length==0){
                    $scope.addBroker();
                }else{
                    alert('brokerId already exist.');
                }
            }
        });
    }
    $scope.getBroker = function(){
        $http({
            withCredentials: false,
            method: 'post',
            url: "/get_broker",
            headers: {'Content-Type': 'application/json'},
            data: $scope.currentBroker,
            contentType : 'application/json',
            dataType: "json"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.currentDeviceList = response.data[0]['deviceId'];
            }
        });
    }
    // get
    $scope.getBrokers = function(){
        $http({
            withCredentials: false,
            method: 'get',
            url: "/get_brokers"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.brokerList = response.data;
            }
        });
    }
    $scope.getSettings = function(){
        $http({
            withCredentials: false,
            method: 'get',
            url: "/get_settings"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.settings = response.data;
            }
        });
    }
    $scope.getRoadMaps = function(){
        $http({
            withCredentials: false,
            method: 'get',
            url: "/get_roadmaps"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.listOfRoadMap = response.data;
            }
        });
    }
    $scope.getRunningRoadMaps = function(){
        $http({
            withCredentials: false,
            method: 'get',
            url: "/get_running_roadmaps"
        }).then(function(response){
            if(response.data=="no_connect"){
                alert('Connect failed. Check MongoDB Url, Port.');
            }else{
                $scope.listOfRunningRoadMap = response.data;
            }
        });
    }

    $scope.changeToTree = function (arrayList) {
        Object.setPrototypeOf(arrayList, Object.prototype);
        var rootNodes = {};

        var insert_incoming = function (list){
            rootNodes.incomingNode[list.target] = rootNodes.incomingNode[list.target] || [];
            rootNodes.incomingNode[list.target].push(list.source);
        }
        var insert_outcoming = function (list){
            rootNodes.outingNode[list.source] = rootNodes.outingNode[list.source] || [];
            rootNodes.outingNode[list.source].push(list.target);
        }
        if(this.getTarget){
            rootNodes.roadMapId = this.getTarget[0]['roadMapId'] || "";
        }
        else{
            rootNodes.roadMapId = "";
        }

        rootNodes.orderNode = this.orderNode['key'];
        rootNodes.initNode = this.listOfInitNode;
        rootNodes.lastNode = this.listOfLastNode;
        rootNodes.isInput = false;
        rootNodes.isOutput = false;
        rootNodes.incomingNode = rootNodes.incomingNode || {};
        rootNodes.outingNode = rootNodes.outingNode || {};
        rootNodes.nodeIds = this.nodeIds || {};
        for(var i=0; i<arrayList.length; ++i){
            insert_incoming(arrayList[i]);
            insert_outcoming(arrayList[i]);
        }
        // $scope.tree = rootNodes;
        $scope.tree = JSON.stringify(rootNodes, null, '   ');
        return rootNodes;
    };

});
<|endoftext|>


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

  var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

  function decode (c) {
    return indexOf(lookup, c)
  }

  function b64ToByteArray(b64) {
    var i, j, l, tmp, placeHolders, arr;

    if (b64.length % 4 > 0) {
      throw 'Invalid string. Length must be a multiple of 4';
    }

    // the number of equal signs (place holders)
    // if there are two placeholders, than the two characters before it
    // represent one byte
    // if there is only one, then the three characters before it represent 2 bytes
    // this is just a cheap hack to not do indexOf twice
    placeHolders = indexOf(b64, '=');
    placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0;

    // base64 is 4/3 + up to two characters of the original data
    arr = new Uint8Array(b64.length * 3 / 4 - placeHolders);

    // if there are placeholders, only get up to the last complete 4 chars
    l = placeHolders > 0 ? b64.length - 4 : b64.length;

    var L = 0

    function push (v) {
      arr[L++] = v
    }

    for (i = 0, j = 0; i < l; i += 4, j += 3) {
      tmp = (decode(b64.charAt(i)) << 18) | (indexOf(lookup, b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3));
      push((tmp & 0xFF0000) >> 16);
      push((tmp & 0xFF00) >> 8);
      push(tmp & 0xFF);
    }

    if (placeHolders === 2) {
      tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4);
      push(tmp & 0xFF);
    } else if (placeHolders === 1) {
      tmp = (indexOf(lookup, b64.charAt(i)) << 10) | (indexOf(lookup, b64.charAt(i + 1)) << 4) | (indexOf(lookup, b64.charAt(i + 2)) >> 2);
      push((tmp >> 8) & 0xFF);
      push(tmp & 0xFF);
    }

    return arr;
  }

  function uint8ToBase64(uint8) {
    var i,
      extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
      output = "",
      temp, length;

    function tripletToBase64 (num) {
      return lookup.charAt(num >> 18 & 0x3F) + lookup.charAt(num >> 12 & 0x3F) + lookup.charAt(num >> 6 & 0x3F) + lookup.charAt(num & 0x3F);
    };

    // go through the array every three bytes, we'll deal with trailing stuff later
    for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
      temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
      output += tripletToBase64(temp);
    }

    // pad the end with zeros, but make sure to not forget the extra bytes
    switch (extraBytes) {
      case 1:
        temp = uint8[uint8.length - 1];
        output += lookup.charAt(temp >> 2);
        output += lookup.charAt((temp << 4) & 0x3F);
        output += '==';
        break;
      case 2:
        temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
        output += lookup.charAt(temp >> 10);
        output += lookup.charAt((temp >> 4) & 0x3F);
        output += lookup.charAt((temp << 2) & 0x3F);
        output += '=';
        break;
    }

    return output;
  }

  module.exports.toByteArray = b64ToByteArray;
  module.exports.fromByteArray = uint8ToBase64;
}());

function indexOf (arr, elt /*, from*/) {
  var len = arr.length;

  var from = Number(arguments[1]) || 0;
  from = (from < 0)
    ? Math.ceil(from)
    : Math.floor(from);
  if (from < 0)
    from += len;

  for (; from < len; from++) {
    if ((typeof arr === 'string' && arr.charAt(from) === elt) ||
        (typeof arr !== 'string' && arr[from] === elt)) {
      return from;
    }
  }
  return -1;
}
<commit_msg>use hardcoded ranges instead of indexOf<commit_after>var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

;(function (exports) {
  'use strict';

  var ZERO   = '0'.charCodeAt(0)
  var PLUS   = '+'.charCodeAt(0)
  var SLASH  = '/'.charCodeAt(0)
  var NUMBER = '0'.charCodeAt(0)
  var LOWER  = 'a'.charCodeAt(0)
  var UPPER  = 'A'.charCodeAt(0)

  function decode (elt) {
    var code = elt.charCodeAt(0)
    if(code === PLUS)
      return 62 // '+'
    if(code === SLASH)
      return 63 // '/'
    if(code < NUMBER)
      return -1 //no match
    if(code < NUMBER + 10)
      return code - NUMBER + 26 + 26
    if(code < UPPER + 26)
      return code - UPPER
    if(code < LOWER + 26)
      return code - LOWER + 26
  }

  function b64ToByteArray(b64) {
    var i, j, l, tmp, placeHolders, arr;

    if (b64.length % 4 > 0) {
      throw 'Invalid string. Length must be a multiple of 4';
    }

    // the number of equal signs (place holders)
    // if there are two placeholders, than the two characters before it
    // represent one byte
    // if there is only one, then the three characters before it represent 2 bytes
    // this is just a cheap hack to not do indexOf twice
    placeHolders = indexOf(b64, '=');
    placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0;

    // base64 is 4/3 + up to two characters of the original data
    arr = new Uint8Array(b64.length * 3 / 4 - placeHolders);

    // if there are placeholders, only get up to the last complete 4 chars
    l = placeHolders > 0 ? b64.length - 4 : b64.length;

    var L = 0

    function push (v) {
      arr[L++] = v
    }

    for (i = 0, j = 0; i < l; i += 4, j += 3) {
      tmp = (decode(b64.charAt(i)) << 18) | (indexOf(lookup, b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3));
      push((tmp & 0xFF0000) >> 16);
      push((tmp & 0xFF00) >> 8);
      push(tmp & 0xFF);
    }

    if (placeHolders === 2) {
      tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4);
      push(tmp & 0xFF);
    } else if (placeHolders === 1) {
      tmp = (indexOf(lookup, b64.charAt(i)) << 10) | (indexOf(lookup, b64.charAt(i + 1)) << 4) | (indexOf(lookup, b64.charAt(i + 2)) >> 2);
      push((tmp >> 8) & 0xFF);
      push(tmp & 0xFF);
    }

    return arr;
  }

  function uint8ToBase64(uint8) {
    var i,
      extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
      output = "",
      temp, length;

    function tripletToBase64 (num) {
      return lookup.charAt(num >> 18 & 0x3F) + lookup.charAt(num >> 12 & 0x3F) + lookup.charAt(num >> 6 & 0x3F) + lookup.charAt(num & 0x3F);
    };

    // go through the array every three bytes, we'll deal with trailing stuff later
    for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
      temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
      output += tripletToBase64(temp);
    }

    // pad the end with zeros, but make sure to not forget the extra bytes
    switch (extraBytes) {
      case 1:
        temp = uint8[uint8.length - 1];
        output += lookup.charAt(temp >> 2);
        output += lookup.charAt((temp << 4) & 0x3F);
        output += '==';
        break;
      case 2:
        temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
        output += lookup.charAt(temp >> 10);
        output += lookup.charAt((temp >> 4) & 0x3F);
        output += lookup.charAt((temp << 2) & 0x3F);
        output += '=';
        break;
    }

    return output;
  }

  module.exports.toByteArray = b64ToByteArray;
  module.exports.fromByteArray = uint8ToBase64;
  module.exports.indexOf = indexOf
  module.exports.lookup = lookup
}());

function indexOf (arr, elt /*, from*/) {

  var len = arr.length;

  var from = Number(arguments[1]) || 0;
  from = (from < 0)
    ? Math.ceil(from)
    : Math.floor(from);
  if (from < 0)
    from += len;

  for (; from < len; from++) {
    if ((typeof arr === 'string' && arr.charAt(from) === elt) ||
        (typeof arr !== 'string' && arr[from] === elt)) {
      return from;
    }
  }
  return -1;
}

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the "flow" directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 */
/* BOM */

declare class Screen {
    availHeight: number;
    availLeft: number;
    availop: number;
    availWidth: number;
    colorDepth: number;
    height: number;
    left: number;
    mozOrientation?: string;
    onmozorientationchange?: any;
    orientation?: {
        angle: number;
        onchange: any;
        type: string;
    };
    pixelDepth: number;
    top: number;
    width: number;
    mozLockOrientation?: Function;
    mozUnlockOrientation?: Function;
}

declare var screen: Screen;
declare var window: any;

declare class Navigator {
    appCodeName: string;
    appName: string;
    appVersion: string;
    cookieEnabled: boolean;
    buildId: string;
    doNotTrack?: any;
    geolocation: Geolocation;
    mediaDevices?: Object;
    hardwareConcurrency: number;
    language: string;
    languages: Array<string>;
    maxTouchPoints: number;
    mimeTypes: Array<Object>;
    onLine: boolean;
    ospu: string;
    permissions: any;
    platform: string;
    plugins: Array<Object>;
    product: string;
    productSub: string;
    serviceWorker?: Object;
    userAgent: string;
    vendor: string;
    vendorSub: string;
    getBattery?: Function;
    getGamepads?: Function;
    getStorageUpdates?: Function;
    javaEnabled: Function;
    registerProtocolHandler: Function;
    requestMIDIAccess?: Function;
    requestMediaKeySystemAccess?: Function;
    sendBeacon?: Function;
    unregisterProtocolHandler: Function;
    vibrate?: Function;
    webkitGetUserMedia?: Function;
    mozGetUserMedia?: Function;
    taintEnabled?: Function;
}

declare var navigator: Navigator;

declare class History {
    length: number;
    state: any;
    back(distance?: any): void;
    forward(distance?: any): void;
    go(delta?: any): void;
    replaceState(statedata: any, title: string, url?: string): void;
    pushState(statedata: any, title: string, url?: string): void;
}

declare var history: History;

declare class Location {
    hash: string;
    origin: string;
    protocol: string;
    search: string;
    href: string;
    hostname: string;
    port: string;
    pathname: string;
    host: string;
    reload(flag?: boolean): void;
    replace(url: string): void;
    assign(url: string): void;
    toString(): string;
}

declare var location: Location;

///////////////////////////////////////////////////////////////////////////////

declare class DOMParser {
    parseFromString(source: string, mimeType: string): Document;
}

declare class FormData {
    append(name: any, value: any, blobName?: string): void;
}

declare class MutationRecord {
    oldValue: string;
    previousSibling: Node;
    addedNodes: NodeList;
    attributeName: string;
    removedNodes: NodeList;
    target: Node;
    nextSibling: Node;
    attributeNamespace: string;
    type: string;
}

declare class MutationObserver {
    constructor(callback: (arr: Array<MutationRecord>, observer: MutationObserver)=>any): void;
    observe(target: Node, options: {
        childList?: boolean;
        attributes?: boolean;
        characterData?: boolean;
        subtree?: boolean;
        attributeOldValue?: boolean;
        characterDataOldValue?: boolean;
        attributeFilter?: Array<string>;
    }): void;
    takeRecords(): Array<MutationRecord>;
    disconnect(): void;
}

declare var NodeFilter: {
    acceptNode(n: Node): number;
    SHOW_ENTITY_REFERENCE: number;
    SHOW_NOTATION: number;
    SHOW_ENTITY: number;
    SHOW_DOCUMENT: number;
    SHOW_PROCESSING_INSTRUCTION: number;
    FILTER_REJECT: number;
    SHOW_CDATA_SECTION: number;
    FILTER_ACCEPT: number;
    SHOW_ALL: number;
    SHOW_DOCUMENT_TYPE: number;
    SHOW_TEXT: number;
    SHOW_ELEMENT: number;
    SHOW_COMMENT: number;
    FILTER_SKIP: number;
    SHOW_ATTRIBUTE: number;
    SHOW_DOCUMENT_FRAGMENT: number;
};

declare class WebSocket extends EventTarget {
    constructor(url: string, protocols?: string | Array<string>): void;
    protocol: string;
    readyState: number;
    bufferedAmount: number;
    onopen: (ev: Event) => any;
    extensions: string;
    onmessage: (ev: MessageEvent) => any;
    onclose: (ev: Event) => any;
    onerror: (ev: Event) => any;
    binaryType: string;
    url: string;
    close(code?: number, reason?: string): void;
    send(data: any): void;
    OPEN: number;
    CLOSING: number;
    CONNECTING: number;
    CLOSED: number;
}

declare class Worker extends EventTarget {
    constructor(stringUrl: string): void;
    onerror: (ev: Event) => any;
    onmessage: (ev: Event) => any;
    postMessage(message: any, ports?: any): void;
    terminate(): void;
}

declare class XDomainRequest {
    timeout: number;
    onerror: (ev: Event) => any;
    onload: (ev: Event) => any;
    onprogress: (ev: Event) => any;
    ontimeout: (ev: Event) => any;
    responseText: string;
    contentType: string;
    open(method: string, url: string): void;
    abort(): void;
    send(data?: any): void;
    addEventListener(type: string, listener: (evt: any) => void, useCapture?: boolean): void;

    statics: {
        create(): XDomainRequest;
    }
}

declare class XMLHttpRequest extends EventTarget {
    responseBody: any;
    status: number;
    readyState: number;
    responseText: string;
    responseXML: any;
    ontimeout: (ev: Event) => any;
    statusText: string;
    onreadystatechange: (ev: Event) => any;
    timeout: number;
    onload: (ev: Event) => any;
    response: any;
    withCredentials: boolean;
    onprogress: (ev: ProgressEvent) => any;
    onabort: (ev: Event) => any;
    responseType: string;
    onloadend: (ev: Event) => any;
    upload: XMLHttpRequestEventTarget;
    onerror: (ev: Event) => any;
    onloadstart: (ev: Event) => any;
    msCaching: string;
    open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
    send(data?: any): void;
    abort(): void;
    getAllResponseHeaders(): string;
    setRequestHeader(header: string, value: string): void;
    getResponseHeader(header: string): string;
    msCachingEnabled(): boolean;
    overrideMimeType(mime: string): void;
    LOADING: number;
    DONE: number;
    UNSENT: number;
    OPENED: number;
    HEADERS_RECEIVED: number;

    statics: {
        create(): XMLHttpRequest;
    }
}

declare class XMLHttpRequestEventTarget extends EventTarget {
    onprogress: (ev: ProgressEvent) => any;
    onerror: (ev: Event) => any;
    onload: (ev: Event) => any;
    ontimeout: (ev: Event) => any;
    onabort: (ev: Event) => any;
    onloadstart: (ev: Event) => any;
    onloadend: (ev: Event) => any;
}

declare class XMLSerializer {
    serializeToString(target: Node): string;
}

declare class Geolocation {
    getCurrentPosition: (
        success: (position: Position) => any,
        error?: (error: PositionError) => any,
        options?: PositionOptions
    ) => any;
    watchPosition: (
        success: (position: Position) => any,
        error?: (error: PositionError) => any,
        options?: PositionOptions
    ) => any;
    clearWatch: any;
}

declare class Position {
    coords: Coordinates;
    timestamp: number;
}

declare class Coordinates {
    latitude: number;
    longitude: number;
    altitude?: number;
    accuracy: number;
    altitudeAccuracy?: number;
    heading?: number;
}

declare class PositionError {
    code: number;
    message: string;
    PERMISSION_DENIED: number;
    POSITION_UNAVAILABLE: number;
    TIMEOUT: number;
}

declare class PositionOptions {
    enableHighAccuracy: boolean;
    timeout: number;
    maximumAge: number;
}
<commit_msg>Add a few methods to navigator<commit_after>/**
 * Copyright (c) 2014, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the "flow" directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 */
/* BOM */

declare class Screen {
    availHeight: number;
    availLeft: number;
    availop: number;
    availWidth: number;
    colorDepth: number;
    height: number;
    left: number;
    mozOrientation?: string;
    onmozorientationchange?: any;
    orientation?: {
        angle: number;
        onchange: any;
        type: string;
    };
    pixelDepth: number;
    top: number;
    width: number;
    mozLockOrientation?: Function;
    mozUnlockOrientation?: Function;
}

declare var screen: Screen;
declare var window: any;

declare class Navigator {
    appCodeName: string;
    appName: string;
    appVersion: string;
    cookieEnabled: boolean;
    buildId: string;
    doNotTrack?: any;
    geolocation: Geolocation;
    mediaDevices?: Object;
    hardwareConcurrency: number;
    language: string;
    languages: Array<string>;
    maxTouchPoints: number;
    mimeTypes: Array<Object>;
    onLine: boolean;
    ospu: string;
    permissions: any;
    platform: string;
    plugins: Array<Object>;
    product: string;
    productSub: string;
    serviceWorker?: Object;
    userAgent: string;
    vendor: string;
    vendorSub: string;
    getBattery?: Function;
    getGamepads?: Function;
    webkitGetGamepads?: Function;
    mozGetGamepads?: Function;
    gamepads?: any,
    webkitGamepads?: any,
    mozGamepads?: any,
    getStorageUpdates?: Function;
    javaEnabled: Function;
    registerProtocolHandler: Function;
    requestMIDIAccess?: Function;
    requestMediaKeySystemAccess?: Function;
    sendBeacon?: Function;
    unregisterProtocolHandler: Function;
    vibrate?: Function;
    getUserMedia?: Function;
    webkitGetUserMedia?: Function;
    mozGetUserMedia?: Function;
    msGetUserMedia?: Function;
    taintEnabled?: Function;
}

declare var navigator: Navigator;

declare class History {
    length: number;
    state: any;
    back(distance?: any): void;
    forward(distance?: any): void;
    go(delta?: any): void;
    replaceState(statedata: any, title: string, url?: string): void;
    pushState(statedata: any, title: string, url?: string): void;
}

declare var history: History;

declare class Location {
    hash: string;
    origin: string;
    protocol: string;
    search: string;
    href: string;
    hostname: string;
    port: string;
    pathname: string;
    host: string;
    reload(flag?: boolean): void;
    replace(url: string): void;
    assign(url: string): void;
    toString(): string;
}

declare var location: Location;

///////////////////////////////////////////////////////////////////////////////

declare class DOMParser {
    parseFromString(source: string, mimeType: string): Document;
}

declare class FormData {
    append(name: any, value: any, blobName?: string): void;
}

declare class MutationRecord {
    oldValue: string;
    previousSibling: Node;
    addedNodes: NodeList;
    attributeName: string;
    removedNodes: NodeList;
    target: Node;
    nextSibling: Node;
    attributeNamespace: string;
    type: string;
}

declare class MutationObserver {
    constructor(callback: (arr: Array<MutationRecord>, observer: MutationObserver)=>any): void;
    observe(target: Node, options: {
        childList?: boolean;
        attributes?: boolean;
        characterData?: boolean;
        subtree?: boolean;
        attributeOldValue?: boolean;
        characterDataOldValue?: boolean;
        attributeFilter?: Array<string>;
    }): void;
    takeRecords(): Array<MutationRecord>;
    disconnect(): void;
}

declare var NodeFilter: {
    acceptNode(n: Node): number;
    SHOW_ENTITY_REFERENCE: number;
    SHOW_NOTATION: number;
    SHOW_ENTITY: number;
    SHOW_DOCUMENT: number;
    SHOW_PROCESSING_INSTRUCTION: number;
    FILTER_REJECT: number;
    SHOW_CDATA_SECTION: number;
    FILTER_ACCEPT: number;
    SHOW_ALL: number;
    SHOW_DOCUMENT_TYPE: number;
    SHOW_TEXT: number;
    SHOW_ELEMENT: number;
    SHOW_COMMENT: number;
    FILTER_SKIP: number;
    SHOW_ATTRIBUTE: number;
    SHOW_DOCUMENT_FRAGMENT: number;
};

declare class WebSocket extends EventTarget {
    constructor(url: string, protocols?: string | Array<string>): void;
    protocol: string;
    readyState: number;
    bufferedAmount: number;
    onopen: (ev: Event) => any;
    extensions: string;
    onmessage: (ev: MessageEvent) => any;
    onclose: (ev: Event) => any;
    onerror: (ev: Event) => any;
    binaryType: string;
    url: string;
    close(code?: number, reason?: string): void;
    send(data: any): void;
    OPEN: number;
    CLOSING: number;
    CONNECTING: number;
    CLOSED: number;
}

declare class Worker extends EventTarget {
    constructor(stringUrl: string): void;
    onerror: (ev: Event) => any;
    onmessage: (ev: Event) => any;
    postMessage(message: any, ports?: any): void;
    terminate(): void;
}

declare class XDomainRequest {
    timeout: number;
    onerror: (ev: Event) => any;
    onload: (ev: Event) => any;
    onprogress: (ev: Event) => any;
    ontimeout: (ev: Event) => any;
    responseText: string;
    contentType: string;
    open(method: string, url: string): void;
    abort(): void;
    send(data?: any): void;
    addEventListener(type: string, listener: (evt: any) => void, useCapture?: boolean): void;

    statics: {
        create(): XDomainRequest;
    }
}

declare class XMLHttpRequest extends EventTarget {
    responseBody: any;
    status: number;
    readyState: number;
    responseText: string;
    responseXML: any;
    ontimeout: (ev: Event) => any;
    statusText: string;
    onreadystatechange: (ev: Event) => any;
    timeout: number;
    onload: (ev: Event) => any;
    response: any;
    withCredentials: boolean;
    onprogress: (ev: ProgressEvent) => any;
    onabort: (ev: Event) => any;
    responseType: string;
    onloadend: (ev: Event) => any;
    upload: XMLHttpRequestEventTarget;
    onerror: (ev: Event) => any;
    onloadstart: (ev: Event) => any;
    msCaching: string;
    open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
    send(data?: any): void;
    abort(): void;
    getAllResponseHeaders(): string;
    setRequestHeader(header: string, value: string): void;
    getResponseHeader(header: string): string;
    msCachingEnabled(): boolean;
    overrideMimeType(mime: string): void;
    LOADING: number;
    DONE: number;
    UNSENT: number;
    OPENED: number;
    HEADERS_RECEIVED: number;

    statics: {
        create(): XMLHttpRequest;
    }
}

declare class XMLHttpRequestEventTarget extends EventTarget {
    onprogress: (ev: ProgressEvent) => any;
    onerror: (ev: Event) => any;
    onload: (ev: Event) => any;
    ontimeout: (ev: Event) => any;
    onabort: (ev: Event) => any;
    onloadstart: (ev: Event) => any;
    onloadend: (ev: Event) => any;
}

declare class XMLSerializer {
    serializeToString(target: Node): string;
}

declare class Geolocation {
    getCurrentPosition: (
        success: (position: Position) => any,
        error?: (error: PositionError) => any,
        options?: PositionOptions
    ) => any;
    watchPosition: (
        success: (position: Position) => any,
        error?: (error: PositionError) => any,
        options?: PositionOptions
    ) => any;
    clearWatch: any;
}

declare class Position {
    coords: Coordinates;
    timestamp: number;
}

declare class Coordinates {
    latitude: number;
    longitude: number;
    altitude?: number;
    accuracy: number;
    altitudeAccuracy?: number;
    heading?: number;
}

declare class PositionError {
    code: number;
    message: string;
    PERMISSION_DENIED: number;
    POSITION_UNAVAILABLE: number;
    TIMEOUT: number;
}

declare class PositionOptions {
    enableHighAccuracy: boolean;
    timeout: number;
    maximumAge: number;
}
<|endoftext|>