<commit_before>window.iD = function () {
    window.locale.en = iD.data.en;
    window.locale.current('en');

    var context = {},
        storage;

    // https://github.com/openstreetmap/iD/issues/772
    // http://mathiasbynens.be/notes/localstorage-pattern#comment-9
    try { storage = localStorage; } catch (e) {}
    storage = storage || (function() {
        var s = {};
        return {
            getItem: function(k) { return s[k]; },
            setItem: function(k, v) { s[k] = v; },
            removeItem: function(k) { delete s[k]; }
        };
    })();

    context.storage = function(k, v) {
        try {
            if (arguments.length === 1) return storage.getItem(k);
            else if (v === null) storage.removeItem(k);
            else storage.setItem(k, v);
        } catch(e) {
            // localstorage quota exceeded
            /* jshint devel:true */
            if (typeof console !== 'undefined') console.error('localStorage quota exceeded');
            /* jshint devel:false */
        }
    };

    /* Accessor for setting minimum zoom for editing features. */

    var minEditableZoom = 16;
    context.minEditableZoom = function(_) {
        if (!arguments.length) return minEditableZoom;
        minEditableZoom = _;
        connection.tileZoom(_);
        return context;
    };

    var history = iD.History(context),
        dispatch = d3.dispatch('enter', 'exit'),
        mode,
        container,
        ui = iD.ui(context),
        connection = iD.Connection(),
        locale = iD.detect().locale,
        localePath;

    if (locale && iD.data.locales.indexOf(locale) === -1) {
        locale = locale.split('-')[0];
    }

    connection.on('load.context', function loadContext(err, result) {
        history.merge(result.data, result.extent);
    });

    context.preauth = function(options) {
        connection.switch(options);
        return context;
    };

    context.locale = function(_, path) {
        locale = _;
        localePath = path;
        return context;
    };

    context.loadLocale = function(cb) {
        if (locale && locale !== 'en' && iD.data.locales.indexOf(locale) !== -1) {
            localePath = localePath || context.assetPath() + 'locales/' + locale + '.json';
            d3.json(localePath, function(err, result) {
                window.locale[locale] = result;
                window.locale.current(locale);
                cb();
            });
        } else {
            cb();
        }
    };

    /* Straight accessors. Avoid using these if you can. */
    context.ui = function() { return ui; };
    context.connection = function() { return connection; };
    context.history = function() { return history; };

    /* History */
    context.graph = history.graph;
    context.changes = history.changes;
    context.intersects = history.intersects;

    var inIntro = false;

    context.inIntro = function(_) {
        if (!arguments.length) return inIntro;
        inIntro = _;
        return context;
    };

    context.save = function() {
        if (inIntro) return;
        history.save();
        if (history.hasChanges()) return t('save.unsaved_changes');
    };

    context.flush = function() {
        connection.flush();
        features.reset();
        history.reset();
        return context;
    };

    // Debounce save, since it's a synchronous localStorage write,
    // and history changes can happen frequently (e.g. when dragging).
    var debouncedSave = _.debounce(context.save, 350);
    function withDebouncedSave(fn) {
        return function() {
            var result = fn.apply(history, arguments);
            debouncedSave();
            return result;
        };
    }

    context.perform = withDebouncedSave(history.perform);
    context.replace = withDebouncedSave(history.replace);
    context.pop = withDebouncedSave(history.pop);
    context.undo = withDebouncedSave(history.undo);
    context.redo = withDebouncedSave(history.redo);

    /* Graph */
    context.hasEntity = function(id) {
        return history.graph().hasEntity(id);
    };

    context.entity = function(id) {
        return history.graph().entity(id);
    };

    context.childNodes = function(way) {
        return history.graph().childNodes(way);
    };

    context.geometry = function(id) {
        return context.entity(id).geometry(history.graph());
    };

    /* Modes */
    context.enter = function(newMode) {
        if (mode) {
            mode.exit();
            dispatch.exit(mode);
        }

        mode = newMode;
        mode.enter();
        dispatch.enter(mode);
    };

    context.mode = function() {
        return mode;
    };

    context.selectedIDs = function() {
        if (mode && mode.selectedIDs) {
            return mode.selectedIDs();
        } else {
            return [];
        }
    };

    context.loadEntity = function(id, zoomTo) {
        if (zoomTo !== false) {
            connection.loadEntity(id, function(error, entity) {
                if (entity) {
                    map.zoomTo(entity);
                }
            });
        }

        map.on('drawn.loadEntity', function() {
            if (!context.hasEntity(id)) return;
            map.on('drawn.loadEntity', null);
            context.on('enter.loadEntity', null);
            context.enter(iD.modes.Select(context, [id]));
        });

        context.on('enter.loadEntity', function() {
            if (mode.id !== 'browse') {
                map.on('drawn.loadEntity', null);
                context.on('enter.loadEntity', null);
            }
        });
    };

    /* Behaviors */
    context.install = function(behavior) {
        context.surface().call(behavior);
    };

    context.uninstall = function(behavior) {
        context.surface().call(behavior.off);
    };

    /* Projection */
    context.projection = iD.geo.RawMercator();

    /* Background */
    var background = iD.Background(context);
    context.background = function() { return background; };

    /* Features */
    var features = iD.Features(context);
    context.features = function() { return features; };
    context.hasHiddenConnections = function(id) {
        var graph = history.graph(),
            entity = graph.entity(id);
        return features.hasHiddenConnections(entity, graph);
    };

    /* Map */
    var map = iD.Map(context);
    context.map = function() { return map; };
    context.layers = function() { return map.layers; };
    context.surface = function() { return map.surface; };
    context.editable = function() { return map.editable(); };
    context.mouse = map.mouse;
    context.extent = map.extent;
    context.pan = map.pan;
    context.zoomIn = map.zoomIn;
    context.zoomOut = map.zoomOut;

    context.surfaceRect = function() {
        // Work around a bug in Firefox.
        //   http://stackoverflow.com/questions/18153989/
        //   https://bugzilla.mozilla.org/show_bug.cgi?id=530985
        return context.surface().node().parentNode.getBoundingClientRect();
    };

    /* Presets */
    var presets = iD.presets();

    context.presets = function(_) {
        if (!arguments.length) return presets;
        presets.load(_);
        iD.areaKeys = presets.areaKeys();
        return context;
    };

    context.imagery = function(_) {
        background.load(_);
        return context;
    };

    context.container = function(_) {
        if (!arguments.length) return container;
        container = _;
        container.classed('id-container', true);
        return context;
    };

    /* Taginfo */
    var taginfo;
    context.taginfo = function(_) {
        if (!arguments.length) return taginfo;
        taginfo = _;
        return context;
    };

    var embed = false;
    context.embed = function(_) {
        if (!arguments.length) return embed;
        embed = _;
        return context;
    };

    var assetPath = '';
    context.assetPath = function(_) {
        if (!arguments.length) return assetPath;
        assetPath = _;
        return context;
    };

    var assetMap = {};
    context.assetMap = function(_) {
        if (!arguments.length) return assetMap;
        assetMap = _;
        return context;
    };

    context.imagePath = function(_) {
        var asset = 'img/' + _;
        return assetMap[asset] || assetPath + asset;
    };

    return d3.rebind(context, dispatch, 'on');
};

iD.version = '1.6.1';

