<commit_before>'use strict';

module.exports = {

	/* APP CONFIG */
	APP_NAME: 					'now@ucsandiego',
	GOOGLE_ANALYTICS_ID: 		'UA-59591330-3',
	DEBUG_ENABLED: 				false,				// Disables all logger functions (i.e. logger.log) if set to false (console.log is unaffected)
	NAVIGATOR_ENABLED: 			false,				// IOS setting only - if true, app uses Navigator instead of Navigator IOS
													// Navigator will always be used for Android

	/* CARDS */
	SHUTTLE_CARD_ENABLED: 		true,
	WEATHER_CARD_ENABLED: 		true,
	EVENTS_CARD_ENABLED: 		true,
	TOPSTORIES_CARD_ENABLED: 	true,
	NEARBY_CARD_ENABLED: 		true,

	/* APIS / ENDPOINTS */
	WEATHER_API_URL: 			'https://e29re7itnc.execute-api.us-west-2.amazonaws.com/prod/forecast',
	SURF_API_URL: 				'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/surffeed.json',
	TOP_STORIES_API_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/allstories.json',
	EVENTS_API_URL: 			'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/student_events.json',
	SHUTTLE_STOPS_API_URL: 		'https://ies4wyrlx9.execute-api.us-west-2.amazonaws.com/prod/stops/',
	DINING_API_URL: 			'https://s3-us-west-2.amazonaws.com/ucsd-mobile/v1/dining-feed.json',
	FEEDBACK_URL: 				'https://eforms.ucsd.edu/view.php?id=175631',
	PRIVACY_POLICY_URL: 		'http://www.ucsd.edu/_about/legal/uc-san-diego-website-privacy-policy.html',
	NODE_MARKERS_BASE_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/nearby_markers/',
	WEATHER_ICON_BASE_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/images/v1/weather-icons/',
	WELCOME_WEEK_API_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/welcome_week_events.json',

};<commit_msg>Updates to AppSettings<commit_after>'use strict';

module.exports = {

	/* APP CONFIG */
	APP_NAME: 					'now@ucsandiego',
	GOOGLE_ANALYTICS_ID: 		'UA-81825078-1',
	DEBUG_ENABLED: 				false,				// Disables all logger functions (i.e. logger.log) if set to false (console.log is unaffected)
	NAVIGATOR_ENABLED: 			false,				// IOS setting only - if true, app uses Navigator instead of Navigator IOS
													// Navigator will always be used for Android

	/* CARDS */
	WELCOME_WEEK_ENABLED: 		true,
	SHUTTLE_CARD_ENABLED: 		true,
	WEATHER_CARD_ENABLED: 		true,
	EVENTS_CARD_ENABLED: 		true,
	TOPSTORIES_CARD_ENABLED: 	true,
	NEARBY_CARD_ENABLED: 		true,
	DINING_CARD_ENABLED: 		true,

	/* APIS / ENDPOINTS */
	WEATHER_API_URL: 			'https://e29re7itnc.execute-api.us-west-2.amazonaws.com/prod/forecast',
	SURF_API_URL: 				'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/surffeed.json',
	TOP_STORIES_API_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/allstories.json',
	EVENTS_API_URL: 			'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/student_events.json',
	SHUTTLE_STOPS_API_URL: 		'https://ies4wyrlx9.execute-api.us-west-2.amazonaws.com/prod/stops/',
	DINING_API_URL: 			'https://s3-us-west-2.amazonaws.com/ucsd-mobile/v1/dining-feed.json',
	FEEDBACK_URL: 				'https://eforms.ucsd.edu/view.php?id=175631',
	PRIVACY_POLICY_URL: 		'http://www.ucsd.edu/_about/legal/uc-san-diego-website-privacy-policy.html',
	NODE_MARKERS_BASE_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/nearby_markers/',
	WEATHER_ICON_BASE_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/images/v1/weather-icons/',
	WELCOME_WEEK_API_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/welcome_week_events.json',

};<|endoftext|>


<commit_before>/**
 *
 * GeometryCanvas
 *
 */

import React from 'react';
import styled from 'styled-components';

import Button from 'material-ui/Button';
import axios from 'axios';

import PropTypes from 'prop-types';
import { download } from 'utils';

import { MdFileDownload } from 'react-icons/lib/md';

const MButton = styled(Button)`
  margin: 12px,
`;

class GeometryCanvas extends React.Component { // eslint-disable-line react/prefer-stateless-function
  componentDidMount() {
    let cifdata = this.props.cifdata;
    if (this.props.cifurl !== '') {
      axios.get(this.props.cifurl).then((res) => {
        cifdata = res.data.cifdata;
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.innerHTML = `
function _load_lib(url, callback){
  id =  'load_' + url;
  var s = document.createElement('script');
  s.src = url;
  s.id = id;
  s.async = true;
  s.onreadystatechange = s.onload = callback;
  s.onerror = function(){console.warn("failed to load library " + url);};
  document.getElementsByTagName("head")[0].appendChild(s);

}
// Load Libraries
_load_lib("https://code.jquery.com/jquery-3.2.1.min.js", function(){
  _load_lib("https://hub.chemdoodle.com/cwc/8.0.0/ChemDoodleWeb.js", function(){

  var rotationMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

  //Code
  let tfcanvas = new ChemDoodle.TransformCanvas3D('${this.props.id}_view');
  let cif = ChemDoodle.readCIF(\`${cifdata}\`, 2, 2, 1);

  tfcanvas.specs.set3DRepresentation('Ball and Stick');
  tfcanvas.specs.backgroundColor = '${this.props.color}';
  tfcanvas.specs.projectionPerspective_3D = true;
  tfcanvas.specs.atoms_displayLabels_3D = true;
  tfcanvas.specs.crystals_unitCellLineWidth = 5;
  tfcanvas.specs.shapes_color = 'black';
  tfcanvas.specs.shapes_lineWidth = 1;
  tfcanvas.specs.fog_mode_3D = 0;
  tfcanvas.specs.shadow_3D = false;
  tfcanvas.specs.atoms_useJMOLColors = true;
  tfcanvas.specs.compass_display = true;
  tfcanvas.loadContent([cif.molecule], [cif.unitCell]);
  });
});`;
        document.getElementById(`${this.props.id}_view`).appendChild(script);
      });
    } else {
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.innerHTML = `
function _load_lib(url, callback){
  id =  'load_' + url;
  var s = document.createElement('script');
  s.src = url;
  s.id = id;
  s.async = true;
  s.onreadystatechange = s.onload = callback;
  s.onerror = function(){console.warn("failed to load library " + url);};
  document.getElementsByTagName("head")[0].appendChild(s);

}
// Load Libraries
_load_lib("https://code.jquery.com/jquery-3.2.1.min.js", function(){
  _load_lib("https://hub.chemdoodle.com/cwc/8.0.0/ChemDoodleWeb.js", function(){

  var rotationMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

  //Code
  let tfcanvas = new ChemDoodle.TransformCanvas3D('${this.props.id}_view');
  let cif = ChemDoodle.readCIF(\`${cifdata}\`, 1, 1, 1);

  tfcanvas.specs.set3DRepresentation('Ball and Stick');
  tfcanvas.specs.backgroundColor = '${this.props.color}';
  tfcanvas.specs.projectionPerspective_3D = true;
  tfcanvas.specs.atoms_displayLabels_3D = true;
  tfcanvas.specs.crystals_unitCellLineWidth = 5;
  tfcanvas.specs.shapes_color = 'black';
  tfcanvas.specs.shapes_lineWidth = 1;
  tfcanvas.loadContent([cif.molecule], [cif.unitCell]);
  });
});
    `;
      document.getElementById(`${this.props.id}_view`).appendChild(script);
    }
  }

  render() {
    return (

        <p id={`${this.props.id}_script`} />
        <canvas
          id={`${this.props.id}_view`}
          height={this.props.height}
          width={this.props.width}
          style={{
            borderWidth: 1,
            borderColor: '#000000',
            borderStyle: 'solid',
          }}
        />

        <MButton
          primary
          raised
          onClick={() => { download(`structure_${this.props.id}.cif`, this.props.cifdata); }}
          style={{
            margin: 12,
          }}
        >
          <MdFileDownload /> Download CIF
        </MButton>

    );
  }
}

GeometryCanvas.defaultProps = {
  height: 550,
  width: 550,
  color: '#fff',
  cifdata: '',
  cifurl: '',
};

GeometryCanvas.propTypes = {
  id: PropTypes.string.isRequired,
  cifdata: PropTypes.string,
  cifurl: PropTypes.string,
  height: PropTypes.number,
  width: PropTypes.number,
  color: PropTypes.string,
};

export default GeometryCanvas;
<commit_msg>Removed faulty primary attributee<commit_after>/**
 *
 * GeometryCanvas
 *
 */

import React from 'react';
import styled from 'styled-components';

import Button from 'material-ui/Button';
import axios from 'axios';

import PropTypes from 'prop-types';
import { download } from 'utils';

import { MdFileDownload } from 'react-icons/lib/md';

const MButton = styled(Button)`
  margin: 12px,
`;

class GeometryCanvas extends React.Component { // eslint-disable-line react/prefer-stateless-function
  componentDidMount() {
    let cifdata = this.props.cifdata;
    if (this.props.cifurl !== '') {
      axios.get(this.props.cifurl).then((res) => {
        cifdata = res.data.cifdata;
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.innerHTML = `
function _load_lib(url, callback){
  id =  'load_' + url;
  var s = document.createElement('script');
  s.src = url;
  s.id = id;
  s.async = true;
  s.onreadystatechange = s.onload = callback;
  s.onerror = function(){console.warn("failed to load library " + url);};
  document.getElementsByTagName("head")[0].appendChild(s);

}
// Load Libraries
_load_lib("https://code.jquery.com/jquery-3.2.1.min.js", function(){
  _load_lib("https://hub.chemdoodle.com/cwc/8.0.0/ChemDoodleWeb.js", function(){

  var rotationMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

  //Code
  let tfcanvas = new ChemDoodle.TransformCanvas3D('${this.props.id}_view');
  let cif = ChemDoodle.readCIF(\`${cifdata}\`, 2, 2, 1);

  tfcanvas.specs.set3DRepresentation('Ball and Stick');
  tfcanvas.specs.backgroundColor = '${this.props.color}';
  tfcanvas.specs.projectionPerspective_3D = true;
  tfcanvas.specs.atoms_displayLabels_3D = true;
  tfcanvas.specs.crystals_unitCellLineWidth = 5;
  tfcanvas.specs.shapes_color = 'black';
  tfcanvas.specs.shapes_lineWidth = 1;
  tfcanvas.specs.fog_mode_3D = 0;
  tfcanvas.specs.shadow_3D = false;
  tfcanvas.specs.atoms_useJMOLColors = true;
  tfcanvas.specs.compass_display = true;
  tfcanvas.loadContent([cif.molecule], [cif.unitCell]);
  });
});`;
        document.getElementById(`${this.props.id}_view`).appendChild(script);
      });
    } else {
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.innerHTML = `
function _load_lib(url, callback){
  id =  'load_' + url;
  var s = document.createElement('script');
  s.src = url;
  s.id = id;
  s.async = true;
  s.onreadystatechange = s.onload = callback;
  s.onerror = function(){console.warn("failed to load library " + url);};
  document.getElementsByTagName("head")[0].appendChild(s);

}
// Load Libraries
_load_lib("https://code.jquery.com/jquery-3.2.1.min.js", function(){
  _load_lib("https://hub.chemdoodle.com/cwc/8.0.0/ChemDoodleWeb.js", function(){

  var rotationMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

  //Code
  let tfcanvas = new ChemDoodle.TransformCanvas3D('${this.props.id}_view');
  let cif = ChemDoodle.readCIF(\`${cifdata}\`, 1, 1, 1);

  tfcanvas.specs.set3DRepresentation('Ball and Stick');
  tfcanvas.specs.backgroundColor = '${this.props.color}';
  tfcanvas.specs.projectionPerspective_3D = true;
  tfcanvas.specs.atoms_displayLabels_3D = true;
  tfcanvas.specs.crystals_unitCellLineWidth = 5;
  tfcanvas.specs.shapes_color = 'black';
  tfcanvas.specs.shapes_lineWidth = 1;
  tfcanvas.loadContent([cif.molecule], [cif.unitCell]);
  });
});
    `;
      document.getElementById(`${this.props.id}_view`).appendChild(script);
    }
  }

  render() {
    return (

        <p id={`${this.props.id}_script`} />
        <canvas
          id={`${this.props.id}_view`}
          height={this.props.height}
          width={this.props.width}
          style={{
            borderWidth: 1,
            borderColor: '#000000',
            borderStyle: 'solid',
          }}
        />

        <MButton
          raised
          onClick={() => { download(`structure_${this.props.id}.cif`, this.props.cifdata); }}
          style={{
            margin: 12,
          }}
        >
          <MdFileDownload /> Download CIF
        </MButton>

    );
  }
}

GeometryCanvas.defaultProps = {
  height: 550,
  width: 550,
  color: '#fff',
  cifdata: '',
  cifurl: '',
};

GeometryCanvas.propTypes = {
  id: PropTypes.string.isRequired,
  cifdata: PropTypes.string,
  cifurl: PropTypes.string,
  height: PropTypes.number,
  width: PropTypes.number,
  color: PropTypes.string,
};

export default GeometryCanvas;
<|endoftext|>


<commit_before>
var sys = require("sys");
var p = require("path");
var fs = require("fs");
var spawn = require("child_process").spawn;
var exec = require("child_process").exec;
var fileExtensionPattern;
var program, port;
// A program name which is "impossible" for anyone to choose, which represents no program.
var NO_PROGRAM = "__none__.coffee";

exports.run = run;

function run (args) {
  var arg, next, watch, extensions, executor;
  while (arg = args.shift()) {
    if (arg === "--help" || arg === "-h" || arg === "-?") {
      return help();
    } else if (arg === "--watch" || arg === "-w") {
      watch = args.shift();
    } else if (arg === "--port" || arg === "-p") {
      port = args.shift();
    } else if (arg === "--extensions" || arg === "-e") {
      extensions = args.shift();
    } else if (arg === "--exec" || arg === "-x") {
      executor = args.shift();
    } else if (arg.indexOf("-") && !args.length) {
      // Assume last arg is the program
      program = arg;
    }
  }
  if (!program) {
    //return help();
    var pwdFiles = fs.readdirSync('.');
    console.log(pwdFiles);
    var autoRunFiles = ["app.js", "app.coffee", "manage.py"]
    for (var i = 0; i < autoRunFiles.length; i++) {
      console.log( autoRunFiles[i], pwdFiles.indexOf(autoRunFiles[i]) )
      if (pwdFiles.indexOf(autoRunFiles[i]) > -1) program=autoRunFiles[i];
    }
    if (!program) {
      program = NO_PROGRAM;
    }

  }
  if (!watch) {
    watch = ".";
  }

  var programExt = program.match(/.*\.(.*)/);
  programExt = programExt && programExt[1];

  if (!extensions) {
    // If no extensions passed try to guess from the program
    extensions = "node|js|styl|eco|coffee|jade";
    if (programExt && extensions.indexOf(programExt) == -1)
      extensions += "|" + programExt;
  }
  fileExtensionPattern = new RegExp(".*\.(" + extensions + ")$");

  if (!executor) {
    if (programExt === "coffee") {
      executor = "coffee";
    } else if (programExt === "py") {
      executor = "python";
    } else if (programExt === "js") {
      executor = "node";
    } else {
      throw "Extension `" + programExt + "` not supported.";
    }
  }

  sys.puts("")
  sys.debug("Running node-supervisor with");
  sys.debug("  program '" + program + "'");
  sys.debug("  --watch '" + watch + "'");
  sys.debug("  --extensions '" + extensions + "'");
  sys.debug("  --exec '" + executor + "'");
  sys.puts("")

  // if we have a program, then run it, and restart when it crashes.
  // if we have a watch folder, then watch the folder for changes and restart the prog
<<<<<<< HEAD

=======
>>>>>>> 8230c50e643ba53a9f51092447661de547bb6114
  if (program !== NO_PROGRAM) startProgram(program, executor);
  var watchItems = watch.split(',');
  watchItems.forEach(function (watchItem) {
    if (!watchItem.match(/^\/.*/)) { // watch is not an absolute path
      // convert watch item to absolute path
      watchItem = process.cwd() + '/' + watchItem;
    }
    sys.debug("Watching directory '" + watchItem + "' for changes.");
    findAllWatchFiles(watchItem, watchGivenFile);
  });
};

function print (m, n) { sys.print(m+(!n?"\n":"")); return print }

function help () {
  print
    ("")
    ("Node Supervisor is used to restart programs when they crash.")
    ("It can also be used to restart programs when a *.js file changes.")
    ("")
    ("Usage:")
    ("  supervisor [options] <program>")
    ("")
    ("Required:")
    ("  <program>")
    ("    The program to run.")
    ("")
    ("Options:")
    ("  -w|--watch <watchItems>")
    ("    A comma-delimited list of folders or js files to watch for changes.")
    ("    When a change to a js file occurs, reload the program")
    ("    Default is '.'")
    ("")
    ("  -e|--extensions <extensions>")
    ("    Specific file extensions to watch in addition to defaults.")
    ("    Used when --watch option includes folders")
    ("    Default is 'node|js'")
    ("")
    ("  -x|--exec <executable>")
    ("    The executable that runs the specified program.")
    ("    Default is 'node'")
    ("")
    ("  -h|--help|-?")
    ("    Display these usage instructions.")
    ("")
    ("Examples:")
    ("  supervisor myapp.js")
    ("  supervisor myapp.coffee")
    ("  supervisor -w scripts -e myext -x myrunner myapp")
    ("  supervisor -w lib -w server.js -w config.js server.js")
    ("")
}

function startProgram (prog, exec) {
  var cl_args;
  if (prog == 'manage.py') {
    program = NO_PROGRAM
    // special case for Django program.
    cl_args = [prog, 'runserver', '0.0.0.0:' + (port || 8000)];
  } else {
    cl_args = [prog];
  }
  sys.debug("Starting child process with '" + exec + " " + cl_args.join(' ') + "'");
  var child = exports.child = spawn(exec, cl_args);
  child.stdout.addListener("data", function (chunk) { chunk && sys.print(chunk) });
  child.stderr.addListener("data", function (chunk) { chunk && sys.debug(chunk) });
  child.addListener("exit", function () { startProgram(prog, exec) });
}

var timer = null, counter = -1, mtime = null;

function getExtension(filename) {
  var programExt = filename.match(/.*\.([^\.]*)$/);
  return programExt && programExt[1];
}

function stopCrashing () {
  if (counter > 3) throw new Error("Crashing too much, shutting down");
  else counter = -1;
}