(function() {
    var detected = {};

    var ua = navigator.userAgent,
        msie = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');

    if (msie.exec(ua) !== null) {
        var rv = parseFloat(RegExp.$1);
        detected.support = !(rv && rv < 9);
    } else {
        detected.support = true;
    }

    // Added due to incomplete svg style support. See #715
    detected.opera = ua.indexOf('Opera') >= 0;

    detected.locale = navigator.language || navigator.userLanguage;

    detected.filedrop = (window.FileReader && 'ondrop' in window);

    function nav(x) {
        return navigator.userAgent.indexOf(x) !== -1;
    }

    if (nav('Win')) detected.os = 'win';
    else if (nav('Mac')) detected.os = 'mac';
    else if (nav('X11')) detected.os = 'linux';
    else if (nav('Linux')) detected.os = 'linux';
    else detected.os = 'win';

    iD.detect = function() { return detected; };
})();
<commit_msg>support loading entities into alternate graph..<commit_after>window.iD = function () {
    window.locale.en = iD.data.en;
    window.locale.current('en');

    var context = {},
        storage;

    // https://github.com/openstreetmap/iD/issues/772
    // http://mathiasbynens.be/notes/localstorage-pattern#comment-9
    try { storage = localStorage; } catch (e) {}
    storage = storage || (function() {
        var s = {};
        return {
            getItem: function(k) { return s[k]; },
            setItem: function(k, v) { s[k] = v; },
            removeItem: function(k) { delete s[k]; }
        };
    })();

    context.storage = function(k, v) {
        try {
            if (arguments.length === 1) return storage.getItem(k);
            else if (v === null) storage.removeItem(k);
            else storage.setItem(k, v);
        } catch(e) {
            // localstorage quota exceeded
            /* jshint devel:true */
            if (typeof console !== 'undefined') console.error('localStorage quota exceeded');
            /* jshint devel:false */
        }
    };

    /* Accessor for setting minimum zoom for editing features. */

    var minEditableZoom = 16;
    context.minEditableZoom = function(_) {
        if (!arguments.length) return minEditableZoom;
        minEditableZoom = _;
        connection.tileZoom(_);
        return context;
    };

    var history = iD.History(context),
        dispatch = d3.dispatch('enter', 'exit'),
        mode,
        container,
        ui = iD.ui(context),
        connection = iD.Connection(),
        locale = iD.detect().locale,
        localePath,
        altGraph;

    if (locale && iD.data.locales.indexOf(locale) === -1) {
        locale = locale.split('-')[0];
    }

    connection.on('load.context', function loadContext(err, result) {
        if (altGraph) {
            altGraph.rebase(result.data, [altGraph]);
        } else {
            history.merge(result.data, result.extent);
        }
    });

    context.preauth = function(options) {
        connection.switch(options);
        return context;
    };

    context.locale = function(_, path) {
        locale = _;
        localePath = path;
        return context;
    };

    context.loadLocale = function(cb) {
        if (locale && locale !== 'en' && iD.data.locales.indexOf(locale) !== -1) {
            localePath = localePath || context.assetPath() + 'locales/' + locale + '.json';
            d3.json(localePath, function(err, result) {
                window.locale[locale] = result;
                window.locale.current(locale);
                cb();
            });
        } else {
            cb();
        }
    };

    /* Straight accessors. Avoid using these if you can. */
    context.ui = function() { return ui; };
    context.connection = function() { return connection; };
    context.history = function() { return history; };

    /* History */
    context.graph = history.graph;
    context.changes = history.changes;
    context.intersects = history.intersects;

    context.altGraph = function(_) {
        if (!arguments.length) return altGraph;
        altGraph = _;
        return context;
    };

    var inIntro = false;

    context.inIntro = function(_) {
        if (!arguments.length) return inIntro;
        inIntro = _;
        return context;
    };

    context.save = function() {
        if (inIntro) return;
        history.save();
        if (history.hasChanges()) return t('save.unsaved_changes');
    };

    context.flush = function() {
        altGraph = undefined;
        connection.flush();
        features.reset();
        history.reset();
        return context;
    };

    // Debounce save, since it's a synchronous localStorage write,
    // and history changes can happen frequently (e.g. when dragging).
    var debouncedSave = _.debounce(context.save, 350);
    function withDebouncedSave(fn) {
        return function() {
            var result = fn.apply(history, arguments);
            debouncedSave();
            return result;
        };
    }

    context.perform = withDebouncedSave(history.perform);
    context.replace = withDebouncedSave(history.replace);
    context.pop = withDebouncedSave(history.pop);
    context.undo = withDebouncedSave(history.undo);
    context.redo = withDebouncedSave(history.redo);

    /* Graph */
    context.hasEntity = function(id) {
        return history.graph().hasEntity(id);
    };

    context.entity = function(id) {
        return history.graph().entity(id);
    };

    context.childNodes = function(way) {
        return history.graph().childNodes(way);
    };

    context.geometry = function(id) {
        return context.entity(id).geometry(history.graph());
    };

    /* Modes */
    context.enter = function(newMode) {
        if (mode) {
            mode.exit();
            dispatch.exit(mode);
        }

        mode = newMode;
        mode.enter();
        dispatch.enter(mode);
    };

    context.mode = function() {
        return mode;
    };

    context.selectedIDs = function() {
        if (mode && mode.selectedIDs) {
            return mode.selectedIDs();
        } else {
            return [];
        }
    };

    context.loadEntity = function(id, zoomTo) {
        if (zoomTo !== false) {
            connection.loadEntity(id, function(error, entity) {
                if (entity) {
                    map.zoomTo(entity);
                }
            });
        }

        map.on('drawn.loadEntity', function() {
            if (!context.hasEntity(id)) return;
            map.on('drawn.loadEntity', null);
            context.on('enter.loadEntity', null);
            context.enter(iD.modes.Select(context, [id]));
        });

        context.on('enter.loadEntity', function() {
            if (mode.id !== 'browse') {
                map.on('drawn.loadEntity', null);
                context.on('enter.loadEntity', null);
            }
        });
    };

    /* Behaviors */
    context.install = function(behavior) {
        context.surface().call(behavior);
    };

    context.uninstall = function(behavior) {
        context.surface().call(behavior.off);
    };

    /* Projection */
    context.projection = iD.geo.RawMercator();

    /* Background */
    var background = iD.Background(context);
    context.background = function() { return background; };

    /* Features */
    var features = iD.Features(context);
    context.features = function() { return features; };
    context.hasHiddenConnections = function(id) {
        var graph = history.graph(),
            entity = graph.entity(id);
        return features.hasHiddenConnections(entity, graph);
    };

    /* Map */
    var map = iD.Map(context);
    context.map = function() { return map; };
    context.layers = function() { return map.layers; };
    context.surface = function() { return map.surface; };
    context.editable = function() { return map.editable(); };
    context.mouse = map.mouse;
    context.extent = map.extent;
    context.pan = map.pan;
    context.zoomIn = map.zoomIn;
    context.zoomOut = map.zoomOut;

    context.surfaceRect = function() {
        // Work around a bug in Firefox.
        //   http://stackoverflow.com/questions/18153989/
        //   https://bugzilla.mozilla.org/show_bug.cgi?id=530985
        return context.surface().node().parentNode.getBoundingClientRect();
    };

    /* Presets */
    var presets = iD.presets();

    context.presets = function(_) {
        if (!arguments.length) return presets;
        presets.load(_);
        iD.areaKeys = presets.areaKeys();
        return context;
    };

    context.imagery = function(_) {
        background.load(_);
        return context;
    };

    context.container = function(_) {
        if (!arguments.length) return container;
        container = _;
        container.classed('id-container', true);
        return context;
    };

    /* Taginfo */
    var taginfo;
    context.taginfo = function(_) {
        if (!arguments.length) return taginfo;
        taginfo = _;
        return context;
    };

    var embed = false;
    context.embed = function(_) {
        if (!arguments.length) return embed;
        embed = _;
        return context;
    };

    var assetPath = '';
    context.assetPath = function(_) {
        if (!arguments.length) return assetPath;
        assetPath = _;
        return context;
    };

    var assetMap = {};
    context.assetMap = function(_) {
        if (!arguments.length) return assetMap;
        assetMap = _;
        return context;
    };

    context.imagePath = function(_) {
        var asset = 'img/' + _;
        return assetMap[asset] || assetPath + asset;
    };

    return d3.rebind(context, dispatch, 'on');
};

iD.version = '1.6.1';

(function() {
    var detected = {};

    var ua = navigator.userAgent,
        msie = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');

    if (msie.exec(ua) !== null) {
        var rv = parseFloat(RegExp.$1);
        detected.support = !(rv && rv < 9);
    } else {
        detected.support = true;
    }

    // Added due to incomplete svg style support. See #715
    detected.opera = ua.indexOf('Opera') >= 0;

    detected.locale = navigator.language || navigator.userLanguage;

    detected.filedrop = (window.FileReader && 'ondrop' in window);

    function nav(x) {
        return navigator.userAgent.indexOf(x) !== -1;
    }

    if (nav('Win')) detected.os = 'win';
    else if (nav('Mac')) detected.os = 'mac';
    else if (nav('X11')) detected.os = 'linux';
    else if (nav('Linux')) detected.os = 'linux';
    else detected.os = 'win';

    iD.detect = function() { return detected; };
})();
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var WebSocket = require('ws');
var url = 'ws://localhost:7001';

var danaWs;
var danaHdl;
var numSend = 0;
var numDone = 0;
var sendMutipleSamples = true;

function connectToDana() {
  danaWs = new WebSocket(url);
  danaWs.on('open', function connection(err) {
    console.log('Connected to Dana');
    iAmConnectedToDana();
  });
  danaWs.on('message', function(msg, flags) {
    if (msg !== 'done')
      console.log('Message from Dana', msg);
    numDone++;
    if (numSend === numDone) process.exit(0);
  });
  danaWs.on('error', function error(err) {
    console.log('Error from Dana', err);
  });
  danaWs.on('close', function close() {
    console.log('Disconnected from Dana');
  });
}

//connectToDana();
var numBuilds = process.argv[2];
var numTests = process.argv[3];
var numSeries = process.argv[4];
if (numBuilds === undefined) {
  console.log('Missing numBuilds')
}
if (numTests === undefined) {
  console.log('Missing numTests')
}
if (numSeries === undefined) {
  console.log('Missing numSeries')
}
if ((numBuilds === undefined) ||
  (numSeries === undefined) ||
  (numTests === undefined)) {
  console.log('usage: node pullDummyData numBuilds numTests numSeries');
  process.exit(1);
}

function sendToDana(data) {
  numSend++;
  danaWs.send(JSON.stringify(data));
  //console.log(data)
}

function iAmConnectedToDana() {

  console.log('Pulling ', numBuilds, 'builds');
  for (let ii = 0; ii < numBuilds; ii++) {
    var data = {
      api: 'addBuild',
      projectId: 'Test',
      build: {
        buildId: 1000 + ii,
        infos: {
          hash: "hash_build_" + 1000 + ii,
          abbrevHash: "abbrevHash_build_" + 1000 + ii,
          authorName: "authorName",
          authorEmail: "authorEmail",
          subject: "Dummy build " + 1000 + ii,
          url: "http://url_build_" + 1000 + ii,
        }
      },
      override: true,
    }
    sendToDana(data);
  }

  console.log('Pulling ', numTests, 'tests');
  for (let ii = 0; ii < numTests; ii++) {
    var data = {
      api: 'addSerie',
      projectId: 'Test',
      serieId: "test.dummy." + ii,
      analyse: {
        test: {}
      },
      override: true,
    }
    sendToDana(data);

    let base0, base2, lengthBase0;
    let target = Math.floor(Math.random() * 2);
    if (Math.random() < 0.6) {
      base0 = true;
      base2 = true;
    } else {
      base0 = true;
      base2 = false
    }
    lengthBase0 = Math.floor(Math.random() * (numBuilds));

    let samples = [];
    let base = base0;
    let currentLength = 0;
    let value;
    for (let jj = 0; jj < numBuilds; jj++) {
      value = base
      currentLength++
      if (currentLength === lengthBase0)
        base = base2;
      let sample = {
        buildId: 1000 + jj,
        value: value
      };
      if (sendMutipleSamples) {
        samples.push(sample)
      } else {
        sendToDana({
          api: 'addSample',
          projectId: 'Test',
          serieId: "test.dummy." + ii,
          sample: sample,
          override: true,
        });
      }
    }
    if (sendMutipleSamples) {
      sendToDana({
        api: 'addSample',
        projectId: 'Test',
        serieId: "test.dummy." + ii,
        samples: samples,
        override: true,
      });
    }
  }

  console.log('Pulling ', numSeries, 'series');
  for (let ii = 0; ii < numSeries; ii++) {
    var data = {
      api: 'addSerie',
      projectId: 'Test',
      serieId: "serie.dummy." + ii,
      analyse: {
        benchmark: {
          range: "5%",
          required: 2,
          trend: "higher"
        }
      },
      override: true,
    }
    sendToDana(data);

    let base0, base2, lengthBase0;
    let target = Math.floor(Math.random() * 3);
    if (target === 0) {
      base0 = Math.floor(Math.random() * 10000) + 100;
      base2 = base0;
    }
    if (target === 1) {
      base0 = Math.floor(Math.random() * 10000) + 100;
      base2 = Math.floor(base0 * (1 + (((Math.random() * 20) + 6) / 100)));
    }
    if (target === 2) {
      base0 = Math.floor(Math.random() * 10000) + 100;
      base2 = Math.floor(base0 * (1 - (((Math.random() * 20) + 6) / 100)));
    }
    lengthBase0 = Math.floor(Math.random() * (numBuilds));

    let samples = [];
    let base = base0;
    let currentLength = 0;
    let value;
    for (let jj = 0; jj < numBuilds; jj++) {
      value = Math.floor(base * (1 + ((Math.random() * 5) / 100)));
      currentLength++
      if (currentLength === lengthBase0)
        base = base2;
      let sample = {
        buildId: 1000 + jj,
        value: value
      };
      if (sendMutipleSamples) {
        samples.push(sample)
      } else {
        sendToDana({
          api: 'addSample',
          projectId: 'Test',
          serieId: "serie.dummy." + ii,
          sample: sample,
          override: true,
        });
      }
    }
    if (sendMutipleSamples) {
      sendToDana({
        api: 'addSample',
        projectId: 'Test',
        serieId: "serie.dummy." + ii,
        samples: samples,
        override: true,
      });
    }
  }
}

connectToDana();
<commit_msg>Dont use override when pushing data<commit_after>/*
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var WebSocket = require('ws');
var url = 'ws://localhost:7001';

var danaWs;
var danaHdl;
var numSend = 0;
var numDone = 0;
var sendMutipleSamples = true;

function connectToDana() {
  danaWs = new WebSocket(url);
  danaWs.on('open', function connection(err) {
    console.log('Connected to Dana');
    iAmConnectedToDana();
  });
  danaWs.on('message', function(msg, flags) {
    if (msg !== 'done')
      console.log('Message from Dana', msg);
    numDone++;
    if (numSend === numDone) process.exit(0);
  });
  danaWs.on('error', function error(err) {
    console.log('Error from Dana', err);
  });
  danaWs.on('close', function close() {
    console.log('Disconnected from Dana');
  });
}

//connectToDana();
var numBuilds = process.argv[2];
var numTests = process.argv[3];
var numSeries = process.argv[4];
if (numBuilds === undefined) {
  console.log('Missing numBuilds')
}
if (numTests === undefined) {
  console.log('Missing numTests')
}
if (numSeries === undefined) {
  console.log('Missing numSeries')
}
if ((numBuilds === undefined) ||
  (numSeries === undefined) ||
  (numTests === undefined)) {
  console.log('usage: node pullDummyData numBuilds numTests numSeries');
  process.exit(1);
}

function sendToDana(data) {
  numSend++;
  danaWs.send(JSON.stringify(data));
  //console.log(data)
}

function iAmConnectedToDana() {

  console.log('Pulling ', numBuilds, 'builds');
  for (let ii = 0; ii < numBuilds; ii++) {
    var data = {
      api: 'addBuild',
      projectId: 'Test',
      build: {
        buildId: 1000 + ii,
        infos: {
          hash: "hash_build_" + 1000 + ii,
          abbrevHash: "abbrevHash_build_" + 1000 + ii,
          authorName: "authorName",
          authorEmail: "authorEmail",
          subject: "Dummy build " + 1000 + ii,
          url: "http://url_build_" + 1000 + ii,
        }
      },
    }
    sendToDana(data);
  }

  console.log('Pulling ', numTests, 'tests');
  for (let ii = 0; ii < numTests; ii++) {
    var data = {
      api: 'addSerie',
      projectId: 'Test',
      serieId: "test.dummy." + ii,
      analyse: {
        test: {}
      },
    }
    sendToDana(data);

    let base0, base2, lengthBase0;
    let target = Math.floor(Math.random() * 2);
    if (Math.random() < 0.6) {
      base0 = true;
      base2 = true;
    } else {
      base0 = true;
      base2 = false
    }
    lengthBase0 = Math.floor(Math.random() * (numBuilds));

    let samples = [];
    let base = base0;
    let currentLength = 0;
    let value;
    for (let jj = 0; jj < numBuilds; jj++) {
      value = base
      currentLength++
      if (currentLength === lengthBase0)
        base = base2;
      let sample = {
        buildId: 1000 + jj,
        value: value
      };
      if (sendMutipleSamples) {
        samples.push(sample)
      } else {
        sendToDana({
          api: 'addSample',
          projectId: 'Test',
          serieId: "test.dummy." + ii,
          sample: sample,
        });
      }
    }
    if (sendMutipleSamples) {
      sendToDana({
        api: 'addSample',
        projectId: 'Test',
        serieId: "test.dummy." + ii,
        samples: samples,
      });
    }
  }

  console.log('Pulling ', numSeries, 'series');
  for (let ii = 0; ii < numSeries; ii++) {
    var data = {
      api: 'addSerie',
      projectId: 'Test',
      serieId: "serie.dummy." + ii,
      analyse: {
        benchmark: {
          range: "5%",
          required: 2,
          trend: "higher"
        }
      },
    }
    sendToDana(data);

    let base0, base2, lengthBase0;
    let target = Math.floor(Math.random() * 3);
    if (target === 0) {
      base0 = Math.floor(Math.random() * 10000) + 100;
      base2 = base0;
    }
    if (target === 1) {
      base0 = Math.floor(Math.random() * 10000) + 100;
      base2 = Math.floor(base0 * (1 + (((Math.random() * 20) + 6) / 100)));
    }
    if (target === 2) {
      base0 = Math.floor(Math.random() * 10000) + 100;
      base2 = Math.floor(base0 * (1 - (((Math.random() * 20) + 6) / 100)));
    }
    lengthBase0 = Math.floor(Math.random() * (numBuilds));

    let samples = [];
    let base = base0;
    let currentLength = 0;
    let value;
    for (let jj = 0; jj < numBuilds; jj++) {
      value = Math.floor(base * (1 + ((Math.random() * 5) / 100)));
      currentLength++
      if (currentLength === lengthBase0)
        base = base2;
      let sample = {
        buildId: 1000 + jj,
        value: value
      };
      if (sendMutipleSamples) {
        samples.push(sample)
      } else {
        sendToDana({
          api: 'addSample',
          projectId: 'Test',
          serieId: "serie.dummy." + ii,
          sample: sample,
        });
      }
    }
    if (sendMutipleSamples) {
      sendToDana({
        api: 'addSample',
        projectId: 'Test',
        serieId: "serie.dummy." + ii,
        samples: samples,
      });
    }
  }
}

connectToDana();
<|endoftext|>


<commit_before>window.onload = function() {
    var kps = 15;
    var mspk = (1 / kps) * 1000;
    var title = document.getElementById('mainBarTitle');
    var projects = document.getElementById("mainBarProjects");
    var about = document.getElementById("mainBarAbout");
    var signature = document.getElementById("signature");

    var full = window.location.host;
    console.log(full)
    console.log(document.referrer)
    var parts = full.split(".");
    if (parts.length > 2) {
        title.innerHTML = parts[0];
    }
    var titleFinalText = title.innerHTML
    var projectsFinalText = projects.innerHTML
    var aboutFinalText = about.innerHTML
    title.innerHTML = ">_"
    projects.innerHTML = ">_"
    about.innerHTML = ">_"
    anime({
        duration: titleFinalText.length * mspk,
        easing: 'linear',
        update: function(anim) {
            title.innerHTML = ">" + titleFinalText.substr(0, Math.floor(titleFinalText.length * (anim.progress / 100))) + "_"
        },
        complete: function(anim) {
            anime({
                duration: projectsFinalText.length * mspk,
                easing: 'linear',
                update: function(anim) {
                    projects.innerHTML = ">" + projectsFinalText.substr(0, Math.floor(projectsFinalText.length * (anim.progress / 100))) + "_"
                },
                complete: function(anim) {
                    anime({
                        duration: aboutFinalText.length * mspk,
                        easing: 'linear',
                        update: function(anim) {
                            about.innerHTML = ">" + aboutFinalText.substr(0, Math.floor(aboutFinalText.length * (anim.progress / 100))) + "_"
                        }
                    });
                }
            });
        }
    });
    title.onmouseenter = function() {
        anime.remove("#mainBarTitle");
        anime({
            targets: "#mainBarTitle",
            fontSize: '18px'
        });
    };
    title.onmouseout = function() {
        anime.remove("#mainBarTitle");
        anime({
            targets: "#mainBarTitle",
            fontSize: '16px'
        });
    };
    projects.onmouseenter = function() {
        anime.remove("#mainBarProjects");
        anime({
            targets: "#mainBarProjects",
            fontSize: '18px'
        });
    };
    projects.onmouseout = function() {
        anime.remove("#mainBarProjects");
        anime({
            targets: "#mainBarProjects",
            fontSize: '16px'
        });
    };
    about.onmouseenter = function() {
        anime.remove("#mainBarAbout");
        anime({
            targets: "#mainBarAbout",
            fontSize: '18px'
        });
    };
    about.onmouseout = function() {
        anime.remove("#mainBarAbout");
        anime({
            targets: "#mainBarAbout",
            fontSize: '16px'
        });
    };
};
<commit_msg>Fix name change<commit_after>window.onload = function() {
    var kps = 15;
    var mspk = (1 / kps) * 1000;
    var title = document.getElementById('mainBarTitle');
    var projects = document.getElementById("mainBarProjects");
    var about = document.getElementById("mainBarAbout");
    var signature = document.getElementById("signature");

    var full = window.location.href;
    console.log(full)
    console.log(window.location.href)
    var parts = full.split("=");
    if (parts.length > 1) {
        title.innerHTML = parts[1];
    }
    var titleFinalText = title.innerHTML
    var projectsFinalText = projects.innerHTML
    var aboutFinalText = about.innerHTML
    title.innerHTML = ">_"
    projects.innerHTML = ">_"
    about.innerHTML = ">_"
    anime({
        duration: titleFinalText.length * mspk,
        easing: 'linear',
        update: function(anim) {
            title.innerHTML = ">" + titleFinalText.substr(0, Math.floor(titleFinalText.length * (anim.progress / 100))) + "_"
        },
        complete: function(anim) {
            anime({
                duration: projectsFinalText.length * mspk,
                easing: 'linear',
                update: function(anim) {
                    projects.innerHTML = ">" + projectsFinalText.substr(0, Math.floor(projectsFinalText.length * (anim.progress / 100))) + "_"
                },
                complete: function(anim) {
                    anime({
                        duration: aboutFinalText.length * mspk,
                        easing: 'linear',
                        update: function(anim) {
                            about.innerHTML = ">" + aboutFinalText.substr(0, Math.floor(aboutFinalText.length * (anim.progress / 100))) + "_"
                        }
                    });
                }
            });
        }
    });
    title.onmouseenter = function() {
        anime.remove("#mainBarTitle");
        anime({
            targets: "#mainBarTitle",
            fontSize: '18px'
        });
    };
    title.onmouseout = function() {
        anime.remove("#mainBarTitle");
        anime({
            targets: "#mainBarTitle",
            fontSize: '16px'
        });
    };
    projects.onmouseenter = function() {
        anime.remove("#mainBarProjects");
        anime({
            targets: "#mainBarProjects",
            fontSize: '18px'
        });
    };
    projects.onmouseout = function() {
        anime.remove("#mainBarProjects");
        anime({
            targets: "#mainBarProjects",
            fontSize: '16px'
        });
    };
    about.onmouseenter = function() {
        anime.remove("#mainBarAbout");
        anime({
            targets: "#mainBarAbout",
            fontSize: '18px'
        });
    };
    about.onmouseout = function() {
        anime.remove("#mainBarAbout");
        anime({
            targets: "#mainBarAbout",
            fontSize: '16px'
        });
    };
};
<|endoftext|>


<commit_before>var myChart = echarts.init(document.getElementById('main'));

        // Specify configurations and data graphs
myChart.showLoading({text:'iUsed努力加载数据中...'});

$.get('https://s3-us-west-2.amazonaws.com/s.cdpn.io/95368/USA_geo.json', function (usaJson) {
    myChart.hideLoading();

    echarts.registerMap('USA', usaJson, {
        Alaska: {              // 把阿拉斯加移到美国主大陆左下方
            left: -131,
            top: 25,
            width: 15
        },
        Hawaii: {
            left: -110,        // 夏威夷
            top: 28,
            width: 5
        },
        'Puerto Rico': {       // 波多黎各
            left: -76,
            top: 26,
            width: 2
        }
    });
    option = {
        title: {
            text: 'Unique Visitors On iUsed.org(Feb.2017)',
            subtext: 'Data from api.iused.org',
            sublink: 'http://api.iused.org',
            left: 'right'
        },
        tooltip: {
            trigger: 'item',
            showDelay: 0,
            transitionDuration: 0.2,
            formatter: function (params) {
                var value = (params.value + '').split('.');
                value = value[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,');
                return params.seriesName + '
' + params.name + ': ' + value+'人访问';
            }
        },
        visualMap: {
            left: 'right',
            min: 0,
            max: 500,
            inRange: {
                color: ['#424242', '#616161', '#757575', '#9E9E9E', '#E0E0E0', '#EEEEEE', '#DCEDC8', '#C5E1A5', '#AED581', '#9CCC65','#8BC34A']
            },
            text:['Opening','Wait to start'],           // 文本，默认为数值文本
            calculable: true
        },
        toolbox: {
            show: true,
            //orient: 'vertical',
            left: 'left',
            top: 'top',
            feature: {
                dataView: {readOnly: true},
                restore: {show:false},
                saveAsImage: {}
            }
        },
        series: [
            {
                name: '初始数据统计中...',
                type: 'map',
                roam: true,
                map: 'USA',
                itemStyle:{
                    emphasis:{label:{show:true}}
                },
                // 文本位置修正
                textFixed: {
                    Alaska: [20, -20]
                },
                data:[
                    {name: 'Alabama', value: 0,provinceurl:"http://al.iused.org"},
                    {name: 'Alaska', value: 0,provinceurl:"http://ak.iused.org"},
                    {name: 'Arizona', value: 400,provinceurl:"http://az.iused.org"},
                    {name: 'Arkansas', value: 0,provinceurl:"http://ar.iused.org"},
                    {name: 'California', value: 0,provinceurl:"http://ca.iused.org"},
                    {name: 'Colorado', value: 0,provinceurl:"http://co.iused.org"},
                    {name: 'Connecticut', value: 0,provinceurl:"http://ct.iused.org"},
                    {name: 'Delaware', value: 0,provinceurl:"http://de.iused.org"},
                    {name: 'District of Columbia', value: 0,provinceurl:"http://dc.iused.org"},
                    {name: 'Florida', value: 400,provinceurl:"http://fl.iused.org"},
                    {name: 'Georgia', value: 0,provinceurl:"http://ga.iused.org"},
                    {name: 'Hawaii', value: 0,provinceurl:"http://hi.iused.org"},
                    {name: 'Idaho', value: 0,provinceurl:"http://id.iused.org"},
                    {name: 'Illinois', value: 0,provinceurl:"http://il.iused.org"},
                    {name: 'Indiana', value: 0,provinceurl:"http://in.iused.org"},
                    {name: 'Iowa', value: 500,provinceurl:"http://ia.iused.org"},
                    {name: 'Kansas', value: 500,provinceurl:"http://ks.iused.org"},
                    {name: 'Kentucky', value: 0,provinceurl:"http://ky.iused.org"},
                    {name: 'Louisiana', value: 0,provinceurl:"http://la.iused.org"},
                    {name: 'Maine', value: 0,provinceurl:"http://me.iused.org"},
                    {name: 'Maryland', value: 0,provinceurl:"http://md.iused.org"},
                    {name: 'Massachusetts', value: 0,provinceurl:"http://ma.iused.org"},
                    {name: 'Michigan', value: 400,provinceurl:"http://mi.iused.org"},
                    {name: 'Minnesota', value: 0,provinceurl:"http://mn.iused.org"},
                    {name: 'Mississippi', value: 0,provinceurl:"http://ms.iused.org"},
                    {name: 'Missouri', value: 500,provinceurl:"http://mo.iused.org"},
                    {name: 'Montana', value: 0,provinceurl:"http://mt.iused.org"},
                    {name: 'Nebraska', value: 0,provinceurl:"http://ne.iused.org"},
                    {name: 'Nevada', value: 0,provinceurl:"http://nv.iused.org"},
                    {name: 'New Hampshire', value: 0,provinceurl:"http://nh.iused.org"},
                    {name: 'New Jersey', value: 0,provinceurl:"http://nj.iused.org"},
                    {name: 'New Mexico', value: 0,provinceurl:"http://nm.iused.org"},
                    {name: 'New York', value: 0,provinceurl:"http://ny.iused.org"},
                    {name: 'North Carolina', value: 0,provinceurl:"http://nc.iused.org"},
                    {name: 'North Dakota', value: 0,provinceurl:"http://nd.iused.org"},
                    {name: 'Ohio', value: 400,provinceurl:"http://oh.iused.org"},
                    {name: 'Oklahoma', value: 500,provinceurl:"http://ok.iused.org"},
                    {name: 'Oregon', value: 400,provinceurl:"http://or.iused.org"},
                    {name: 'Pennsylvania', value: 400,provinceurl:"http://pa.iused.org"},
                    {name: 'Rhode Island', value: 0,provinceurl:"http://ri.iused.org"},
                    {name: 'South Carolina', value: 0,provinceurl:"http://sc.iused.org"},
                    {name: 'South Dakota', value: 0,provinceurl:"http://sd.iused.org"},
                    {name: 'Tennessee', value: 0,provinceurl:"http://tn.iused.org"},
                    {name: 'Texas', value: 0,provinceurl:"http://tx.iused.org"},
                    {name: 'Utah', value: 0,provinceurl:"http://ut.iused.org"},
                    {name: 'Vermont', value: 0,provinceurl:"http://vt.iused.org"},
                    {name: 'Virginia', value: 0,provinceurl:"http://va.iused.org"},
                    {name: 'Washington', value: 0,provinceurl:"http://wa.iused.org"},
                    {name: 'West Virginia', value: 0,provinceurl:"http://wv.iused.org"},
                    {name: 'Wisconsin', value: 0,provinceurl:"http://wi.iused.org"},
                    {name: 'Wyoming', value: 0,provinceurl:"http://wy.iused.org"},
                    {name: 'Puerto Rico', value: 0,provinceurl:"http://pr.iused.org"}
                ]
            }
        ]
    };

    myChart.setOption(option);
});
onresize = myChart.resize;
    myChart.on('click', function (params) {window.open(params.data.provinceurl);
});
<commit_msg>Update index.js<commit_after>var myChart = echarts.init(document.getElementById('main'));

        // Specify configurations and data graphs
myChart.showLoading({text:'iUsed正努力加载数据中...'});

$.get('https://s3-us-west-2.amazonaws.com/s.cdpn.io/95368/USA_geo.json', function (usaJson) {
    myChart.hideLoading();

    echarts.registerMap('USA', usaJson, {
        Alaska: {              // 把阿拉斯加移到美国主大陆左下方
            left: -131,
            top: 25,
            width: 15
        },
        Hawaii: {
            left: -110,        // 夏威夷
            top: 28,
            width: 5
        },
        'Puerto Rico': {       // 波多黎各
            left: -76,
            top: 26,
            width: 2
        }
    });
    option = {
        title: {
            text: 'Unique Visitors On iUsed.org(Feb.2017)',
            subtext: 'Data from api.iused.org',
            sublink: 'http://api.iused.org',
            left: 'right'
        },
        tooltip: {
            trigger: 'item',
            showDelay: 0,
            transitionDuration: 0.2,
            formatter: function (params) {
                var value = (params.value + '').split('.');
                value = value[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,');
                return params.seriesName + '
' + params.name + ': ' + value+'人访问';
            }
        },
        visualMap: {
            left: 'right',
            min: 0,
            max: 500,
            inRange: {
                color: ['#455A64', '#546E7A', '#607D8B', '#78909C', '#90A4AE', '#B0BEC5', '#DCEDC8', '#C5E1A5', '#AED581', '#9CCC65','#8BC34A']
            },
            text:['Opening','Wait to start'],           // 文本，默认为数值文本
            calculable: true
        },
        toolbox: {
            show: true,
            //orient: 'vertical',
            left: 'left',
            top: 'top',
            feature: {
                dataView: {readOnly: true},
                restore: {show:false},
                saveAsImage: {}
            }
        },
        series: [
            {
                name: '初始数据统计中...',
                type: 'map',
                roam: true,
                map: 'USA',
                itemStyle:{
                    emphasis:{label:{show:true}}
                },
                // 文本位置修正
                textFixed: {
                    Alaska: [20, -20]
                },
                data:[
                    {name: 'Alabama', value: 0,provinceurl:"http://al.iused.org"},
                    {name: 'Alaska', value: 0,provinceurl:"http://ak.iused.org"},
                    {name: 'Arizona', value: 400,provinceurl:"http://az.iused.org"},
                    {name: 'Arkansas', value: 0,provinceurl:"http://ar.iused.org"},
                    {name: 'California', value: 0,provinceurl:"http://ca.iused.org"},
                    {name: 'Colorado', value: 0,provinceurl:"http://co.iused.org"},
                    {name: 'Connecticut', value: 0,provinceurl:"http://ct.iused.org"},
                    {name: 'Delaware', value: 0,provinceurl:"http://de.iused.org"},
                    {name: 'District of Columbia', value: 0,provinceurl:"http://dc.iused.org"},
                    {name: 'Florida', value: 400,provinceurl:"http://fl.iused.org"},
                    {name: 'Georgia', value: 0,provinceurl:"http://ga.iused.org"},
                    {name: 'Hawaii', value: 0,provinceurl:"http://hi.iused.org"},
                    {name: 'Idaho', value: 0,provinceurl:"http://id.iused.org"},
                    {name: 'Illinois', value: 0,provinceurl:"http://il.iused.org"},
                    {name: 'Indiana', value: 0,provinceurl:"http://in.iused.org"},
                    {name: 'Iowa', value: 500,provinceurl:"http://ia.iused.org"},
                    {name: 'Kansas', value: 500,provinceurl:"http://ks.iused.org"},
                    {name: 'Kentucky', value: 0,provinceurl:"http://ky.iused.org"},
                    {name: 'Louisiana', value: 0,provinceurl:"http://la.iused.org"},
                    {name: 'Maine', value: 0,provinceurl:"http://me.iused.org"},
                    {name: 'Maryland', value: 0,provinceurl:"http://md.iused.org"},
                    {name: 'Massachusetts', value: 0,provinceurl:"http://ma.iused.org"},
                    {name: 'Michigan', value: 400,provinceurl:"http://mi.iused.org"},
                    {name: 'Minnesota', value: 0,provinceurl:"http://mn.iused.org"},
                    {name: 'Mississippi', value: 0,provinceurl:"http://ms.iused.org"},
                    {name: 'Missouri', value: 500,provinceurl:"http://mo.iused.org"},
                    {name: 'Montana', value: 0,provinceurl:"http://mt.iused.org"},
                    {name: 'Nebraska', value: 0,provinceurl:"http://ne.iused.org"},
                    {name: 'Nevada', value: 0,provinceurl:"http://nv.iused.org"},
                    {name: 'New Hampshire', value: 0,provinceurl:"http://nh.iused.org"},
                    {name: 'New Jersey', value: 0,provinceurl:"http://nj.iused.org"},
                    {name: 'New Mexico', value: 0,provinceurl:"http://nm.iused.org"},
                    {name: 'New York', value: 0,provinceurl:"http://ny.iused.org"},
                    {name: 'North Carolina', value: 0,provinceurl:"http://nc.iused.org"},
                    {name: 'North Dakota', value: 0,provinceurl:"http://nd.iused.org"},
                    {name: 'Ohio', value: 400,provinceurl:"http://oh.iused.org"},
                    {name: 'Oklahoma', value: 500,provinceurl:"http://ok.iused.org"},
                    {name: 'Oregon', value: 400,provinceurl:"http://or.iused.org"},
                    {name: 'Pennsylvania', value: 400,provinceurl:"http://pa.iused.org"},
                    {name: 'Rhode Island', value: 0,provinceurl:"http://ri.iused.org"},
                    {name: 'South Carolina', value: 0,provinceurl:"http://sc.iused.org"},
                    {name: 'South Dakota', value: 0,provinceurl:"http://sd.iused.org"},
                    {name: 'Tennessee', value: 0,provinceurl:"http://tn.iused.org"},
                    {name: 'Texas', value: 0,provinceurl:"http://tx.iused.org"},
                    {name: 'Utah', value: 0,provinceurl:"http://ut.iused.org"},
                    {name: 'Vermont', value: 0,provinceurl:"http://vt.iused.org"},
                    {name: 'Virginia', value: 0,provinceurl:"http://va.iused.org"},
                    {name: 'Washington', value: 0,provinceurl:"http://wa.iused.org"},
                    {name: 'West Virginia', value: 0,provinceurl:"http://wv.iused.org"},
                    {name: 'Wisconsin', value: 0,provinceurl:"http://wi.iused.org"},
                    {name: 'Wyoming', value: 0,provinceurl:"http://wy.iused.org"},
                    {name: 'Puerto Rico', value: 0,provinceurl:"http://pr.iused.org"}
                ]
            }
        ]
    };

    myChart.setOption(option);
});
onresize = myChart.resize;
    myChart.on('click', function (params) {window.open(params.data.provinceurl);
});
<|endoftext|>


<commit_before>// Defines the top-level API for the igv module

import {createBrowser, removeBrowser, removeAllBrowsers, visibilityChange} from './igv-create.js';
import oauth from './oauth.js';
import igvxhr from "./igvxhr.js";
import embedCss from "./embedCss.js";
import version from "./version.js"
const xhr = igvxhr;
const setApiKey = igvxhr.setApiKey;

embedCss();

function setGoogleOauthToken(accessToken) {
    return oauth.setToken(accessToken);
}

export default {
    createBrowser,
    removeBrowser,
    removeAllBrowsers,
    visibilityChange,
    setGoogleOauthToken,
    oauth,
    version,
    xhr,
    setApiKey,
}

<commit_msg>export MenuUtils<commit_after>// Defines the top-level API for the igv module

import MenuUtils from "./ui/menuUtils.js";
import {createBrowser, removeBrowser, removeAllBrowsers, visibilityChange} from './igv-create.js';
import oauth from './oauth.js';
import igvxhr from "./igvxhr.js";
import embedCss from "./embedCss.js";
import version from "./version.js"
const xhr = igvxhr;
const setApiKey = igvxhr.setApiKey;

embedCss();

function setGoogleOauthToken(accessToken) {
    return oauth.setToken(accessToken);
}

export default {
    MenuUtils,
    createBrowser,
    removeBrowser,
    removeAllBrowsers,
    visibilityChange,
    setGoogleOauthToken,
    oauth,
    version,
    xhr,
    setApiKey,
}

<|endoftext|>


<commit_before>var camera, scene, renderer, controls, ground, player;

var BULLET_RADIUS = 1;
var START_POSITION_Z = -500;
var bulletList = [];
var collisionPoints = [];

function init() {
  var plane, light, groundTexture, groundMaterial;

	scene = new THREE.Scene();

  // Fog( hex, near, far )
  scene.fog = new THREE.Fog( 0xcce0ff, 100, 1000 );

  // add lighting
  scene.add( new THREE.AmbientLight( 0x666666 ) );
  light = new THREE.PointLight( 0xaaddaa, .5 );
  light.position.set( 50, 1200, -500 );
  scene.add( light );

  // add ground
  groundTexture = THREE.ImageUtils.loadTexture( "textures/Moon.png" );
  groundTexture.anisotropy = 16;

  groundMaterial = new THREE.MeshPhongMaterial({
    color: 0xffffff,
    specular: 0x111111,
    map: groundTexture
  });

	ground = new THREE.Mesh( new THREE.PlaneBufferGeometry( 1000, 1000 ),
      groundMaterial );

	ground.rotation.x = -Math.PI / 2;
  ground.receiveShadow = true;
  scene.add( ground );

  // add center around which player will rotate
  var geometry = new THREE.SphereGeometry(.2, 5, 5);
  var material = new THREE.MeshBasicMaterial({ color: 0xaff00 });
  playerCenter = new THREE.Mesh( geometry, material );

  playerCenter.position.set( 0, 20, 0 );

  scene.add( playerCenter );

  // add player obj
  // PlaneGeometry(width, height, widthSegments, heightSegments)
  var geometry = new THREE.PlaneGeometry( 10, 20, 32 );
  var material = new THREE.MeshBasicMaterial({
    color: 0xffff00,
    transparent: true,
    opacity: 0.25,
    side: THREE.DoubleSide
  });

  player = new THREE.Mesh( geometry, material );
  player.position.set( 0, 0, 5 );
  playerCenter.add( player );

  // add player base
  geometry = new THREE.PlaneGeometry( 10, 10, 32 );
  material = new THREE.MeshBasicMaterial({
    color: 0x9999ff,
    transparent: true,
    opacity: 0.5,
    side: THREE.DoubleSide
  });

  var playerPos = new THREE.Mesh( geometry, material );

  // rotate to be parralel with ground
  playerPos.rotation.x = -Math.PI / 2;
  playerPos.position.set(0, 10, 0);

  scene.add( playerPos );

  // add camera
  camera = new THREE.PerspectiveCamera( 45, window.innerWidth /
      window.innerHeight, 1, 1000 );

  camera.position.set( 0, 0, 35 );

  // attach camera to player object
  playerCenter.add( camera );

  // add controls
  controls = new THREE.DeviceOrientationControls( playerCenter );

  // add renderer
  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  makeBullets(12);
  startBullets();
  animate();
}

function makeBullets (numToMake) {
  var geometry = new THREE.SphereGeometry(BULLET_RADIUS, 5, 5);

  var material = new THREE.MeshBasicMaterial({
    color: 0xaff00,
    wireframe: true,
    wireframeLinewidth: 2
  });

  var bullet = {};
  var matrix = new THREE.Matrix4();
  var direction = new THREE.Vector3( 0, 0, 1 );

  bullet = new THREE.Mesh( geometry, material );
  bullet.position.z = START_POSITION_Z;
  bullet.position.y = 25;

  matrix.extractRotation( bullet.matrix );
  direction = matrix.multiplyVector3( direction );

  for (var i = 0; i < numToMake; i++) {
    bullet = new THREE.Mesh( geometry, material );
    bullet.position.z = START_POSITION_Z;
    bullet.position.y = 25;

    // Raycaster( origin, direction, near, far )
    bullet.raycaster = new THREE.Raycaster( bullet.position, direction, 0,
        350 );

    scene.add( bullet );
    bulletList[i] = bullet;
  }
}

function startBullets () {
  var bulletIndex = 0;

  setInterval(function() {
    bullet = bulletList[bulletIndex];

    if (bulletIndex < bulletList.length) {
      bulletIndex++;

    } else {
      bulletIndex = 0;
    }

    position = {
      x: bullet.position.x,
      y: bullet.position.y,
      z: bullet.position.z
    };

    target = {
      x: bullet.position.x + (Math.random() * 10 - 5),
      y: bullet.position.y + (Math.random() * 10 - 5),
      z: 50
    };

    doTween(position, target, bullet, TWEEN.Easing.Circular.Out, 2000);

  }, 1500);
}

function createIntersectionPoint (p) {
  // what is the min and max size for a collision point?
  // var collisionSize = (START_POSITION_Z - p.distance) / 100
  var geometry = new THREE.SphereGeometry(1, 5, 5);

  // determine how much green should be in color
  // the closer the bullet is to person the less green
  // max p.distance = 500
  var green = Math.floor(p.distance / 2);

  var color = parseInt("0xff" + green.toString(16) + "00", 16);

  var material = new THREE.MeshBasicMaterial({
    color: color,
    wireframe: true,
    wireframeLinewidth: 2
  });

  var point = new THREE.Mesh( geometry, material );

  point.position.set(p.point.x, p.point.y, p.point.z);

  collisionPoints.push(point);

  scene.add( point );
}

function checkForCollisions () {
  var intersection;

  // remove all collision points
  for (var i = 0; i < collisionPoints.length; i++) {
    scene.remove(collisionPoints[i]);
  }

  // empty points array -- might be more efficient way
  collisionPoints = [];

  for (var i = 0; i < bulletList.length; i++) {
    // check for collision
    intersection = bulletList[i].raycaster.intersectObject(player);

    if (intersection.length) {

      if (intersection[0].distance > 5) {
        createIntersectionPoint(intersection[0]);

      } else {
        // player was hit - reduce green or increase transparency
        if (player.material.color.g < 0.1) {
          playerCenter.remove( player );

        } else {
          player.material.color.g = player.material.color.g / 1.2;
        }
      }
    }
  }
}

function doTween (position, target, obj, easing, time) {
  var startPosition = {
    x: position.x,
    y: position.y,
    z: position.z
  }
  var tween = new TWEEN.Tween(position)
      .to(target, time)
      .onComplete(function() {

        // if bullet and not at start position z
        if (obj.type === "Mesh" && obj.position.z !== START_POSITION_Z) {
          obj.position.z = START_POSITION_Z;
        }
      });

  tween.onUpdate(function() {
    obj.position.x = position.x;
    obj.position.y = position.y;
    obj.position.z = position.z;
  });

  tween.easing(easing);

  tween.start();
}

function animate() {

  checkForCollisions();

  requestAnimationFrame( animate );

  controls.update();

  TWEEN.update();

  renderer.render( scene, camera );

}
init();
<commit_msg>collision warning grows as collision gets closer<commit_after>var camera, scene, renderer, controls, ground, player;

var BULLET_RADIUS = 1;
var START_POSITION_Z = -500;
var bulletList = [];
var collisionPoints = [];

function init() {
  var plane, light, groundTexture, groundMaterial;

	scene = new THREE.Scene();

  // Fog( hex, near, far )
  scene.fog = new THREE.Fog( 0xcce0ff, 100, 1000 );

  // add lighting
  scene.add( new THREE.AmbientLight( 0x666666 ) );
  light = new THREE.PointLight( 0xaaddaa, .5 );
  light.position.set( 50, 1200, -500 );
  scene.add( light );

  // add ground
  groundTexture = THREE.ImageUtils.loadTexture( "textures/Moon.png" );
  groundTexture.anisotropy = 16;

  groundMaterial = new THREE.MeshPhongMaterial({
    color: 0xffffff,
    specular: 0x111111,
    map: groundTexture
  });

	ground = new THREE.Mesh( new THREE.PlaneBufferGeometry( 1000, 1000 ),
      groundMaterial );

	ground.rotation.x = -Math.PI / 2;
  ground.receiveShadow = true;
  scene.add( ground );

  // add center around which player will rotate
  var geometry = new THREE.SphereGeometry(.2, 5, 5);
  var material = new THREE.MeshBasicMaterial({ color: 0xaff00 });
  playerCenter = new THREE.Mesh( geometry, material );

  playerCenter.position.set( 0, 20, 0 );

  scene.add( playerCenter );

  // add player obj
  // PlaneGeometry(width, height, widthSegments, heightSegments)
  var geometry = new THREE.PlaneGeometry( 10, 20, 32 );
  var material = new THREE.MeshBasicMaterial({
    color: 0xffff00,
    transparent: true,
    opacity: 0.25,
    side: THREE.DoubleSide
  });

  player = new THREE.Mesh( geometry, material );
  player.position.set( 0, 0, 5 );
  playerCenter.add( player );

  // add player base
  geometry = new THREE.PlaneGeometry( 10, 10, 32 );
  material = new THREE.MeshBasicMaterial({
    color: 0x9999ff,
    transparent: true,
    opacity: 0.5,
    side: THREE.DoubleSide
  });

  var playerPos = new THREE.Mesh( geometry, material );

  // rotate to be parralel with ground
  playerPos.rotation.x = -Math.PI / 2;
  playerPos.position.set(0, 10, 0);

  scene.add( playerPos );

  // add camera
  camera = new THREE.PerspectiveCamera( 45, window.innerWidth /
      window.innerHeight, 1, 1000 );

  camera.position.set( 0, 0, 35 );

  // attach camera to player object
  playerCenter.add( camera );

  // add controls
  controls = new THREE.DeviceOrientationControls( playerCenter );

  // add renderer
  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  makeBullets(12);
  startBullets();
  animate();
}

function makeBullets (numToMake) {
  var geometry = new THREE.SphereGeometry(BULLET_RADIUS, 5, 5);

  var material = new THREE.MeshBasicMaterial({
    color: 0xaff00,
    wireframe: true,
    wireframeLinewidth: 2
  });

  var bullet = {};
  var matrix = new THREE.Matrix4();
  var direction = new THREE.Vector3( 0, 0, 1 );

  bullet = new THREE.Mesh( geometry, material );
  bullet.position.z = START_POSITION_Z;
  bullet.position.y = 25;

  matrix.extractRotation( bullet.matrix );
  direction = matrix.multiplyVector3( direction );

  for (var i = 0; i < numToMake; i++) {
    bullet = new THREE.Mesh( geometry, material );
    bullet.position.z = START_POSITION_Z;
    bullet.position.y = 25;

    // Raycaster( origin, direction, near, far )
    bullet.raycaster = new THREE.Raycaster( bullet.position, direction, 0,
        350 );

    scene.add( bullet );
    bulletList[i] = bullet;
  }
}

function startBullets () {
  var bulletIndex = 0;

  setInterval(function() {
    bullet = bulletList[bulletIndex];

    if (bulletIndex < bulletList.length) {
      bulletIndex++;

    } else {
      bulletIndex = 0;
    }

    position = {
      x: bullet.position.x,
      y: bullet.position.y,
      z: bullet.position.z
    };

    target = {
      x: bullet.position.x + (Math.random() * 10 - 5),
      y: bullet.position.y + (Math.random() * 10 - 5),
      z: 50
    };

    doTween(position, target, bullet, TWEEN.Easing.Circular.Out, 2000);

  }, 1500);
}

function createIntersectionPoint (p) {
  var maxSize = 2,
    maxDis = Math.abs(START_POSITION_Z);

  // normalize distance to be between 0 and 1
  var collisionSize = (maxDis - p.distance) / maxDis;

  // collision point size 0 -> 2
  collisionSize *= maxSize;

  var geometry = new THREE.SphereGeometry(collisionSize, 5, 5);

  // determine how much green should be in color
  // the closer the bullet is to person the less green
  // max p.distance = 500
  var green = Math.floor(p.distance / 2);

  var color = parseInt("0xff" + green.toString(16) + "00", 16);

  var material = new THREE.MeshBasicMaterial({
    color: color,
    wireframe: true,
    wireframeLinewidth: 2
  });

  var point = new THREE.Mesh( geometry, material );

  point.position.set(p.point.x, p.point.y, p.point.z);

  collisionPoints.push(point);

  scene.add( point );
}

function checkForCollisions () {
  var intersection;

  // remove all collision points
  for (var i = 0; i < collisionPoints.length; i++) {
    scene.remove(collisionPoints[i]);
  }

  // empty points array -- might be more efficient way
  collisionPoints = [];

  for (var i = 0; i < bulletList.length; i++) {
    // check for collision
    intersection = bulletList[i].raycaster.intersectObject(player);

    if (intersection.length) {

      if (intersection[0].distance > 2) {
        createIntersectionPoint(intersection[0]);

      } else {

        // player was hit - reduce green or increase transparency
        if (player.material.color.g < 0.1) {
          playerCenter.remove( player );

        } else {
          player.material.color.g = player.material.color.g / 1.2;
        }
      }
    }
  }
}

function doTween (position, target, obj, easing, time) {
  var startPosition = {
    x: position.x,
    y: position.y,
    z: position.z
  }
  var tween = new TWEEN.Tween(position)
      .to(target, time)
      .onComplete(function() {

        // if bullet and not at start position z
        if (obj.type === "Mesh" && obj.position.z !== START_POSITION_Z) {
          obj.position.z = START_POSITION_Z;
        }
      });

  tween.onUpdate(function() {
    obj.position.x = position.x;
    obj.position.y = position.y;
    obj.position.z = position.z;
  });

  tween.easing(easing);

  tween.start();
}

function animate() {

  checkForCollisions();

  requestAnimationFrame( animate );

  controls.update();

  TWEEN.update();

  renderer.render( scene, camera );

}
init();
<|endoftext|>


<commit_before>/**** Photo-Sphere-Viewer ****/
viewer = new PhotoSphereViewer({
  container: 'photosphere',
  panorama: 'https://raw.githubusercontent.com/topherbuckley/omnitone-PSV/master/images/beach.png',
  navbar: [
    'zoom',
    'caption',
    'fullscreen'
  ],
  default_long: 0
});