function watchGivenFile (watch) {
  fs.watchFile(watch, function crash (oldStat, newStat) {
    // we only care about modification time, not access time.
    if (
      newStat.mtime.getTime() === oldStat.mtime.getTime()
    ) return;

    if (counter === -1) {
      timer = setTimeout(stopCrashing, 400);
    }
    counter ++;

    var child = exports.child;
    sys.debug("detected change at "+watch);
    var extension = getExtension(watch);
    if ("coffee" === extension) {
      sys.debug("compiling with coffeescript.");
      exec("coffee -c "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "styl") {
      sys.debug('compiling with stylus.');
      exec("stylus "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "eco") {
      sys.debug('compiling with eco.');
      exec("eco -o "+p.dirname(watch)+" "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "jade" && watch.indexOf("client") > -1) {
      sys.debug('compiling with clientjade wrapper.');
      exec("clientjade.py " + p.dirname(watch),function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });

    } else {
      if (program !== NO_PROGRAM) process.kill(child.pid);
    }
  });
}

var findAllWatchFiles = function(path, callback) {
  fs.stat(path, function(err, stats){
    if (err) {
      sys.error('Error retrieving stats for file: ' + path);
    } else {
      if (stats.isDirectory()) {
        fs.readdir(path, function(err, fileNames) {
          if(err) {
            sys.puts('Error reading path: ' + path);
          }
          else {
            fileNames.forEach(function (fileName) {
              findAllWatchFiles(path + '/' + fileName, callback);
            });
          }
        });
      } else {

        if (path.match(fileExtensionPattern)) {
          callback(p.normalize(path));
        }
      }
    }
  });
}
<commit_msg>(sharing)<commit_after>
var sys = require("sys");
var p = require("path");
var fs = require("fs");
var spawn = require("child_process").spawn;
var exec = require("child_process").exec;
var fileExtensionPattern;
var program, port;
// A program name which is "impossible" for anyone to choose, which represents no program.
var NO_PROGRAM = "__none__.coffee";

exports.run = run;

function run (args) {
  var arg, next, watch, extensions, executor;
  while (arg = args.shift()) {
    if (arg === "--help" || arg === "-h" || arg === "-?") {
      return help();
    } else if (arg === "--watch" || arg === "-w") {
      watch = args.shift();
    } else if (arg === "--port" || arg === "-p") {
      port = args.shift();
    } else if (arg === "--extensions" || arg === "-e") {
      extensions = args.shift();
    } else if (arg === "--exec" || arg === "-x") {
      executor = args.shift();
    } else if (arg.indexOf("-") && !args.length) {
      // Assume last arg is the program
      program = arg;
    }
  }
  if (!program) {
    //return help();
    var pwdFiles = fs.readdirSync('.');
    console.log(pwdFiles);
    var autoRunFiles = ["app.js", "app.coffee", "manage.py"]
    for (var i = 0; i < autoRunFiles.length; i++) {
      console.log( autoRunFiles[i], pwdFiles.indexOf(autoRunFiles[i]) )
      if (pwdFiles.indexOf(autoRunFiles[i]) > -1) program=autoRunFiles[i];
    }
    if (!program) {
      program = NO_PROGRAM;
    }

  }
  if (!watch) {
    watch = ".";
  }

  var programExt = program.match(/.*\.(.*)/);
  programExt = programExt && programExt[1];

  if (!extensions) {
    // If no extensions passed try to guess from the program
    extensions = "node|js|styl|eco|coffee|jade";
    if (programExt && extensions.indexOf(programExt) == -1)
      extensions += "|" + programExt;
  }
  fileExtensionPattern = new RegExp(".*\.(" + extensions + ")$");

  if (!executor) {
    if (programExt === "coffee") {
      executor = "coffee";
    } else if (programExt === "py") {
      executor = "python";
    } else if (programExt === "js") {
      executor = "node";
    } else {
      throw "Extension `" + programExt + "` not supported.";
    }
  }

  sys.puts("")
  sys.debug("Running node-supervisor with");
  sys.debug("  program '" + program + "'");
  sys.debug("  --watch '" + watch + "'");
  sys.debug("  --extensions '" + extensions + "'");
  sys.debug("  --exec '" + executor + "'");
  sys.puts("")

  // if we have a program, then run it, and restart when it crashes.
  // if we have a watch folder, then watch the folder for changes and restart the prog

  if (program !== NO_PROGRAM) startProgram(program, executor);
  var watchItems = watch.split(',');
  watchItems.forEach(function (watchItem) {
    if (!watchItem.match(/^\/.*/)) { // watch is not an absolute path
      // convert watch item to absolute path
      watchItem = process.cwd() + '/' + watchItem;
    }
    sys.debug("Watching directory '" + watchItem + "' for changes.");
    findAllWatchFiles(watchItem, watchGivenFile);
  });
};

function print (m, n) { sys.print(m+(!n?"\n":"")); return print }

function help () {
  print
    ("")
    ("Node Supervisor is used to restart programs when they crash.")
    ("It can also be used to restart programs when a *.js file changes.")
    ("")
    ("Usage:")
    ("  supervisor [options] <program>")
    ("")
    ("Required:")
    ("  <program>")
    ("    The program to run.")
    ("")
    ("Options:")
    ("  -w|--watch <watchItems>")
    ("    A comma-delimited list of folders or js files to watch for changes.")
    ("    When a change to a js file occurs, reload the program")
    ("    Default is '.'")
    ("")
    ("  -e|--extensions <extensions>")
    ("    Specific file extensions to watch in addition to defaults.")
    ("    Used when --watch option includes folders")
    ("    Default is 'node|js'")
    ("")
    ("  -x|--exec <executable>")
    ("    The executable that runs the specified program.")
    ("    Default is 'node'")
    ("")
    ("  -h|--help|-?")
    ("    Display these usage instructions.")
    ("")
    ("Examples:")
    ("  supervisor myapp.js")
    ("  supervisor myapp.coffee")
    ("  supervisor -w scripts -e myext -x myrunner myapp")
    ("  supervisor -w lib -w server.js -w config.js server.js")
    ("")
}

function startProgram (prog, exec) {
  var cl_args;
  if (prog == 'manage.py') {
    program = NO_PROGRAM
    // special case for Django program.
    cl_args = [prog, 'runserver', '0.0.0.0:' + (port || 8000)];
  } else {
    cl_args = [prog];
  }
  sys.debug("Starting child process with '" + exec + " " + cl_args.join(' ') + "'");
  var child = exports.child = spawn(exec, cl_args);
  child.stdout.addListener("data", function (chunk) { chunk && sys.print(chunk) });
  child.stderr.addListener("data", function (chunk) { chunk && sys.debug(chunk) });
  child.addListener("exit", function () { startProgram(prog, exec) });
}

var timer = null, counter = -1, mtime = null;

function getExtension(filename) {
  var programExt = filename.match(/.*\.([^\.]*)$/);
  return programExt && programExt[1];
}

function stopCrashing () {
  if (counter > 3) throw new Error("Crashing too much, shutting down");
  else counter = -1;
}

function watchGivenFile (watch) {
  fs.watchFile(watch, function crash (oldStat, newStat) {
    // we only care about modification time, not access time.
    if (
      newStat.mtime.getTime() === oldStat.mtime.getTime()
    ) return;

    if (counter === -1) {
      timer = setTimeout(stopCrashing, 400);
    }
    counter ++;

    var child = exports.child;
    sys.debug("detected change at "+watch);
    var extension = getExtension(watch);
    if ("coffee" === extension) {
      sys.debug("compiling with coffeescript.");
      exec("coffee -c "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "styl") {
      sys.debug('compiling with stylus.');
      exec("stylus "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "eco") {
      sys.debug('compiling with eco.');
      exec("eco -o "+p.dirname(watch)+" "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "jade" && watch.indexOf("client") > -1) {
      sys.debug('compiling with clientjade wrapper.');
      exec("clientjade.py " + p.dirname(watch),function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });

    } else {
      if (program !== NO_PROGRAM) process.kill(child.pid);
    }
  });
}

var findAllWatchFiles = function(path, callback) {
  fs.stat(path, function(err, stats){
    if (err) {
      sys.error('Error retrieving stats for file: ' + path);
    } else {
      if (stats.isDirectory()) {
        fs.readdir(path, function(err, fileNames) {
          if(err) {
            sys.puts('Error reading path: ' + path);
          }
          else {
            fileNames.forEach(function (fileName) {
              findAllWatchFiles(path + '/' + fileName, callback);
            });
          }
        });
      } else {

        if (path.match(fileExtensionPattern)) {
          callback(p.normalize(path));
        }
      }
    }
  });
}
<|endoftext|>


<commit_before>
// NODE.JS 4JHAN SERVER
// LICENCE: MIT

// Main server file

// Imports
var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    bodyParser = require('body-parser'),
    multer = require('multer'),
    auth = require('basic-auth');

// Get config
var config = require('./config.json') || {};

// Markdown conditional require
if (config.markdown)
    marked = require('marked-no-images');

// Info & config setup for 'GET:/'
var info = {
    name : config.name || "Nameless 4jhan server",
    short : config.short || "z",
    admin : config.admin,
    discription : config.discr || "A 4jhan server",
    nsfw : config.nsfw || false,
    timeout : config.timeout || (config.timeout = 60),
    language : config.lang || "English",
    version : require('./package.json').version,
    database : config.db || (config.db = "sqlite"),
    page : config.page,
    imageForce : config.image || (config.image = true),
    uptime : new Date().toUTCString(),
    extra : config.extra,
    files : config.files || (config.files = [ 'png', 'jpg', 'gif' ])
};

// DB setup
var db = require("./lib/db")(config.db);

// Express setup
var app = express();
if (config.log) app.use((require('morgan'))(config.log));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(multer({ dest: config.upload || './img/'}));
app.use('/', express.static(__dirname + '/public'));

// Markdown setup
if (config.sanitize && config.markdown)
  marked.setOptions({ sanitize: true });

// Enable CORS
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    req.auth = auth(req);
    next();
});

// Get server info
app.get('/', function(req,res) {
    res.send(info);
});

// Get list of posts (limited to config.page if set)
app.get('/list', function(req,res) {
    db.getList(req.query.page, function (err, resp) {
        if (err) res.send(500);
		for (var i in resp.thread)
			resp.thread[i].upload = new Date(resp.upload[i].upload).toUTCString();
        res.send(resp);
    });
});

// Get comments on post i.e. Thread
app.get('/thread/:id', function(req,res) {
    db.getThread(req.params.id, function (err, resp) {
        if (err) return res.send(500);
		if (!resp) return res.send(404);

		resp.upload = new Date(resp.upload).toUTCString();
		for (var i in resp.thread)
			resp.thread[i].upload = new Date(resp.upload[i].upload).toUTCString();

        res.send(resp);
    });
});

app.get('/img/:img', function(req,res) {
    res.sendfile((config.upload || './img/')+req.params.img);
});

// Upload post (and image if config.image)
app.post('/upload', function(req,res) {
    if (!req.body.text)
        return res.send(400);
    if (req.files.file)
        return res.send(415);
    var text = config.markdown ? marked(req.body.text) : req.body.text;

    db.newPost({
        title : req.body.title,
        name : req.body.name,
        text : text,
        img : req.files.file ? req.files.file.name : undefined,
		pass : req.body.pass,
        upload : new Date()
    }, function (err) {
        if (err) return res.send(500);
        if (req.body.next) return res.redirect(req.body.next);
        res.send();
    });
});

// Comment on Post, image optional
app.post('/comment', function(req,res) {
    if (!req.body.text)
        return res.send(400);
    if (req.files.file && config.files.indexOf(req.files.file.originalname.split('.').pop()) == -1)
        return res.send(415);
    var text = config.markdown ? marked(req.body.text) : req.body.text;

	db.newComment({
        name : req.body.name,
        text : text,
        op :   req.body.op,
        img :  req.files.file ? req.files.file.name : undefined,
		pass : req.body.pass,
        upload : new Date(),
    }, function (err) {
        if (err) return res.send(500);
        if (req.body.next) return res.redirect(req.body.next);
        res.send();
    });
});

// Load robots.txt file if it exists
if (fs.existsSync('./robots.txt')) app.get('/robots.txt', function(req,res) {
	 res.sendfile('./robots.txt');
});

// Delete too old posts. (set by config.timeout)
setInterval(db.clear, 6000*config.timeout);

module.exports = app;
<commit_msg>Oops, this shouldn't be removed<commit_after>
// NODE.JS 4JHAN SERVER
// LICENCE: MIT

// Main server file

// Imports
var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    bodyParser = require('body-parser'),
    multer = require('multer'),
    auth = require('basic-auth');

// Get config
var config = require('./config.json') || {};

// Markdown conditional require
if (config.markdown)
    marked = require('marked-no-images');

// Info & config setup for 'GET:/'
var info = {
    name : config.name || "Nameless 4jhan server",
    short : config.short || "z",
    admin : config.admin,
    discription : config.discr || "A 4jhan server",
    nsfw : config.nsfw || false,
    timeout : config.timeout || (config.timeout = 60),
    language : config.lang || "English",
    version : require('./package.json').version,
    database : config.db || (config.db = "sqlite"),
    page : config.page,
    imageForce : config.image || (config.image = true),
    uptime : new Date().toUTCString(),
    extra : config.extra,
    files : config.files || (config.files = [ 'png', 'jpg', 'gif' ])
};

// DB setup
var db = require("./lib/db")(config.db);

// Express setup
var app = express();
if (config.log) app.use((require('morgan'))(config.log));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(multer({ dest: config.upload || './img/'}));
app.use('/', express.static(__dirname + '/public'));

// Markdown setup
if (config.sanitize && config.markdown)
  marked.setOptions({ sanitize: true });

// Enable CORS
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    req.auth = auth(req);
    next();
});

// Get server info
app.get('/', function(req,res) {
    res.send(info);
});

// Get list of posts (limited to config.page if set)
app.get('/list', function(req,res) {
    db.getList(req.query.page, function (err, resp) {
        if (err) res.send(500);
		for (var i in resp.thread)
			resp.thread[i].upload = new Date(resp.upload[i].upload).toUTCString();
        res.send(resp);
    });
});

// Get comments on post i.e. Thread
app.get('/thread/:id', function(req,res) {
    db.getThread(req.params.id, function (err, resp) {
        if (err) return res.send(500);
		if (!resp) return res.send(404);

		resp.upload = new Date(resp.upload).toUTCString();
		for (var i in resp.thread)
			resp.thread[i].upload = new Date(resp.upload[i].upload).toUTCString();

        res.send(resp);
    });
});

app.get('/img/:img', function(req,res) {
    res.sendfile((config.upload || './img/')+req.params.img);
});

// Upload post (and image if config.image)
app.post('/upload', function(req,res) {
    if (!req.body.text && (!config.image || req.files.file)))
        return res.send(400);
    if (req.files.file && config.files.indexOf(req.files.file.originalname.split('.').pop()) == -1)
        return res.send(415);
    var text = config.markdown ? marked(req.body.text) : req.body.text;

    db.newPost({
        title : req.body.title,
        name : req.body.name,
        text : text,
        img : req.files.file ? req.files.file.name : undefined,
		pass : req.body.pass,
        upload : new Date()
    }, function (err) {
        if (err) return res.send(500);
        if (req.body.next) return res.redirect(req.body.next);
        res.send();
    });
});

// Comment on Post, image optional
app.post('/comment', function(req,res) {
    if (!req.body.text)
        return res.send(400);
    if (req.files.file && config.files.indexOf(req.files.file.originalname.split('.').pop()) == -1)
        return res.send(415);
    var text = config.markdown ? marked(req.body.text) : req.body.text;

	db.newComment({
        name : req.body.name,
        text : text,
        op :   req.body.op,
        img :  req.files.file ? req.files.file.name : undefined,
		pass : req.body.pass,
        upload : new Date(),
    }, function (err) {
        if (err) return res.send(500);
        if (req.body.next) return res.redirect(req.body.next);
        res.send();
    });
});

// Load robots.txt file if it exists
if (fs.existsSync('./robots.txt')) app.get('/robots.txt', function(req,res) {
	 res.sendfile('./robots.txt');
});

// Delete too old posts. (set by config.timeout)
setInterval(db.clear, 6000*config.timeout);

module.exports = app;
<|endoftext|>


<commit_before>$(function(){
	//$('#category').chosen();

	// Toggles the datepicker
	$('.datepicker').datepicker({ format: "dd/mm/yyyy"});

	// Displays punctual-date datepicker or goes back to from-to-date
	$('#isPunctual').on("change", function() {
		if($('#isPunctual').is(':checked')) {
			$('#ends_at').prop('disabled', true);
		} else {
			$('#ends_at').prop('disabled', false);
		}
	});

	$('.swipe a').on('swipeleft', function(){
		$('.swipe a').css({marginRight: '0'});
		$(this).animate({marginRight: '60px'}, 150);
	});

	$(window).on('scrollstart', function(){
		$('.swipe a').css({marginRight: '0'});
	});
});<commit_msg>Add fancy stuff to datepicker<commit_after>$(function(){
	//$('#category').chosen();

	// Toggles the datepicker
	$('.datepicker').datepicker({
		format: "dd/mm/yyyy",
		autoclose: true,
    	todayHighlight: true
	});

	// Displays punctual-date datepicker or goes back to from-to-date
	$('#isPunctual').on("change", function() {
		if($('#isPunctual').is(':checked')) {
			$('#ends_at').prop('disabled', true);
		} else {
			$('#ends_at').prop('disabled', false);
		}
	});

	$('.swipe a').on('swipeleft', function(){
		$('.swipe a').css({marginRight: '0'});
		$(this).animate({marginRight: '60px'}, 150);
	});

	$(window).on('scrollstart', function(){
		$('.swipe a').css({marginRight: '0'});
	});
});<|endoftext|>


<commit_before>module.exports = {

	/* APP CONFIG */
	APP_VERSION: 				'5.0',
	APP_CODEPUSH_VERSION: 		'1',
	APP_NAME: 					'campus-mobile',
	APP_CAMPUS_NAME: 			'APP_CAMPUS_NAME_PH',
	GOOGLE_ANALYTICS_ID: 		'GOOGLE_ANALYTICS_ID_PH',
	DEBUG_ENABLED: 				false, // Disables all logger functions (i.e. logger.log, logger.error).
									   // Use console.log/error as necessary but do not commit code using console.log/error

	/* APIs / FEEDS */
	WEATHER_API_URL: 			'https://w3wyps9yje.execute-api.us-west-2.amazonaws.com/prod/forecast',
	SURF_API_URL: 				'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/surffeed.json',
	SHUTTLE_STOPS_API_URL: 		'https://ies4wyrlx9.execute-api.us-west-2.amazonaws.com/prod/stops/',
	DINING_API_URL: 			'https://pg83tslbyi.execute-api.us-west-2.amazonaws.com/prod/v2/dining/locations',
	EVENTS_API_URL: 			'https://evv6vpvob6.execute-api.us-west-2.amazonaws.com/prod/',
	QUICKLINKS_API_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/quick_links/ucsd-quicklinks-v2.json',
	NEWS_API_URL: 				'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/allstories.json',
	MAP_SEARCH_API_URL: 		'https://xgu9qa7gx4.execute-api.us-west-2.amazonaws.com/prod/map/search?region=0&query=',

	/* RESOURCES */
	FEEDBACK_URL: 				'https://eforms.ucsd.edu/view.php?id=175631',
	NODE_MARKERS_BASE_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/nearby_markers/',
	WEATHER_ICON_BASE_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/images/v1/weather-icons/',
	WELCOME_WEEK_API_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/welcome_week_events.json',

	/* API TTL (seconds) */
	WEATHER_API_TTL: 			3600,
	SURF_API_TTL: 				3600,
	SHUTTLE_STOPS_API_TTL: 		3600,
	EVENTS_API_TTL: 			3600,
	DINING_API_TTL: 			60,
	QUICKLINKS_API_TTL: 		86400,

	USER_LOGIN: {
		ENABLED: false,
		METHOD: 'openid',
		OPTIONS: {
			CLIENT_ID: 'campusimplicit',
			AUTH_URL: 'https://auth-dev.ucdavis.edu/identity/connect/authorize',
			USER_INFO_URL: 'https://auth-dev.ucdavis.edu/identity/connect/userinfo',
			REDIRECT_URL: 'campusmobile://cb',
			STATE: 'M9NGbE6bnUV18FflfVeZ2U0j94'
		}
	}
};
<commit_msg>add version tracking to api endpoints<commit_after>const APP_VERSION = 			'5.0',
	  APP_NAME = 				'campus-mobile',
	  API_TRACKING = 			'version=' + APP_NAME + '_' + APP_VERSION;

module.exports = {

	/* APP CONFIG */
	APP_NAME: 					APP_NAME,
	APP_VERSION: 				APP_VERSION,
	APP_CODEPUSH_VERSION: 		'1',
	APP_CAMPUS_NAME: 			'APP_CAMPUS_NAME_PH',
	GOOGLE_ANALYTICS_ID: 		'GOOGLE_ANALYTICS_ID_PH',
	DEBUG_ENABLED: 				false, // Disables all logger functions (i.e. logger.log, logger.error).
									   // Use console.log/error as necessary but do not commit code using console.log/error

	/* APIs / FEEDS */
	WEATHER_API_URL: 			'https://w3wyps9yje.execute-api.us-west-2.amazonaws.com/prod/forecast?' + API_TRACKING,
	SURF_API_URL: 				'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/surffeed.json?' + API_TRACKING,
	SHUTTLE_STOPS_API_URL: 		'https://ies4wyrlx9.execute-api.us-west-2.amazonaws.com/prod/stops/?' + API_TRACKING,
	DINING_API_URL: 			'https://pg83tslbyi.execute-api.us-west-2.amazonaws.com/prod/v2/dining/locations?' + API_TRACKING,
	EVENTS_API_URL: 			'https://evv6vpvob6.execute-api.us-west-2.amazonaws.com/prod/?' + API_TRACKING,
	QUICKLINKS_API_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/quick_links/ucsd-quicklinks-v2.json?' + API_TRACKING,
	NEWS_API_URL: 				'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/allstories.json?' + API_TRACKING,
	MAP_SEARCH_API_URL: 		'https://xgu9qa7gx4.execute-api.us-west-2.amazonaws.com/prod/map/search?' + API_TRACKING + '&region=0&query=',
	WELCOME_WEEK_API_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/welcome_week_events.json?' + API_TRACKING,

	/* RESOURCES */
	FEEDBACK_URL: 				'https://eforms.ucsd.edu/view.php?id=175631',
	NODE_MARKERS_BASE_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/now_ucsandiego/v1/nearby_markers/',
	WEATHER_ICON_BASE_URL: 		'https://s3-us-west-2.amazonaws.com/ucsd-its-wts/images/v1/weather-icons/',

	/* API TTL (seconds) */
	WEATHER_API_TTL: 			3600,
	SURF_API_TTL: 				3600,
	SHUTTLE_STOPS_API_TTL: 		3600,
	EVENTS_API_TTL: 			3600,
	DINING_API_TTL: 			60,
	QUICKLINKS_API_TTL: 		86400,

	USER_LOGIN: {
		ENABLED: false,
		METHOD: 'openid',
		OPTIONS: {
			CLIENT_ID: 'campusimplicit',
			AUTH_URL: 'https://auth-dev.ucdavis.edu/identity/connect/authorize',
			USER_INFO_URL: 'https://auth-dev.ucdavis.edu/identity/connect/userinfo',
			REDIRECT_URL: 'campusmobile://cb',
			STATE: 'M9NGbE6bnUV18FflfVeZ2U0j94'
		}
	}
};
<|endoftext|>


<commit_before>import '../../css/browser/stack'

import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { FormattedMessage as T, FormattedRelative as D, intlShape } from 'react-intl'

import { emptyStack, fetchStack, viewWebentity } from '../../actions/stacks'
import { setTabUrl } from '../../actions/tabs'

class BrowserStack extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      selectedStackName: this.props.selectedStack && this.props.selectedStack.name,
      selectedWebentityId: null
    }
  }

  // also called by refresh button
  fill () {
    const stack = this.props.stacks.find(s => s.name === this.state.selectedStackName)
    this.props.fetchStack(this.props.server.url, this.props.corpus, stack)
  }

  selectWebentity (weId) {
    const webentity = this.props.webentities.find(x => x.id === weId)
    this.setState({ selectedWebentityId: webentity.id })
    this.props.viewWebentity(webentity)
    this.props.setTabUrl(webentity.homepage, this.props.activeTabId)
  }

  // used by Prev (-1) / Next (+1) buttons
  rotateWebentity (offset) {
    const { webentities } = this.props
    const idx = webentities.findIndex(x => x.id === this.state.selectedWebentityId)
    let webentity
    if (idx === 0 && offset === -1) {
      webentity = webentities[webentities.length - 1]
    } else if (idx === webentities.length - 1 && offset === 1) {
      webentity = webentities[0]
    } else {
      webentity = webentities[idx + offset]
    }
    this.selectWebentity(webentity.id)
  }

  // top row
  renderFiller () {
    const { lastRefresh, selectedStack, stacks, webentities } = this.props
    const viewCount = webentities.filter(x => x.viewed).length

    if (!selectedStack) {
      return (

            <select className="form-control"
              defaultValue={ this.state.selectedStackName }
              onChange={ (evt) => { if (evt.target.value) this.setState({ selectedStackName: evt.target.value }) } }>
              <option key="prompt" value="">{ this.context.intl.formatMessage({ id: 'select-stack' }) }</option>
              { stacks.map(s => (
                <option key={ s.name } value={ s.name }>{ s.description }</option>
              )) }
            </select>
            <button className="btn btn-default"
              onClick={ () => this.fill() }>

              <T id="fill" />
            </button>

      )
    }
    return (

            { selectedStack.name }

            { selectedStack.description }

          <T id="viewed" /> { viewCount } / { webentities.length }

          <T id="refreshed-ago" values={ { relative: <D value={ lastRefresh } /> } } />
          <button className="btn btn-default"
              onClick={ () => this.fill() }>

            <T id="refresh" />
          </button>

          <button className="btn btn-default"
              onClick={ () => this.props.emptyStack() }>

            <T id="empty" />
          </button>

    )
  }

  // bottom row
  renderWesSelector () {
    const { webentities } = this.props
    const viewed = this.context.intl.formatMessage({ id: 'viewed' })

    return (

          <button className="btn btn-default browser-stack-wes-prev"
            onClick={ () => this.rotateWebentity(-1) }>

            <T id="previous" />
          </button>

          <select className="form-control"
            value={ this.state.selectedWebentityId }
            onChange={ (evt) => this.selectWebentity(evt.target.value) }>
            { webentities.map((w, i) => (
              <option key={ w.id } value={ w.id }>#{ i + 1 } - { w.viewed ? `[${viewed}] - ` : '' } { w.name } ({ w.homepage })</option>
            )) }
          </select>

          <button className="btn btn-default browser-stack-wes-next"
            onClick={ () => this.rotateWebentity(1) }>
            <T id="next" />

          </button>

    )
  }

  render () {
    return (

        { this.renderFiller() }
        { this.props.selectedStack ? this.renderWesSelector() : null }

    )
  }
}