/**** Omnitone Code ****/
// Set up an audio element to feed the ambisonic source audio feed.
var audioElement = document.createElement('audio');
audioElement.src = 'https://raw.githubusercontent.com/topherbuckley/omnitone-PSV/master/audio/AmbisonicSeasideFull.wav';
audioElement.loop = true;

// Create AudioContext, MediaElementSourceNode and FOARenderer.
var audioContext = new AudioContext();
var audioElementSource =
    audioContext.createMediaElementSource(audioElement);
var foaRenderer = Omnitone.createFOARenderer(audioContext, {
    HRIRUrl: 'https://raw.githubusercontent.com/topherbuckley/omnitone-PSV/master/HRTFs/sh_hrir_o_1.wav'
  });

// Make connection and start play.
foaRenderer.initialize().then(function () {
    audioElementSource.connect(foaRenderer.input);
    foaRenderer.output.connect(audioContext.destination);
    audioElement.play();
  });

viewer.on('ready', function() {
  var camera = viewer.camera;
  // Rotate the sound field by passing Three.js camera object. (4x4 matrix)
  foaRenderer.setRotationMatrixFromCamera(camera.matrix);
  // foaDecoder.setRotationMatrixFromCamera(camera.matrix);
});

viewer.on('render', function() {
  foaRenderer.setRotationMatrixFromCamera(viewer.camera.matrix)
});
<commit_msg>Fixing relative references again<commit_after>/**** Photo-Sphere-Viewer ****/
viewer = new PhotoSphereViewer({
  container: 'photosphere',
  panorama: 'https://github.com/topherbuckley/omnitone-PSV/blob/master/images/beach.png?raw=true',
  navbar: [
    'zoom',
    'caption',
    'fullscreen'
  ],
  default_long: 0
});