BrowserStack.contextTypes = {
  intl: intlShape
}

BrowserStack.propTypes = {
  activeTabId: PropTypes.string,
  corpus: PropTypes.object.isRequired,
  lastRefresh: PropTypes.number,
  server: PropTypes.object.isRequired,
  selectedStack: PropTypes.any,
  stacks: PropTypes.array.isRequired,
  webentities: PropTypes.array.isRequired,

  emptyStack: PropTypes.func.isRequired,
  fetchStack: PropTypes.func.isRequired,
  setTabUrl: PropTypes.func.isRequired
}

const mapStateToProps = ({ corpora, servers, stacks, tabs }) => ({
  activeTabId: tabs.activeTab,
  corpus: corpora.selected,
  lastRefresh: stacks.lastRefresh,
  server: servers.selected,
  selectedStack: stacks.selected,
  stacks: stacks.list,
  webentities: stacks.webentities
})

const mapDispatchToProps = {
  emptyStack,
  fetchStack,
  setTabUrl,
  viewWebentity
}

export default connect(mapStateToProps, mapDispatchToProps)(BrowserStack)
<commit_msg>fix(stack): activeTabId prop<commit_after>import '../../css/browser/stack'

import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { FormattedMessage as T, FormattedRelative as D, intlShape } from 'react-intl'

import { emptyStack, fetchStack, viewWebentity } from '../../actions/stacks'
import { setTabUrl } from '../../actions/tabs'

class BrowserStack extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      selectedStackName: this.props.selectedStack && this.props.selectedStack.name,
      selectedWebentityId: null
    }
  }

  // also called by refresh button
  fill () {
    const stack = this.props.stacks.find(s => s.name === this.state.selectedStackName)
    this.props.fetchStack(this.props.server.url, this.props.corpus, stack)
  }

  selectWebentity (weId) {
    const webentity = this.props.webentities.find(x => x.id === weId)
    this.setState({ selectedWebentityId: webentity.id })
    this.props.viewWebentity(webentity)
    this.props.setTabUrl(webentity.homepage, this.props.activeTabId)
  }

  // used by Prev (-1) / Next (+1) buttons
  rotateWebentity (offset) {
    const { webentities } = this.props
    const idx = webentities.findIndex(x => x.id === this.state.selectedWebentityId)
    let webentity
    if (idx === 0 && offset === -1) {
      webentity = webentities[webentities.length - 1]
    } else if (idx === webentities.length - 1 && offset === 1) {
      webentity = webentities[0]
    } else {
      webentity = webentities[idx + offset]
    }
    this.selectWebentity(webentity.id)
  }

  // top row
  renderFiller () {
    const { lastRefresh, selectedStack, stacks, webentities } = this.props
    const viewCount = webentities.filter(x => x.viewed).length

    if (!selectedStack) {
      return (

            <select className="form-control"
              defaultValue={ this.state.selectedStackName }
              onChange={ (evt) => { if (evt.target.value) this.setState({ selectedStackName: evt.target.value }) } }>
              <option key="prompt" value="">{ this.context.intl.formatMessage({ id: 'select-stack' }) }</option>
              { stacks.map(s => (
                <option key={ s.name } value={ s.name }>{ s.description }</option>
              )) }
            </select>
            <button className="btn btn-default"
              onClick={ () => this.fill() }>

              <T id="fill" />
            </button>

      )
    }
    return (

            { selectedStack.name }

            { selectedStack.description }

          <T id="viewed" /> { viewCount } / { webentities.length }

          <T id="refreshed-ago" values={ { relative: <D value={ lastRefresh } /> } } />
          <button className="btn btn-default"
              onClick={ () => this.fill() }>

            <T id="refresh" />
          </button>

          <button className="btn btn-default"
              onClick={ () => this.props.emptyStack() }>

            <T id="empty" />
          </button>

    )
  }

  // bottom row
  renderWesSelector () {
    const { webentities } = this.props
    const viewed = this.context.intl.formatMessage({ id: 'viewed' })

    return (

          <button className="btn btn-default browser-stack-wes-prev"
            onClick={ () => this.rotateWebentity(-1) }>

            <T id="previous" />
          </button>

          <select className="form-control"
            value={ this.state.selectedWebentityId }
            onChange={ (evt) => this.selectWebentity(evt.target.value) }>
            { webentities.map((w, i) => (
              <option key={ w.id } value={ w.id }>#{ i + 1 } - { w.viewed ? `[${viewed}] - ` : '' } { w.name } ({ w.homepage })</option>
            )) }
          </select>

          <button className="btn btn-default browser-stack-wes-next"
            onClick={ () => this.rotateWebentity(1) }>
            <T id="next" />

          </button>

    )
  }

  render () {
    return (

        { this.renderFiller() }
        { this.props.selectedStack ? this.renderWesSelector() : null }

    )
  }
}

BrowserStack.contextTypes = {
  intl: intlShape
}

BrowserStack.propTypes = {
  activeTabId: PropTypes.string,
  corpus: PropTypes.object.isRequired,
  lastRefresh: PropTypes.number,
  server: PropTypes.object.isRequired,
  selectedStack: PropTypes.any,
  stacks: PropTypes.array.isRequired,
  webentities: PropTypes.array.isRequired,

  emptyStack: PropTypes.func.isRequired,
  fetchStack: PropTypes.func.isRequired,
  setTabUrl: PropTypes.func.isRequired
}

const mapStateToProps = ({ corpora, servers, stacks, tabs }) => ({
  activeTabId: tabs.activeTab && tabs.activeTab.id,
  corpus: corpora.selected,
  lastRefresh: stacks.lastRefresh,
  server: servers.selected,
  selectedStack: stacks.selected,
  stacks: stacks.list,
  webentities: stacks.webentities
})

const mapDispatchToProps = {
  emptyStack,
  fetchStack,
  setTabUrl,
  viewWebentity
}

export default connect(mapStateToProps, mapDispatchToProps)(BrowserStack)
<|endoftext|>


<commit_before>/*********************************************************#
# @@ScriptName: app.js
# @@Author: Konstantinos Vaggelakos<kozze89@gmail.com>
# @@Create Date: 2013-07-18 08:44:48
# @@Modify Date: 2013-07-18 13:11:42
# @@Function:
#*********************************************************/

/* jshint laxcomma:true */

var express = require('express')
  , config = require('./config')
  , mongoose = require('mongoose');

var app = module.exports = express.createServer();

// Connect to mongo db
mongoose.connect(config.database.connectionString);

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Include api routes
require('./routes/api')(app);

// Include web site
require('./routes/pages')(app);

app.listen(3000, function(){
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
<commit_msg>Looking for env port, before defaulting<commit_after>/*********************************************************#
# @@ScriptName: app.js
# @@Author: Konstantinos Vaggelakos<kozze89@gmail.com>
# @@Create Date: 2013-07-18 08:44:48
# @@Modify Date: 2013-07-19 16:43:36
# @@Function:
#*********************************************************/

/* jshint laxcomma:true */

var express = require('express')
  , config = require('./config')
  , mongoose = require('mongoose');

var app = module.exports = express.createServer();

// Connect to mongo db
mongoose.connect(config.database.connectionString);

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Include api routes
require('./routes/api')(app);

// Include web site
require('./routes/pages')(app);

// Start server
var port = process.env.PORT || 3000;
app.listen(port, function(){
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
<|endoftext|>


<commit_before>/* eslint-env amd */

define(
    ['./realtime-set-interval', 'underscore', 'backbone'],
    function(realtimeSetInterval, _, Backbone) {
        // User won't notice lower intervals than these
        return function() {
            var user = _.extend({}, Backbone.Events);
            var maxReadInterval = 250;

            var triggerReadIfNeeded = (function() {
                var lastRead;
                return function() {
                    var now = Date.now();
                    if (!lastRead || now > lastRead + maxReadInterval) {
                        user.trigger('read');
                        lastRead = now;
                    }
                };
            })();

            (function userViewTimer() {
                requestAnimationFrame(userViewTimer); // Consumes less CPU than d3.timer()
                user.trigger('view');
                triggerReadIfNeeded();
            })();

            // requestanimationframe() is not always triggered when the tab is not
            // active. Here we ensure it is called at least once every second (as we
            // are not using realtimeSetInterval())
            setInterval(triggerReadIfNeeded, maxReadInterval);

            realtimeSetInterval(function() { user.trigger('hear'); }, 250);

            return user;
        };
    }
);
<commit_msg>user.js from AMD to CommonJS<commit_after>/* eslint-env node */

var realtimeSetInterval = require('./realtime-set-interval');
var _ = require('underscore');
var Backbone = require('backbone');

// User won't notice lower intervals than these
var MAX_READ_INTERVAL = 250; // msecs

module.exports = function () {
    var user = _.extend({}, Backbone.Events);

    var triggerReadIfNeeded = (function() {
        var lastRead;
        return function() {
            var now = Date.now();
            if (!lastRead || now > lastRead + MAX_READ_INTERVAL) {
                user.trigger('read');
                lastRead = now;
            }
        };
    })();

    (function _userViewTimer() {
        requestAnimationFrame(_userViewTimer); // Consumes less CPU than d3.timer()
        user.trigger('view');
        triggerReadIfNeeded();
    })();

    // requestanimationframe() is not always triggered when the tab is not
    // active. Here we ensure it is called at least once every second (as we
    // are not using realtimeSetInterval())
    setInterval(triggerReadIfNeeded, MAX_READ_INTERVAL);

    realtimeSetInterval(function() { user.trigger('hear'); }, 250);

    return user;
};
<|endoftext|>


<commit_before>'use strict';
// Karma configuration
// Generated on Tue Sep 10 2013 18:12:14 GMT+0200 (CEST)

var files = require('./files.conf.js');
var conf = require('./karma.shared.conf.js');
module.exports = function(config) {

    conf.files = files.testFilesBuild;

    conf.browserStack = {
        username: process.env.BROWSER_STACK_USERNAME,
        accessKey: process.env.BROWSER_STACK_ACCESS_KEY,
        startTunnel: true,
        captureTimeout: 120000, // 2 mins
        retryLimit: 8
    };
    conf.logLevel = config.LOG_DEBUG;
    conf.reportSlowerThan = 30000;
    conf.browserDisconnectTimeout = 30000;
    conf.customLaunchers = {

        BS_FIREFOX: {
            base: 'BrowserStack',
                browser: 'firefox',
                browser_version: '24.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_CHROME: {
            base: 'BrowserStack',
                browser: 'chrome',
                browser_version: '29.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_IE8: {
            base: 'BrowserStack',
                browser: 'ie',
                browser_version: '8.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_IE9: {
            base: 'BrowserStack',
                browser: 'ie',
                browser_version: '9.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_IE10: {
            base: 'BrowserStack',
                browser: 'ie',
                browser_version: '10.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_IE11: {
            base: 'BrowserStack',
                browser: 'ie',
                browser_version: '11.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_SAFARI51: {
            base: 'BrowserStack',
                browser: 'safari',
                browser_version: '5.1',
                os: 'OS X',
                os_version: 'Snow Leopard'
        },

        BS_SAFARI6: {
            base: 'BrowserStack',
                browser: 'safari',
                browser_version: '6.0',
                os: 'OS X',
                os_version: 'Mountain Lion'
        },

        BS_OPERA15: {
            base: 'BrowserStack',
                os: 'Windows',
                browser: 'opera',
                os_version: '7',
                browser_version: '15.0'
        },

        BS_ANDROID_23: {
            base: 'BrowserStack',
                os: 'android',
                device: 'Samsung Galaxy S II',
                browser: 'Android Browser',
                os_version: '2.3',
                browser_version: null
        },

        BS_ANDROID_4: {
            base: 'BrowserStack',
                os: 'android',
                device: 'Samsung Galaxy Tab 2 10.1',
                browser: 'Android Browser',
                os_version: '4.0',
                browser_version: null
        },

        BS_ANDROID_41: {
            base: 'BrowserStack',
                os: 'android',
                device: 'Samsung Galaxy Note II',
                browser: 'Android Browser',
                os_version: '4.1',
                browser_version: null
        },

        BS_ANDROID_42: {
            base: 'BrowserStack',
                os: 'android',
                device: 'LG Nexus 4',
                browser: 'Android Browser',
                os_version: '4.2',
                browser_version: null
        },

        BS_IOS_6: {
            base: 'BrowserStack',
                os: 'ios',
                device: 'iPad 3rd (6.0)',
                browser: 'Mobile Safari',
                os_version: '6.0',
                browser_version: null
        }

    };
    conf.autoWatch = false;
    conf.singleRun = true;
    config.set(conf);

};
<commit_msg>chore: switch back to LOG_ERROR<commit_after>'use strict';
// Karma configuration
// Generated on Tue Sep 10 2013 18:12:14 GMT+0200 (CEST)

var files = require('./files.conf.js');
var conf = require('./karma.shared.conf.js');
module.exports = function(config) {

    conf.files = files.testFilesBuild;

    conf.browserStack = {
        username: process.env.BROWSER_STACK_USERNAME,
        accessKey: process.env.BROWSER_STACK_ACCESS_KEY,
        startTunnel: true,
        captureTimeout: 120000, // 2 mins
        retryLimit: 8
    };
    conf.logLevel = config.LOG_ERROR;
    conf.reportSlowerThan = 30000;
    conf.browserDisconnectTimeout = 30000;
    conf.customLaunchers = {

        BS_FIREFOX: {
            base: 'BrowserStack',
                browser: 'firefox',
                browser_version: '24.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_CHROME: {
            base: 'BrowserStack',
                browser: 'chrome',
                browser_version: '29.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_IE8: {
            base: 'BrowserStack',
                browser: 'ie',
                browser_version: '8.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_IE9: {
            base: 'BrowserStack',
                browser: 'ie',
                browser_version: '9.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_IE10: {
            base: 'BrowserStack',
                browser: 'ie',
                browser_version: '10.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_IE11: {
            base: 'BrowserStack',
                browser: 'ie',
                browser_version: '11.0',
                os: 'Windows',
                os_version: '7'
        },

        BS_SAFARI51: {
            base: 'BrowserStack',
                browser: 'safari',
                browser_version: '5.1',
                os: 'OS X',
                os_version: 'Snow Leopard'
        },

        BS_SAFARI6: {
            base: 'BrowserStack',
                browser: 'safari',
                browser_version: '6.0',
                os: 'OS X',
                os_version: 'Mountain Lion'
        },

        BS_OPERA15: {
            base: 'BrowserStack',
                os: 'Windows',
                browser: 'opera',
                os_version: '7',
                browser_version: '15.0'
        },

        BS_ANDROID_23: {
            base: 'BrowserStack',
                os: 'android',
                device: 'Samsung Galaxy S II',
                browser: 'Android Browser',
                os_version: '2.3',
                browser_version: null
        },

        BS_ANDROID_4: {
            base: 'BrowserStack',
                os: 'android',
                device: 'Samsung Galaxy Tab 2 10.1',
                browser: 'Android Browser',
                os_version: '4.0',
                browser_version: null
        },

        BS_ANDROID_41: {
            base: 'BrowserStack',
                os: 'android',
                device: 'Samsung Galaxy Note II',
                browser: 'Android Browser',
                os_version: '4.1',
                browser_version: null
        },

        BS_ANDROID_42: {
            base: 'BrowserStack',
                os: 'android',
                device: 'LG Nexus 4',
                browser: 'Android Browser',
                os_version: '4.2',
                browser_version: null
        },

        BS_IOS_6: {
            base: 'BrowserStack',
                os: 'ios',
                device: 'iPad 3rd (6.0)',
                browser: 'Mobile Safari',
                os_version: '6.0',
                browser_version: null
        }

    };
    conf.autoWatch = false;
    conf.singleRun = true;
    config.set(conf);

};
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var path = require('path');
// var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

/*
    Local modules
*/

var todo = require('./api/ToDo/toDo');

/*
    Config
*/

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

/*
    Routes
*/
app.get('/*.html', express.static(__dirname + '/public'));
app.get('/bundle.js', express.static(__dirname + '/public'));
app.use('/css', express.static(__dirname + '/public/css'));

app.all('/*', function(req, res, next) {
    res.sendFile('index.html', { root: __dirname + '/public' });
});

/*
    Errors
*/

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.json({
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json({
        message: err.message,
        error: {}
    });
});

module.exports = app;
<commit_msg>updated to-do require, since to do is two words. Definitly.<commit_after>'use strict';

var express = require('express');
var path = require('path');
// var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

/*
    Local modules
*/

var todo = require('./api/to-do/to-do');

/*
    Config
*/

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

/*
    Routes
*/
app.get('/*.html', express.static(__dirname + '/public'));
app.get('/bundle.js', express.static(__dirname + '/public'));
app.use('/css', express.static(__dirname + '/public/css'));

app.all('/*', function(req, res, next) {
    res.sendFile('index.html', { root: __dirname + '/public' });
});

/*
    Errors
*/

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.json({
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json({
        message: err.message,
        error: {}
    });
});

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

module.exports = (FLOW, XIBLE, EXPRESS_APP) => {
  // retrieve all flows
  EXPRESS_APP.get('/api/flows', (req, res) => {
    const flows = res.json(XIBLE.getFlows());
  });

  // create a new flow
  EXPRESS_APP.post('/api/flows', async (req, res) => {
    if (!req.body || !req.body._id) {
      res.status(400).end();
      return;
    }

    const flow = new FLOW();
    flow.initJson(req.body, true);
    await flow.save();

    res.json({
      _id: flow._id
    });
  });

  // get a flow by a given id
  EXPRESS_APP.param('flowId', (req, res, next, id) => {
    const flow = XIBLE.getFlowById(id);

    if (!flow) {
      res.status(404).end();
      return;
    }

    req.locals.flow = flow;
    next();
  });

  // get an existing flow
  EXPRESS_APP.get('/api/flows/:flowId', (req, res) => {
    const flow = req.locals.flow;

    const returnFlow = {
      _id: flow._id,
      name: flow._id,
      nodes: flow.nodes,
      connectors: flow.json.connectors,
      viewState: flow.json.viewState,
      runnable: flow.runnable,
      directed: flow.directed,
      state: flow.state
    };

    res.json(returnFlow);
  });

  // update an existing flow
  EXPRESS_APP.put('/api/flows/:flowId', async (req, res) => {
    if (!req.body) {
      res.status(400).end();
      return;
    }

    const flow = req.locals.flow;
    await flow.stopAllInstances();

    // init the newly provided json over the existing flow
    flow.initJson(req.body, true);

    // save it to file
    await flow.save();

    // output the flow id
    res.json({
      _id: flow._id
    });
  });

  // delete an existing flow
  EXPRESS_APP.delete('/api/flows/:flowId', async (req, res) => {
    await req.locals.flow.delete();
    res.end();
  });

  // stop all instances
  EXPRESS_APP.patch('/api/flows/:flowId/stop', async (req, res) => {
    await req.locals.flow.stopAllInstances();
    res.end();
  });

  // return all instances on a flow
  EXPRESS_APP.get('/api/flows/:flowId/instances', async (req, res) => {
    res.json(req.locals.flow.instances);
  });

  // create a new flowInstance
  EXPRESS_APP.post('/api/flows/:flowId/instances', async (req, res) => {
    const instance = req.locals.flow.createInstance({
      params: req.body.params,
      directNodes: req.body.directNodes
    });
    if (req.body.start === true) {
      await instance.forceStart();
    }
    res.json(instance);
  });

  // delete all flowInstances
  EXPRESS_APP.delete('/api/flows/:flowId/instances', async (req, res) => {
    await req.locals.flow.deleteAllInstances();
    res.end();
  });

  // get an instance by a given id
  EXPRESS_APP.param('flowInstanceId', (req, res, next, id) => {
    const flowInstance = req.locals.flow.getInstanceById(id);

    if (!flowInstance) {
      res.status(404).end();
      return;
    }

    req.locals.flowInstance = flowInstance;
    next();
  });

  EXPRESS_APP.delete('/api/flows/:flowId/instances/:flowInstanceId', async (req, res) => {
    try {
      await req.locals.flowInstance.delete();
      res.end();
    } catch (err) {
      console.error(err);
      res.status(500).end();
    }
  });

  // start a flowInstance
  EXPRESS_APP.patch('/api/flows/:flowId/instances/:flowInstanceId/start', async (req, res) => {
    try {
      await req.locals.flowInstance.forceStart();
      res.end();
    } catch (err) {
      console.error(err);
      res.status(500).end();
    }
  });

  // stop a flowInstance
  EXPRESS_APP.patch('/api/flows/:flowId/instances/:flowInstanceId/stop', async (req, res) => {
    try {
      await req.locals.flowInstance.forceStop(req.body.delete);
      res.end();
    } catch (err) {
      console.error(err);
      res.status(500).end();
    }
  });

  // run part of a flow directly
  EXPRESS_APP.patch('/api/flows/:flowId/instances/:flowInstanceId/direct', (req, res) => {
    req.locals.flowInstance.direct(req.body);
    res.end();
  });
};
<commit_msg>linter fix<commit_after>'use strict';

module.exports = (FLOW, XIBLE, EXPRESS_APP) => {
  // retrieve all flows
  EXPRESS_APP.get('/api/flows', (req, res) => {
    res.json(XIBLE.getFlows());
  });

  // create a new flow
  EXPRESS_APP.post('/api/flows', async (req, res) => {
    if (!req.body || !req.body._id) {
      res.status(400).end();
      return;
    }

    const flow = new FLOW();
    flow.initJson(req.body, true);
    await flow.save();

    res.json({
      _id: flow._id
    });
  });

  // get a flow by a given id
  EXPRESS_APP.param('flowId', (req, res, next, id) => {
    const flow = XIBLE.getFlowById(id);

    if (!flow) {
      res.status(404).end();
      return;
    }

    req.locals.flow = flow;
    next();
  });

  // get an existing flow
  EXPRESS_APP.get('/api/flows/:flowId', (req, res) => {
    const flow = req.locals.flow;

    const returnFlow = {
      _id: flow._id,
      name: flow._id,
      nodes: flow.nodes,
      connectors: flow.json.connectors,
      viewState: flow.json.viewState,
      runnable: flow.runnable,
      directed: flow.directed,
      state: flow.state
    };

    res.json(returnFlow);
  });

  // update an existing flow
  EXPRESS_APP.put('/api/flows/:flowId', async (req, res) => {
    if (!req.body) {
      res.status(400).end();
      return;
    }

    const flow = req.locals.flow;
    await flow.stopAllInstances();

    // init the newly provided json over the existing flow
    flow.initJson(req.body, true);

    // save it to file
    await flow.save();

    // output the flow id
    res.json({
      _id: flow._id
    });
  });

  // delete an existing flow
  EXPRESS_APP.delete('/api/flows/:flowId', async (req, res) => {
    await req.locals.flow.delete();
    res.end();
  });

  // stop all instances
  EXPRESS_APP.patch('/api/flows/:flowId/stop', async (req, res) => {
    await req.locals.flow.stopAllInstances();
    res.end();
  });

  // return all instances on a flow
  EXPRESS_APP.get('/api/flows/:flowId/instances', async (req, res) => {
    res.json(req.locals.flow.instances);
  });

  // create a new flowInstance
  EXPRESS_APP.post('/api/flows/:flowId/instances', async (req, res) => {
    const instance = req.locals.flow.createInstance({
      params: req.body.params,
      directNodes: req.body.directNodes
    });
    if (req.body.start === true) {
      await instance.forceStart();
    }
    res.json(instance);
  });

  // delete all flowInstances
  EXPRESS_APP.delete('/api/flows/:flowId/instances', async (req, res) => {
    await req.locals.flow.deleteAllInstances();
    res.end();
  });

  // get an instance by a given id
  EXPRESS_APP.param('flowInstanceId', (req, res, next, id) => {
    const flowInstance = req.locals.flow.getInstanceById(id);

    if (!flowInstance) {
      res.status(404).end();
      return;
    }

    req.locals.flowInstance = flowInstance;
    next();
  });

  EXPRESS_APP.delete('/api/flows/:flowId/instances/:flowInstanceId', async (req, res) => {
    try {
      await req.locals.flowInstance.delete();
      res.end();
    } catch (err) {
      console.error(err);
      res.status(500).end();
    }
  });

  // start a flowInstance
  EXPRESS_APP.patch('/api/flows/:flowId/instances/:flowInstanceId/start', async (req, res) => {
    try {
      await req.locals.flowInstance.forceStart();
      res.end();
    } catch (err) {
      console.error(err);
      res.status(500).end();
    }
  });

  // stop a flowInstance
  EXPRESS_APP.patch('/api/flows/:flowId/instances/:flowInstanceId/stop', async (req, res) => {
    try {
      await req.locals.flowInstance.forceStop(req.body.delete);
      res.end();
    } catch (err) {
      console.error(err);
      res.status(500).end();
    }
  });

  // run part of a flow directly
  EXPRESS_APP.patch('/api/flows/:flowId/instances/:flowInstanceId/direct', (req, res) => {
    req.locals.flowInstance.direct(req.body);
    res.end();
  });
};
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.factories')

.factory('pdfReader', function($q) {
    var getAllTextFromPdf = function(pdfDataUrl) {

// http://stackoverflow.com/questions/12092633/pdf-js-rendering-a-pdf-file-using-a-base64-file-source-instead-of-url
      var BASE64_MARKER = ';base64,';
      function convertDataURIToBinary(dataURI) {
        var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
        var base64 = dataURI.substring(base64Index);
        var raw = window.atob(base64);
        var rawLength = raw.length;
        var array = new Uint8Array(new ArrayBuffer(rawLength));

        for(var i = 0; i < rawLength; i++) {
          array[i] = raw.charCodeAt(i);
        }
        return array;
      }
      var pdfAsArray = convertDataURIToBinary(pdfDataUrl);

      return PDFJS.getDocument(pdfAsArray).then(function(pdf) {
        var allTextFromPdf = [];
        var numPages = pdf.pdfInfo.numPages;
        var promises = [];
        //console.log("pages", numPages);
        for (var i = 1; i <= numPages; i++) {
          promises.push(getTextFromPdfPage(i, pdf).then(function(textFromPdfPage) {
            return textFromPdfPage;
          })); // push the Promises to our array
        }
        return $q.all(promises).then(function(allPromiseResults) {
          allPromiseResults.forEach(function(textFromPdfPage) {
            Array.prototype.push.apply(allTextFromPdf, textFromPdfPage);
          });
          return allTextFromPdf;
        });
      });
    };

    var getTextFromPdfPage = function(pageNumber, pdf) {
      return pdf.getPage(pageNumber).then(function(page) {
        return page.getTextContent().then(function(textContent) {
          function isLowerCase(str) {
            return str === str.toLowerCase();
          }

          function repairPdfTextFormatting(textContent) {
            var repairedTextContent = [];
            for(var i = 0; i < textContent.items.length; i++) {
              var currentElement = textContent.items[i].str;
              if (currentElement == String.fromCharCode(160)) { // TODO: factor as global const
                // Non-breakable space is char 160. Fixes PDFs exported from Google Docs
                currentElement = " ";
                repairedTextContent.push(currentElement);
              } else if (isLowerCase(currentElement.slice(0, 1))) {
                // If it starts with lowercase letter, append it to the end of the previous line
                // Fixes things like ["Work experi", "e", "n", "ce"]
                repairedTextContent[repairedTextContent.length - 1] += currentElement;
              } else {
                repairedTextContent.push(currentElement);
              }
            }
            return repairedTextContent;
          }
          return repairPdfTextFormatting(textContent);
        });
      });
    };

    return {
      getAllTextFromPdf: getAllTextFromPdf
    };
});<commit_msg>PDF Reader: Remove unnecessary function<commit_after>'use strict';

angular.module('myApp.factories')

.factory('pdfReader', function($q) {
    var getAllTextFromPdf = function(pdfDataUrl) {
      return PDFJS.getDocument(pdfDataUrl).then(function(pdf) {
        var allTextFromPdf = [];
        var numPages = pdf.pdfInfo.numPages;
        var promises = [];
        //console.log("pages", numPages);
        for (var i = 1; i <= numPages; i++) {
          promises.push(getTextFromPdfPage(i, pdf).then(function(textFromPdfPage) {
            return textFromPdfPage;
          })); // push the Promises to our array
        }
        return $q.all(promises).then(function(allPromiseResults) {
          allPromiseResults.forEach(function(textFromPdfPage) {
            Array.prototype.push.apply(allTextFromPdf, textFromPdfPage);
          });
          return allTextFromPdf;
        });
      });
    };

    var getTextFromPdfPage = function(pageNumber, pdf) {
      return pdf.getPage(pageNumber).then(function(page) {
        return page.getTextContent().then(function(textContent) {
          function isLowerCase(str) {
            return str === str.toLowerCase();
          }

          function repairPdfTextFormatting(textContent) {
            var repairedTextContent = [];
            for(var i = 0; i < textContent.items.length; i++) {
              var currentElement = textContent.items[i].str;
              if (currentElement == String.fromCharCode(160)) { // TODO: factor as global const
                // Non-breakable space is char 160. Fixes PDFs exported from Google Docs
                currentElement = " ";
                repairedTextContent.push(currentElement);
              } else if (isLowerCase(currentElement.slice(0, 1))) {
                // If it starts with lowercase letter, append it to the end of the previous line
                // Fixes things like ["Work experi", "e", "n", "ce"]
                repairedTextContent[repairedTextContent.length - 1] += currentElement;
              } else {
                repairedTextContent.push(currentElement);
              }
            }
            return repairedTextContent;
          }
          return repairPdfTextFormatting(textContent);
        });
      });
    };

    return {
      getAllTextFromPdf: getAllTextFromPdf
    };
});<|endoftext|>


<commit_before>import ModalBase from 'open-event-frontend/components/modals/modal-base';

export default ModalBase.extend({
  onVisible() {
    this.$('.content').css('height', '300px');
    this.$('img').croppie({
      customClass : 'croppie',
      viewport    : {
        width  : 400,
        height : 200,
        type   : 'square'
      },
      boundary: {
        width  : 600,
        height : 300
      }
    });
  },

  onHide() {
    this.$('img').croppie('destroy');
    const $img = this.$('img');
    if ($img.parent().is('div.croppie')) {
      $img.unwrap();
    }
  },

  actions: {
    resetImage() {
      this.onHide();
      this.onVisible();
    },
    cropImage() {
      this.$('img').croppie('result', 'base64', 'original', 'jpeg').then(result => {
        if (this.get('onImageCrop')) {
          this.onImageCrop(result);
        }
      });
    }
  }
});
<commit_msg>prevents image upload widget overflow<commit_after>import ModalBase from 'open-event-frontend/components/modals/modal-base';

export default ModalBase.extend({
  onVisible() {
    this.$('.content').css('height', '300px');
    this.$('img').croppie({
      customClass : 'croppie',
      viewport    : {
        width  : 300,
        height : 150,
        type   : 'square'
      },
      boundary: {
        height: 250
      }
    });
  },

  onHide() {
    this.$('img').croppie('destroy');
    const $img = this.$('img');
    if ($img.parent().is('div.croppie')) {
      $img.unwrap();
    }
  },

  actions: {
    resetImage() {
      this.onHide();
      this.onVisible();
    },
    cropImage() {
      this.$('img').croppie('result', 'base64', 'original', 'jpeg').then(result => {
        if (this.get('onImageCrop')) {
          this.onImageCrop(result);
        }
      });
    }
  }
});
<|endoftext|>


<commit_before>const webpack = require('webpack');
const merge = require('webpack-merge');
const path = require('path');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const sharedConfig = require('./shared.js');

module.exports = merge(sharedConfig, {

  output: { filename: '[name]-[hash].js' },

  module: {
    rules: [{
      test: /\.(jpe?g|png|gif|svg)$/i,
      use: [
        'file-loader',
        {
          loader: 'image-webpack-loader',
          query: {
            mozjpeg: {
              progressive: true
            },
            gifsicle: {
              interlaced: false
            },
            optipng: {
              optimizationLevel: 7
            },
            pngquant: {
              quality: '75-90',
              speed: 4
            }
          }
        }
      ]
    }, {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader'
      })
    }, {
      test: /\.(scss|sass)$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [{
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        }, {
          loader: 'postcss-loader',
          options: {
            config: {
              path: path.resolve(__dirname, '../../postcss.config.js')
            }
          }
        }, {
          loader: 'sass-loader',
          options: {
            includePaths: [
              path.resolve(__dirname, '../../app/styles')
            ]
          }
        }]
      })
    }]
  },

  plugins: [
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new ExtractTextPlugin('styles.css'),
    new UglifyJSPlugin(),
    process.env.BUNDLE_ANALIZE ? new BundleAnalyzerPlugin({
      analyzerMode: 'static'
    }) : null
  ],

  externals: {
    leaflet: 'L',
    'esri-leaflet': 'L.esri'
  }

});
<commit_msg>fixing bundle<commit_after>const webpack = require('webpack');
const merge = require('webpack-merge');
const path = require('path');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const sharedConfig = require('./shared.js');