/**** Omnitone Code ****/
// Set up an audio element to feed the ambisonic source audio feed.
var audioElement = document.createElement('audio');
audioElement.src = 'https://github.com/topherbuckley/omnitone-PSV/blob/master/audio/AmbisonicSeasideFull.wav?raw=true';
audioElement.loop = true;

// Create AudioContext, MediaElementSourceNode and FOARenderer.
var audioContext = new AudioContext();
var audioElementSource =
    audioContext.createMediaElementSource(audioElement);
var foaRenderer = Omnitone.createFOARenderer(audioContext, {
    HRIRUrl: 'https://github.com/topherbuckley/omnitone-PSV/blob/master/HRTFs/sh_hrir_o_1.wav?raw=true'
  });

// Make connection and start play.
foaRenderer.initialize().then(function () {
    audioElementSource.connect(foaRenderer.input);
    foaRenderer.output.connect(audioContext.destination);
    audioElement.play();
  });

viewer.on('ready', function() {
  var camera = viewer.camera;
  // Rotate the sound field by passing Three.js camera object. (4x4 matrix)
  foaRenderer.setRotationMatrixFromCamera(camera.matrix);
  // foaDecoder.setRotationMatrixFromCamera(camera.matrix);
});

viewer.on('render', function() {
  foaRenderer.setRotationMatrixFromCamera(viewer.camera.matrix)
});
<|endoftext|>