module.exports = merge(sharedConfig, {

  output: { filename: '[name]-[hash].js' },

  module: {
    rules: [{
      test: /\.(jpe?g|png|gif|svg)$/i,
      use: [
        'file-loader',
        {
          loader: 'image-webpack-loader',
          query: {
            mozjpeg: {
              progressive: true
            },
            gifsicle: {
              interlaced: false
            },
            optipng: {
              optimizationLevel: 7
            },
            pngquant: {
              quality: '75-90',
              speed: 4
            }
          }
        }
      ]
    }, {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader'
      })
    }, {
      test: /\.(scss|sass)$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [{
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        }, {
          loader: 'postcss-loader',
          options: {
            config: {
              path: path.resolve(__dirname, '../../postcss.config.js')
            }
          }
        }, {
          loader: 'sass-loader',
          options: {
            includePaths: [
              path.resolve(__dirname, '../../app/styles')
            ]
          }
        }]
      })
    }]
  },

  plugins: [
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new ExtractTextPlugin('styles.css'),
    new UglifyJSPlugin(),
    process.env.BUNDLE_ANALIZE ? new BundleAnalyzerPlugin({
      analyzerMode: 'static'
    }) : function() {}
  ],

  externals: {
    leaflet: 'L',
    'esri-leaflet': 'L.esri'
  }

});
<|endoftext|>


<commit_before>import "./creating.styl"
import template from "./creating.pug"

import autobind from "autobind-decorator"
import BaseComponent from "components/base-component"
import formSerialize from "form-serialize"
import {postJson} from "simple-fetch"
import $$ from "lib/constants"

export default class CreatingStep extends BaseComponent {
  static template = template;

  @autobind
  onEnter() {
    const {$root} = this
    const onComplete = ({downloadURL}) => {
      $root.downloadURL = downloadURL
      $root.$activeStep = "download"
    }

    const {detailsForm} = $root.steps.details.refs
    const pluginDetails = formSerialize(detailsForm, {hash: true})

    pluginDetails.app.icon = pluginDetails.app.icon || $$.DEFAULT_PLUGIN_ICON

    const payload = {
      cmsName: "wordpress",
      installJSON: $root.$installJSON,
      ...pluginDetails
    }

    postJson(`${API_BASE}/create/instant`, payload)
      .then(onComplete)
      .catch(error => console.error(error))
  }
}
<commit_msg>Smooth creation step transition.<commit_after>import "./creating.styl"
import template from "./creating.pug"

import autobind from "autobind-decorator"
import BaseComponent from "components/base-component"
import formSerialize from "form-serialize"
import {postJson} from "simple-fetch"
import $$ from "lib/constants"

const MINIMUM_TRANSITION_DELAY = 2000

export default class CreatingStep extends BaseComponent {
  static template = template;

  @autobind
  onEnter() {
    const {$root} = this
    const {detailsForm} = $root.steps.details.refs
    const pluginDetails = formSerialize(detailsForm, {hash: true})
    const startTime = Date.now()

    const onComplete = ({downloadURL}) => {
      // Delay the transition slightly to smooth out the animation.
      const delay = Math.max(MINIMUM_TRANSITION_DELAY - (Date.now() - startTime), 0)

      setTimeout(() => {
        $root.downloadURL = downloadURL
        $root.$activeStep = "download"
      }, delay)
    }

    pluginDetails.app.icon = pluginDetails.app.icon || $$.DEFAULT_PLUGIN_ICON

    const payload = {
      cmsName: "wordpress",
      installJSON: $root.$installJSON,
      ...pluginDetails
    }

    postJson(`${API_BASE}/create/instant`, payload)
      .then(onComplete)
      .catch(error => console.error(error))
  }
}
<|endoftext|>


<commit_before>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2011 Sebastian Werner
--------------------------------------------------------------------------------------------------
  Based on code of Unify Project
  License: MIT + Apache (V2)
  Copyright: 2009-2011 Deutsche Telekom AG, Germany, http://telekom.com
==================================================================================================
*/

(function() {

	var agent = navigator.userAgent.replace(/_/g, ".");
	var match, version, name;

	if (core.Env.isSet("platform", "win"))
	{
		name = "win";
		match = /((Windows NT|Windows|Win) ?([0-9\.]+))/.exec(agent);
		if (match)
		{
			version = {
				"5.0" : "2000",
				"5.01" : "2000",
				"5.1" : "xp",
				"5.2" : "2003",
				"6.0" : "vista",
				"6.1" : "7"
			}[parseFloat(match[3], 10)] || version;
		}
		else
		{
			match = /(Windows CE)/.exec(agent);
			if (match)
			{
				match = /IEMobile ([0-9\.]+)/.exec(agent);
				if (match)
				{
					version = parseFloat(match[1]);
					if (version >= 7) {
						version = 6.1;
					} else if (version >= 6) {
						version = 6.0;
					} else {
						version = 5.0;
					}
				}
				else
				{
					match = /PPC|Smartphone/.exec(agent);
					if (match) {
						version = 5.0;
					}
				}

				name = "winmobile";
			}
			else if (/PPC|Smartphone/.exec(agent))
			{
				name = "winmobile";
				version = 5.0;
			}
		}
	}
	else if (core.Env.isSet("platform", "mac"))
	{
		match = /(((Mac OS X)|(Mac OS)) ([0-9\.]+))/.exec(agent);
		name = "macos";
		if (match)
		{
			version = parseFloat(match[5], 10);
		}
		else
		{
			var match = /((iPhone OS|iOS) ([0-9\.]+))/.exec(agent);
			if (match)
			{
				version = parseFloat(match[3]);
				name = "ios";
			}
			else
			{
				// If detection of iOS with user string without version number, test for generic
				// device names
				if (/(iPad|iPhone|iPod)/.test(agent)) {
					name = "ios";
					var match=/OS (\d+\.\d+)(?:(?:\.\d+)+)? like/.exec(agent);
					if(match){
						version=parseFloat(match[1],10);
					}
				} else {
					// Fallback
					// Opera as of Version 10.01 has no information about the detailed
					// Mac OS X version. Are other clients affected as well?

					// The last option here is to simply base on the OS X string
					// basically found on all new Macs - even in Opera
					if (navigator.platform === "MacIntel") {
						version = 10.4;
					} else if (/Mac OS X/.exec(agent)) {
						version = 10.0;
					} else {
						version = 9.0;
					}
				}
			}
		}
	}
	else if (core.Env.isSet("platform", "unix"))
	{
		if (agent.indexOf("Linux") != -1)
		{
			match = /((Android|Maemo) ([0-9\.]+))/.exec(agent);
			if (match)
			{
				name = match[2].toLowerCase();
				version = parseFloat(match[3]);
			}
			else
			{
				name = "linux";
			}
		}
		else if (agent.indexOf("webOS") != -1)
		{
			name = "webos";
			match = /webOS\/([\.0-9]+)/.exec(agent);
			if (match) {
				version = parseFloat(match[1]);
			}
		}
		else if (agent.indexOf("BSD") != -1)
		{
			name = "bsd";
		}
		else
		{
			name = "unix";
		}
	}
	else if (core.Env.isSet("platform", "other"))
	{
		if (agent.indexOf("RIM Tablet OS") != -1)
		{
			name = "rim tablet os";
			match = /RIM Tablet OS ([\.0-9]+)/.exec(agent);
			if (match) {
				version = parseFloat(match[1]);
			}
		}
		else if (agent.indexOf("Symbian") != -1)
		{
			name = "symbian";
		}
	}

	if (version == null) {
		version = "0.0";
	}

	/**
	 * Detects the system where the application is running on. This is more detailed
	 * than just the platform as on most of them it includes the specific version
	 * e.g. Windows XP or a specific variant e.g. Android.
	 *
	 * The listed constants are automatically filled on the initialization
	 * phase of the class. The defaults listed in the API viewer need not
	 * to be identical to the values at runtime.
	 *
	 * @require {core.detect.Platform}
	 */
	core.Module("core.detect.System", {

		VALUE: name + " " + version

	});

})();<commit_msg>Minor change<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2011 Sebastian Werner
--------------------------------------------------------------------------------------------------
  Based on code of Unify Project
  License: MIT + Apache (V2)
  Copyright: 2009-2011 Deutsche Telekom AG, Germany, http://telekom.com
==================================================================================================
*/

(function() {

	var agent = navigator.userAgent.replace(/_/g, ".");
	var match, version, name;

	if (core.Env.isSet("platform", "win"))
	{
		name = "win";
		match = /((Windows NT|Windows|Win) ?([0-9\.]+))/.exec(agent);
		if (match)
		{
			version = {
				"5.0" : "2000",
				"5.01" : "2000",
				"5.1" : "xp",
				"5.2" : "2003",
				"6.0" : "vista",
				"6.1" : "7"
			}[parseFloat(match[3], 10)] || version;
		}
		else
		{
			match = /(Windows CE)/.exec(agent);
			if (match)
			{
				match = /IEMobile ([0-9\.]+)/.exec(agent);
				if (match)
				{
					version = parseFloat(match[1]);
					if (version >= 7) {
						version = 6.1;
					} else if (version >= 6) {
						version = 6.0;
					} else {
						version = 5.0;
					}
				}
				else
				{
					match = /PPC|Smartphone/.exec(agent);
					if (match) {
						version = 5.0;
					}
				}

				name = "winmobile";
			}
			else if (/PPC|Smartphone/.exec(agent))
			{
				name = "winmobile";
				version = 5.0;
			}
		}
	}
	else if (core.Env.isSet("platform", "mac"))
	{
		match = /(((Mac OS X)|(Mac OS)) ([0-9\.]+))/.exec(agent);
		name = "macos";
		if (match)
		{
			version = parseFloat(match[5], 10);
		}
		else
		{
			var match = /((iPhone OS|iOS) ([0-9\.]+))/.exec(agent);
			if (match)
			{
				version = parseFloat(match[3]);
				name = "ios";
			}
			else
			{
				// If detection of iOS with user string without version number, test for generic
				// device names
				if (/(iPad|iPhone|iPod)/.test(agent)) {
					name = "ios";
					var match=/OS (\d+\.\d+)(?:(?:\.\d+)+)? like/.exec(agent);
					if(match){
						version = parseFloat(match[1],10);
					}
				} else {
					// Fallback
					// Opera as of Version 10.01 has no information about the detailed
					// Mac OS X version. Are other clients affected as well?

					// The last option here is to simply base on the OS X string
					// basically found on all new Macs - even in Opera
					if (navigator.platform === "MacIntel") {
						version = 10.4;
					} else if (/Mac OS X/.exec(agent)) {
						version = 10.0;
					} else {
						version = 9.0;
					}
				}
			}
		}
	}
	else if (core.Env.isSet("platform", "unix"))
	{
		if (agent.indexOf("Linux") != -1)
		{
			match = /((Android|Maemo) ([0-9\.]+))/.exec(agent);
			if (match)
			{
				name = match[2].toLowerCase();
				version = parseFloat(match[3]);
			}
			else
			{
				name = "linux";
			}
		}
		else if (agent.indexOf("webOS") != -1)
		{
			name = "webos";
			match = /webOS\/([\.0-9]+)/.exec(agent);
			if (match) {
				version = parseFloat(match[1]);
			}
		}
		else if (agent.indexOf("BSD") != -1)
		{
			name = "bsd";
		}
		else
		{
			name = "unix";
		}
	}
	else if (core.Env.isSet("platform", "other"))
	{
		if (agent.indexOf("RIM Tablet OS") != -1)
		{
			name = "rim tablet os";
			match = /RIM Tablet OS ([\.0-9]+)/.exec(agent);
			if (match) {
				version = parseFloat(match[1]);
			}
		}
		else if (agent.indexOf("Symbian") != -1)
		{
			name = "symbian";
		}
	}

	if (version == null) {
		version = "0.0";
	}

	/**
	 * Detects the system where the application is running on. This is more detailed
	 * than just the platform as on most of them it includes the specific version
	 * e.g. Windows XP or a specific variant e.g. Android.
	 *
	 * The listed constants are automatically filled on the initialization
	 * phase of the class. The defaults listed in the API viewer need not
	 * to be identical to the values at runtime.
	 *
	 * @require {core.detect.Platform}
	 */
	core.Module("core.detect.System", {

		VALUE: name + " " + version

	});

})();<|endoftext|>