<commit_before>var posts = [];
var post_index = 0;
var post_count = 0;
var map;  // Google map object (global variable)

var lat;
var lng;

function left_card() {
  post_index = (post_index + post_count - 1) % post_count;
  retrieve_comments();
  retrieve_map();
}

function right_card() {
  post_index = (post_index + post_count + 1) % post_count;
  if(post_index == post_count - 3) {
    retrieve_posts();
  }
  retrieve_comments();
  retrieve_map();
}

function retrieve_map() {
  $.get("http://bounce9833.azurewebsites.net/api/post_bounces", {post_id: posts[post_index]._id}, function(bounces) {
    console.log(bounces);
    console.log(bounces[0]);
    console.log(bounces[0].loc);
    // Create a Google coordinate object for where to center the map
    var latlngCenter = new google.maps.LatLng({lng: bounces[0].loc[0], lat: bounces[0].loc[1]} ); // Coordinates of Washington, DC (area centroid)

    // Map options for how to display the Google map
    var mapOptions = { zoom: 12, center: latlngCenter  };

    // Show the Google map in the div with the attribute id 'map-canvas'.
    map = new google.maps.Map(document.getElementById(posts[post_index]._id + 'right'), mapOptions);

    for(var i = 0; i < bounces.length; i++) {
      var latlng = {lat: bounces[i].loc[1], lng: bounces[i].loc[0]};
      var marker = new google.maps.Marker({
        position: latlng,
        map: map,
      });
    }
  });
}

function retrieve_comments() {
  $.get("http://bounce9833.azurewebsites.net/api/comment", {post_id: posts[post_index]._id}, function(comments) {
    var commentString = "";
    for (var i=0; i<comments.length; i++) {
      commentString += '
' + comments[i].text + '
';
    }
    commentString += "
<input type='text' id='" + posts[post_index]._id + "comment' placeholder='Comment'></input> Send";
    $('#' + posts[post_index]._id + 'left').html(commentString);
    return comments;
  });
}

function retrieve_posts() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseFloat(geoloc.coords.latitude);
    var lng = parseFloat(geoloc.coords.longitude);
    $.get("http://bounce9833.azurewebsites.net/api/post", {lat: lat, lng: lng, offset: post_count}, function(new_posts) {
      posts = posts.concat(new_posts);
      post_count = posts.length;
      if (posts.length == 0) {
        $("#card-view").append("

No Posts

");
      } else {
        for(var i = 0; i < new_posts.length; i++) {
          if (i == 0) {
            $("#card-view").append("
" +
                                 "
" +
                                  "
" +
                                    "
" + new_posts[i].text + "
" +
                                    "
Left
" +
                                  "
" +
                                  "
Right
" +
                                "
" +
                              "
");
          } else {
            $("#card-view").append("
" +
                                 "
" +
                                  "
" +
                                    "
" + new_posts[i].text + "
" +
                                    "
Left
" +
                                  "
" +
                                  "
Right
" +
                                "
" +
                              "
");
          }
        }
      }
    });
  });
  setTimeout(function() {
    retrieve_comments();
    retrieve_map();
  }, 5000);
}

function new_text_post() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseFloat(geoloc.coords.latitude);
    var lng = parseFloat(geoloc.coords.longitude);
    var text = document.getElementById('text').value;
    new_post(text, document.cookie, lat, lng);
  });
}

function new_post(text, uid, lat, lng) {
  $.post("http://bounce9833.azurewebsites.net/api/post", {text: text, user_id: uid, lat: lat, lng: lng}, function(message) {
    console.log(message);
  });
}

function add_comment() {
  var text = document.getElementById(posts[post_index]._id + 'comment').value;
  $.post("http://bounce9833.azurewebsites.net/api/comment", {post_id: posts[post_index]._id, user_id: document.cookie, text: text}, function(message) {
    console.log(message);
  })
  retrieve_comments();
}

function bounce() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseFloat(geoloc.coords.latitude);
    var lng = parseFloat(geoloc.coords.longitude);
    $.post("http://bounce9833.azurewebsites.net/api/bounce", {lat: lat, lng: lng, user_id: document.cookie, post_id: posts[post_index]._id}, function(message) {
      console.log(message);
    })
  });
}

function set_latlng() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    lat = geoloc.coords.latitude;
    lng = geoloc.coords.longitude;
  });

}

$(document).ready(function() {
  retrieve_posts();
})
<commit_msg>Loading message<commit_after>var posts = [];
var post_index = 0;
var post_count = 0;
var map;  // Google map object (global variable)

var lat;
var lng;

function left_card() {
  post_index = (post_index + post_count - 1) % post_count;
  retrieve_comments();
  retrieve_map();
}

function right_card() {
  post_index = (post_index + post_count + 1) % post_count;
  if(post_index == post_count - 3) {
    retrieve_posts();
  }
  retrieve_comments();
  retrieve_map();
}

function retrieve_map() {
  $.get("http://bounce9833.azurewebsites.net/api/post_bounces", {post_id: posts[post_index]._id}, function(bounces) {
    console.log(bounces);
    console.log(bounces[0]);
    console.log(bounces[0].loc);
    // Create a Google coordinate object for where to center the map
    var latlngCenter = new google.maps.LatLng({lng: bounces[0].loc[0], lat: bounces[0].loc[1]} ); // Coordinates of Washington, DC (area centroid)

    // Map options for how to display the Google map
    var mapOptions = { zoom: 12, center: latlngCenter  };

    // Show the Google map in the div with the attribute id 'map-canvas'.
    map = new google.maps.Map(document.getElementById(posts[post_index]._id + 'right'), mapOptions);

    for(var i = 0; i < bounces.length; i++) {
      var latlng = {lat: bounces[i].loc[1], lng: bounces[i].loc[0]};
      var marker = new google.maps.Marker({
        position: latlng,
        map: map,
      });
    }
  });
}

function retrieve_comments() {
  $.get("http://bounce9833.azurewebsites.net/api/comment", {post_id: posts[post_index]._id}, function(comments) {
    var commentString = "";
    for (var i=0; i<comments.length; i++) {
      commentString += '
' + comments[i].text + '
';
    }
    commentString += "
<input type='text' id='" + posts[post_index]._id + "comment' placeholder='Comment'></input> Send";
    $('#' + posts[post_index]._id + 'left').html(commentString);
    return comments;
  });
}

function retrieve_posts() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseFloat(geoloc.coords.latitude);
    var lng = parseFloat(geoloc.coords.longitude);
    $.get("http://bounce9833.azurewebsites.net/api/post", {lat: lat, lng: lng, offset: post_count}, function(new_posts) {
      posts = posts.concat(new_posts);
      post_count = posts.length;
      if (posts.length == 0) {
        $("#card-view").append("

No Posts

");
      } else {
        for(var i = 0; i < new_posts.length; i++) {
          if (i == 0) {
            $("#card-view").append("
" +
                                 "
" +
                                  "
" +
                                    "
" + new_posts[i].text + "
" +
                                    "
Loading..
" +
                                  "
" +
                                  "
Loading..
" +
                                "
" +
                              "
");
          } else {
            $("#card-view").append("
" +
                                 "
" +
                                  "
" +
                                    "
" + new_posts[i].text + "
" +
                                    "
Loading..
" +
                                  "
" +
                                  "
Loading..
" +
                                "
" +
                              "
");
          }
        }
      }
    });
  });
  setTimeout(function() {
    retrieve_comments();
    retrieve_map();
  }, 5000);
}

function new_text_post() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseFloat(geoloc.coords.latitude);
    var lng = parseFloat(geoloc.coords.longitude);
    var text = document.getElementById('text').value;
    new_post(text, document.cookie, lat, lng);
  });
}

function new_post(text, uid, lat, lng) {
  $.post("http://bounce9833.azurewebsites.net/api/post", {text: text, user_id: uid, lat: lat, lng: lng}, function(message) {
    console.log(message);
  });
}

function add_comment() {
  var text = document.getElementById(posts[post_index]._id + 'comment').value;
  $.post("http://bounce9833.azurewebsites.net/api/comment", {post_id: posts[post_index]._id, user_id: document.cookie, text: text}, function(message) {
    console.log(message);
  })
  retrieve_comments();
}

function bounce() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseFloat(geoloc.coords.latitude);
    var lng = parseFloat(geoloc.coords.longitude);
    $.post("http://bounce9833.azurewebsites.net/api/bounce", {lat: lat, lng: lng, user_id: document.cookie, post_id: posts[post_index]._id}, function(message) {
      console.log(message);
    })
  });
}

function set_latlng() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    lat = geoloc.coords.latitude;
    lng = geoloc.coords.longitude;
  });

}

$(document).ready(function() {
  retrieve_posts();
})
<|endoftext|>


<commit_before>/**
 * Application logic.
 *
 * @package themakermap
 */

(function($){
    /**
     * Configuration
     */
    var dataProvider = '1tteiG-HYAlsmh3ef5U-XVDEWu5QXqDxqWwDx-pc';

    /**
     * Storage objects
     */
    var makersLayer;
    var map, layer, infoWindow;

    /**
     * Window rendering handler.
     */
    function render () {
        var $map    = $('#map-wrapper');
        var calc    = $(window).height() - $map.position().top;

        $map.css('height', calc + 'px');
    }

    /**
     * Event handler for checkbox controls.
     *
     * @param {Object} Event
     *
     * @return {void}
     */
    function updateAnyCheckbox (e) {
        var $target = $(e.target);
        var $boxen  = $('#filter').find('input.classification-filter[type="checkbox"]').not('[value="any"]');
        var $any    = $('#filter').find('input.classification-filter[value="any"]');

        if ($target.val() == 'any') {
            // Update other checkboxes based on "any" state
            if ($any.is(':checked')) {
                $boxen.prop('checked', 'checked');
            } else {
                $boxen.removeAttr('checked');
            }
        } else {
            // Update "any" checkbox based on others' state
            if ($boxen.not(':checked').length) {
                $any.removeAttr('checked');
            } else {
                $any.prop('checked', 'checked');
            }
        }
    }

    /**
     * Google Maps
     */
    function initMaps () {
        map = new google.maps.Map(document.getElementById('map-canvas'), {
            center: new google.maps.LatLng(-37.8136, 144.9631),
            zoom: 9,
            disableDefaultUI: true,
            zoomControl: true,
    		zoomControlOptions: {
    			style: google.maps.ZoomControlStyle.LARGE,
    			position: google.maps.ControlPosition.TOP_RIGHT
    		},
            streetViewControl: true
        });

        var style = [
            {
                elementType: 'geometry',
                stylers: [
                    { saturation: -100 },
                    { weight: 0.4 }
                ]
            },
            {
                featureType: 'poi',
                stylers: [
                    { visibility: "off" }
                ]
            },
            {
                featureType: 'administrative.land_parcel',
                elementType: 'all',
                stylers: [
                    { visibility: 'off' }
                ]
            }
        ];

        var styledMapType = new google.maps.StyledMapType(style, {
            map: map,
            name: 'Styled Map'
        });

        map.mapTypes.set('map-style', styledMapType);
        map.setMapTypeId('map-style');

        infoWindow = new google.maps.InfoWindow({
            content: ""
        });
        loadData();

        if (navigator && navigator.geolocation) {
           locateMe();
        }
    }

		function locateMe () {
			navigator.geolocation.getCurrentPosition(function(position) {
	      var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	      map.setCenter(latlng);
	      map.setZoom(12);

				$('.locateMe').fadeIn(1000,function(){
					$(this).tooltip('show');
				}).css("display",'table');

	    });

			$('.locateMe').click(function(){
				locateMe();
			});

		}

    /**
     * UI events
     */
    function initEventListeners () {
        // Selectors
        var $searchNav  = $('#search-nav');
        var $addContentNav = $('#add-content-nav');
        var $aboutNav = $('#about-nav');
        var $window = $(window);
        var $nav    = $('#topnav a');
        var $search = $('#search');
        var $filter = $('#filter');

        // Resize handler
        $window.resize(render);

        // Top nav
        $.hovertips($nav, {
            delay_hide:     0,
            delay_hover:    0,
            delay_leave:    0,
            render: function($el, data, loading) {
                var $tooltip;
                var self = this;
                $tooltip = $('
');
                $tooltip.addClass('nav-tooltip')
                $tooltip.html($el.find('img').attr('alt'));
                $el.on('click', function() {
                    self.hide(0);
                });
                return $tooltip;
            }
        });

        $addContentNav.click(function () {
            $('.searchMenu').hide();
            $('.aboutMenu').hide();
            $('.addContentMenu').show();
            console.log('content');
        });

        $aboutNav.click(function () {
            $('.searchMenu').hide();
            $('.addContentMenu').hide();
            $('.aboutMenu').show();
            console.log('content');
        });

        $searchNav.click(function () {
            $('.searchMenu').show();
            $('.aboutMenu').hide();
            $('.addContentMenu').hide();
            console.log('search');
        });

        // Load classifications
        var classQry = new Parse.Query(MakerMap.Model.PrimaryClassification);
        classQry.find({
            success: function(resp) {
                for (var i = 0; i < resp.length; i++) {
                    var cls = resp[i];
                    $("ul.filters").append("
" + cls.get("friendlyName") + " <input type='checkbox' class='classification-filter' value='" + cls.id + "' />
");
                }

                // Filter
                $filter.find('input.classification-filter').click(function (e) {
                    updateAnyCheckbox(e);
                    loadData();
                });
            },
            failure: function(err) {
                alert("An error occurred loading primary classifications: " + err);
            }
        });

        // Search
        $search.submit(function () {
            return false;
        });

        $search.find('input').keyup(function () {
            loadData();
        });
    }

		function filterMenu() {
			$('.filterIcon').click(function(){
				$('.filterWrap').slideToggle();
			});
		}

		function mobileMenu() {
			$('.menuToggle').click(function(){
				$('.aboutWrap').slideToggle();
			});
		}

		function aboutModal() {
			var aboutContent = $('.aboutWrap').html();
			$('#aboutModal .modal-body').html(aboutContent);

			$('.about .searchAction').click(function(){
				$('#aboutModal').modal('hide');
				$('#searchForm').focus();
			});

    		}

    function initSocialite() {
        Socialite.load($('div.footer'));
    }

    function makerToFeature(mkr) {
        var coords = mkr.get("coordinates").toJSON();
        var obj = {
            id: mkr.id,
            geometry: {
                lng: coords.longitude,
                lat: coords.latitude
            },
            properties: {
                title: mkr.get("title"),
                description: mkr.get("description"),
                marker_color: mkr.get("marker_color"),
                marker_size: mkr.get("marker_size"),
                marker_symbol: mkr.get("marker_symbol")
            }
        };
        return new google.maps.Data.Feature(obj);
    }

    function getIcon(symbolName) {
        if (!symbolName || symbolName == "") {
            return null;
        }
        var relPart = "img/markers/" + symbolName + ".png";
        //HACK: Should be a better way to get the URL base of index.html
        if (window.location.pathname.indexOf("index.html") >= 0)
            return window.location.pathname.replace("index.html", relPart);
        else
            return relPart;
    }

    function loadData() {
        var query_array = [];
        var query = new Parse.Query(MakerMap.Model.Maker);

        // Detach the layer before replacing
        if (makersLayer) {
            makersLayer.setMap(null);
        }
        makersLayer = new google.maps.Data();
        makersLayer.setStyle(function(feature) {
            return {
                fillColor: feature.getProperty("marker_color"),
                clickable: true,
                title: feature.getProperty("title"),
                icon: getIcon(feature.getProperty("marker_symbol"))
            };
        });

        search_string = $('#search').find('input').val();
        if(search_string != "") {
            var title_query = new Parse.Query(MakerMap.Model.Maker);
            var description_query = new Parse.Query(MakerMap.Model.Maker);
            title_query.contains("title", search_string);
            description_query.contains("description", search_string);
            query = Parse.Query.or(title_query, description_query);
        }

        if($('#filter').find('input.classification-filter[value="any"]:checked').length == 0) {
            $('#filter').find('input.classification-filter[type="checkbox"]:checked').each(function () {
                query_array.push($(this).attr('value'));
            });
            var lookupQuery = new Parse.Query(MakerMap.Model.PrimaryClassification);
            lookupQuery.containedIn("objectId", query_array);
            query.matchesKeyInQuery("classification", "objectId", lookupQuery);
        }

        query.find({
            success: function(resp) {
                for (var i = 0; i < resp.length; i++) {
                    makersLayer.add(makerToFeature(resp[i]));
                }
                makersLayer.setMap(map);
                setupEventListeners();
            },
            failure: function(err) {
                alert("Error loading markers: " + err);
            }
        });
    }

    function setupEventListeners() {
        makersLayer.addListener('click', function(event) {
            infoWindow.setContent(
                '
'+event.feature.getProperty('title')+'
'+
                '
'+event.feature.getProperty('description')+'
'
            );
            var anchor = new google.maps.MVCObject();
            anchor.set("position",event.latLng);
            infoWindow.open(map,anchor);
        });
    };

    //Init the parse API
    Parse.initialize("wj2jWY2HA6L4C1qpWuZzsruUHkO8BZjIbtUI0hmr" /* App ID */, "3GNfJdTZKsLlRrqsH1n8vJtrgFCRwuCmfb33Y2JG" /* JS Key */);
    /**
     * On load, init maps & start listening for UI events
     */
    render();
    initMaps();
    initEventListeners();
		filterMenu();
		mobileMenu();
		aboutModal();
    initSocialite();

})(jQuery);
<commit_msg>fixed over-zelious about information<commit_after>/**
 * Application logic.
 *
 * @package themakermap
 */

(function($){
    /**
     * Configuration
     */
    var dataProvider = '1tteiG-HYAlsmh3ef5U-XVDEWu5QXqDxqWwDx-pc';

    /**
     * Storage objects
     */
    var makersLayer;
    var map, layer, infoWindow;

    /**
     * Window rendering handler.
     */
    function render () {
        var $map    = $('#map-wrapper');
        var calc    = $(window).height() - $map.position().top;

        $map.css('height', calc + 'px');
    }

    /**
     * Event handler for checkbox controls.
     *
     * @param {Object} Event
     *
     * @return {void}
     */
    function updateAnyCheckbox (e) {
        var $target = $(e.target);
        var $boxen  = $('#filter').find('input.classification-filter[type="checkbox"]').not('[value="any"]');
        var $any    = $('#filter').find('input.classification-filter[value="any"]');

        if ($target.val() == 'any') {
            // Update other checkboxes based on "any" state
            if ($any.is(':checked')) {
                $boxen.prop('checked', 'checked');
            } else {
                $boxen.removeAttr('checked');
            }
        } else {
            // Update "any" checkbox based on others' state
            if ($boxen.not(':checked').length) {
                $any.removeAttr('checked');
            } else {
                $any.prop('checked', 'checked');
            }
        }
    }

    /**
     * Google Maps
     */
    function initMaps () {
        map = new google.maps.Map(document.getElementById('map-canvas'), {
            center: new google.maps.LatLng(-37.8136, 144.9631),
            zoom: 9,
            disableDefaultUI: true,
            zoomControl: true,
    		zoomControlOptions: {
    			style: google.maps.ZoomControlStyle.LARGE,
    			position: google.maps.ControlPosition.TOP_RIGHT
    		},
            streetViewControl: true
        });

        var style = [
            {
                elementType: 'geometry',
                stylers: [
                    { saturation: -100 },
                    { weight: 0.4 }
                ]
            },
            {
                featureType: 'poi',
                stylers: [
                    { visibility: "off" }
                ]
            },
            {
                featureType: 'administrative.land_parcel',
                elementType: 'all',
                stylers: [
                    { visibility: 'off' }
                ]
            }
        ];

        var styledMapType = new google.maps.StyledMapType(style, {
            map: map,
            name: 'Styled Map'
        });

        map.mapTypes.set('map-style', styledMapType);
        map.setMapTypeId('map-style');

        infoWindow = new google.maps.InfoWindow({
            content: ""
        });
        loadData();

        if (navigator && navigator.geolocation) {
           locateMe();
        }
    }

		function locateMe () {
			navigator.geolocation.getCurrentPosition(function(position) {
	      var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	      map.setCenter(latlng);
	      map.setZoom(12);

				$('.locateMe').fadeIn(1000,function(){
					$(this).tooltip('show');
				}).css("display",'table');

	    });

			$('.locateMe').click(function(){
				locateMe();
			});

		}

    /**
     * UI events
     */
    function initEventListeners () {
        // Selectors
        var $searchNav  = $('#search-nav');
        var $addContentNav = $('#add-content-nav');
        var $aboutNav = $('#about-nav');
        var $window = $(window);
        var $nav    = $('#topnav a');
        var $search = $('#search');
        var $filter = $('#filter');

        // Resize handler
        $window.resize(render);

        // Top nav
        $.hovertips($nav, {
            delay_hide:     0,
            delay_hover:    0,
            delay_leave:    0,
            render: function($el, data, loading) {
                var $tooltip;
                var self = this;
                $tooltip = $('
');
                $tooltip.addClass('nav-tooltip')
                $tooltip.html($el.find('img').attr('alt'));
                $el.on('click', function() {
                    self.hide(0);
                });
                return $tooltip;
            }
        });

        $addContentNav.click(function () {
            $('.searchMenu').hide();
            $('.aboutMenu').hide();
            $('.addContentMenu').show();
            console.log('content');
        });

        $aboutNav.click(function () {
            $('.searchMenu').hide();
            $('.addContentMenu').hide();
            $('.aboutMenu').show();
            console.log('content');
        });

        $searchNav.click(function () {
            $('.searchMenu').show();
            $('.aboutMenu').hide();
            $('.addContentMenu').hide();
            console.log('search');
        });

        // Load classifications
        var classQry = new Parse.Query(MakerMap.Model.PrimaryClassification);
        classQry.find({
            success: function(resp) {
                for (var i = 0; i < resp.length; i++) {
                    var cls = resp[i];
                    $("ul.filters").append("
" + cls.get("friendlyName") + " <input type='checkbox' class='classification-filter' value='" + cls.id + "' />
");
                }

                // Filter
                $filter.find('input.classification-filter').click(function (e) {
                    updateAnyCheckbox(e);
                    loadData();
                });
            },
            failure: function(err) {
                alert("An error occurred loading primary classifications: " + err);
            }
        });

        // Search
        $search.submit(function () {
            return false;
        });

        $search.find('input').keyup(function () {
            loadData();
        });
    }

		function filterMenu() {
			$('.filterIcon').click(function(){
				$('.filterWrap').slideToggle();
			});
		}

		function mobileMenu() {
			$('.menuToggle').click(function(){
				$('.aboutWrap').slideToggle();
			});
		}

    function initSocialite() {
        Socialite.load($('div.footer'));
    }

    function makerToFeature(mkr) {
        var coords = mkr.get("coordinates").toJSON();
        var obj = {
            id: mkr.id,
            geometry: {
                lng: coords.longitude,
                lat: coords.latitude
            },
            properties: {
                title: mkr.get("title"),
                description: mkr.get("description"),
                marker_color: mkr.get("marker_color"),
                marker_size: mkr.get("marker_size"),
                marker_symbol: mkr.get("marker_symbol")
            }
        };
        return new google.maps.Data.Feature(obj);
    }

    function getIcon(symbolName) {
        if (!symbolName || symbolName == "") {
            return null;
        }
        var relPart = "img/markers/" + symbolName + ".png";
        //HACK: Should be a better way to get the URL base of index.html
        if (window.location.pathname.indexOf("index.html") >= 0)
            return window.location.pathname.replace("index.html", relPart);
        else
            return relPart;
    }

    function loadData() {
        var query_array = [];
        var query = new Parse.Query(MakerMap.Model.Maker);

        // Detach the layer before replacing
        if (makersLayer) {
            makersLayer.setMap(null);
        }
        makersLayer = new google.maps.Data();
        makersLayer.setStyle(function(feature) {
            return {
                fillColor: feature.getProperty("marker_color"),
                clickable: true,
                title: feature.getProperty("title"),
                icon: getIcon(feature.getProperty("marker_symbol"))
            };
        });

        search_string = $('#search').find('input').val();
        if(search_string != "") {
            var title_query = new Parse.Query(MakerMap.Model.Maker);
            var description_query = new Parse.Query(MakerMap.Model.Maker);
            title_query.contains("title", search_string);
            description_query.contains("description", search_string);
            query = Parse.Query.or(title_query, description_query);
        }

        if($('#filter').find('input.classification-filter[value="any"]:checked').length == 0) {
            $('#filter').find('input.classification-filter[type="checkbox"]:checked').each(function () {
                query_array.push($(this).attr('value'));
            });
            var lookupQuery = new Parse.Query(MakerMap.Model.PrimaryClassification);
            lookupQuery.containedIn("objectId", query_array);
            query.matchesKeyInQuery("classification", "objectId", lookupQuery);
        }

        query.find({
            success: function(resp) {
                for (var i = 0; i < resp.length; i++) {
                    makersLayer.add(makerToFeature(resp[i]));
                }
                makersLayer.setMap(map);
                setupEventListeners();
            },
            failure: function(err) {
                alert("Error loading markers: " + err);
            }
        });
    }

    function setupEventListeners() {
        makersLayer.addListener('click', function(event) {
            infoWindow.setContent(
                '
'+event.feature.getProperty('title')+'
'+
                '
'+event.feature.getProperty('description')+'
'
            );
            var anchor = new google.maps.MVCObject();
            anchor.set("position",event.latLng);
            infoWindow.open(map,anchor);
        });
    };

    //Init the parse API
    Parse.initialize("wj2jWY2HA6L4C1qpWuZzsruUHkO8BZjIbtUI0hmr" /* App ID */, "3GNfJdTZKsLlRrqsH1n8vJtrgFCRwuCmfb33Y2JG" /* JS Key */);
    /**
     * On load, init maps & start listening for UI events
     */
    render();
    initMaps();
    initEventListeners();
		filterMenu();
		mobileMenu();
	$('.aboutMenu').hide();
    initSocialite();

})(jQuery);
<|endoftext|>