<commit_before>/*jslint node: true es5: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */

var log = require("./logging.js").log;
var joynr = require("joynr");

var runInteractiveConsole = function(radioProvider, onDone) {
    var readline = require('readline');
    var rl = readline.createInterface(process.stdin, process.stdout);
    rl.setPrompt('>> ');
    var MODES = {
        HELP : {
            value : "h",
            description : "help",
            options : {}
        },
        MULTICAST : {
            value : "w",
            description : "multicast weak signal",
            options : {}
        },
        MULTICASTP : {
            value : "p",
            description : "multicast weak signal with country of current station as partition",
            options : {}
        },
        QUIT : {
            value : "q",
            description : "quit",
            options : {}
        },
        SHUFFLE : {
            value : "shuffle",
            description : "shuffle current station",
            options : {}
        }
    };

    var showHelp = require("./console_common.js");
    rl.on('line', function(line) {
        var input = line.trim().split(' ');
        switch (input[0]) {
            case MODES.HELP.value:
                showHelp(MODES);
                break;
            case MODES.QUIT.value:
                rl.close();
                break;
            case MODES.MULTICAST.value:
                radioProvider.fireWeakSignal();
                break;
            case MODES.MULTICASTP.value:
                radioProvider.fireWeakSignalWithPartition();
                break;
            case MODES.SHUFFLE.value:
                radioProvider.shuffleStations({});
                break;
            case '':
                break;
            default:
                log('unknown input: ' + input);
                break;
        }
        rl.prompt();
    });

    rl.on('close', function() {
        if (onDone) {
            onDone().then(function() {
                process.exit(0);
            }).catch(function(error) {
                console.log("error while shutting down: " + error);
                process.exit(1);
            });
        } else {
            process.exit(0);
        }
    });

    showHelp(MODES);
    rl.prompt();
};

if (process.env.domain === undefined) {
    log("please pass a domain as argument");
    process.exit(0);
}
var domain = process.env.domain;
log("domain: " + domain);

var provisioning = require("./provisioning_common.js");

provisioning.persistency = {
    //clearPersistency : true,
    location : "./radioLocalStorageProvider"
};

if (process.env.runtime !== undefined) {
    if (process.env.runtime === "inprocess") {
        provisioning.brokerUri = process.env.brokerUri;
        provisioning.bounceProxyBaseUrl = process.env.bounceProxyBaseUrl;
        provisioning.bounceProxyUrl = provisioning.bounceProxyBaseUrl + "/bounceproxy/";
        joynr.selectRuntime("inprocess");
    } else if (process.env.runtime === "websocket") {
        provisioning.ccAddress.host = process.env.cchost;
        provisioning.ccAddress.port = process.env.ccport;
        joynr.selectRuntime("websocket.libjoynr");
    }
}

var RadioProvider = require("../generated/js/joynr/vehicle/RadioProvider.js");
var MyRadioProvider = require("./MyRadioProvider.js");
joynr.load(provisioning).then(function(loadedJoynr) {
    log("joynr started");
    joynr = loadedJoynr;

    var providerQos = new joynr.types.ProviderQos({
        customParameters : [],
        priority : Date.now(),
        scope : joynr.types.ProviderScope.GLOBAL,
        supportsOnChangeSubscriptions : true
    });

    var radioProviderImpl = new MyRadioProvider();
    var radioProvider = joynr.providerBuilder.build(
        RadioProvider,
        radioProviderImpl);
    radioProviderImpl.setProvider(radioProvider);

    joynr.registration.registerProvider(domain, radioProvider, providerQos).then(function() {
        log("provider registered successfully");
        runInteractiveConsole(radioProviderImpl, function() {
            return joynr.registration.unregisterProvider(domain, radioProvider)
            .then(function() {
                joynr.shutdown();
            }).catch(function() {
                joynr.shutdown();
            });
        });
        return null;
    }).catch(function(error) {
        log("error registering provider: " + error.toString());
    });
    return loadedJoynr;
}).catch(function(error){
    throw error;
});
<commit_msg>[JS] radio-node uses awaitGlobalRegistration<commit_after>/*jslint node: true es5: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */

var log = require("./logging.js").log;
var joynr = require("joynr");

var runInteractiveConsole = function(radioProvider, onDone) {
    var readline = require('readline');
    var rl = readline.createInterface(process.stdin, process.stdout);
    rl.setPrompt('>> ');
    var MODES = {
        HELP : {
            value : "h",
            description : "help",
            options : {}
        },
        MULTICAST : {
            value : "w",
            description : "multicast weak signal",
            options : {}
        },
        MULTICASTP : {
            value : "p",
            description : "multicast weak signal with country of current station as partition",
            options : {}
        },
        QUIT : {
            value : "q",
            description : "quit",
            options : {}
        },
        SHUFFLE : {
            value : "shuffle",
            description : "shuffle current station",
            options : {}
        }
    };

    var showHelp = require("./console_common.js");
    rl.on('line', function(line) {
        var input = line.trim().split(' ');
        switch (input[0]) {
            case MODES.HELP.value:
                showHelp(MODES);
                break;
            case MODES.QUIT.value:
                rl.close();
                break;
            case MODES.MULTICAST.value:
                radioProvider.fireWeakSignal();
                break;
            case MODES.MULTICASTP.value:
                radioProvider.fireWeakSignalWithPartition();
                break;
            case MODES.SHUFFLE.value:
                radioProvider.shuffleStations({});
                break;
            case '':
                break;
            default:
                log('unknown input: ' + input);
                break;
        }
        rl.prompt();
    });

    rl.on('close', function() {
        if (onDone) {
            onDone().then(function() {
                process.exit(0);
            }).catch(function(error) {
                console.log("error while shutting down: " + error);
                process.exit(1);
            });
        } else {
            process.exit(0);
        }
    });

    showHelp(MODES);
    rl.prompt();
};

if (process.env.domain === undefined) {
    log("please pass a domain as argument");
    process.exit(0);
}
var domain = process.env.domain;
log("domain: " + domain);

var provisioning = require("./provisioning_common.js");

provisioning.persistency = {
    //clearPersistency : true,
    location : "./radioLocalStorageProvider"
};

if (process.env.runtime !== undefined) {
    if (process.env.runtime === "inprocess") {
        provisioning.brokerUri = process.env.brokerUri;
        provisioning.bounceProxyBaseUrl = process.env.bounceProxyBaseUrl;
        provisioning.bounceProxyUrl = provisioning.bounceProxyBaseUrl + "/bounceproxy/";
        joynr.selectRuntime("inprocess");
    } else if (process.env.runtime === "websocket") {
        provisioning.ccAddress.host = process.env.cchost;
        provisioning.ccAddress.port = process.env.ccport;
        joynr.selectRuntime("websocket.libjoynr");
    }
}

var RadioProvider = require("../generated/js/joynr/vehicle/RadioProvider.js");
var MyRadioProvider = require("./MyRadioProvider.js");
joynr.load(provisioning).then(function(loadedJoynr) {
    log("joynr started");
    joynr = loadedJoynr;

    var providerQos = new joynr.types.ProviderQos({
        customParameters : [],
        priority : Date.now(),
        scope : joynr.types.ProviderScope.GLOBAL,
        supportsOnChangeSubscriptions : true
    });

    var radioProviderImpl = new MyRadioProvider();
    var radioProvider = joynr.providerBuilder.build(
        RadioProvider,
        radioProviderImpl);
    radioProviderImpl.setProvider(radioProvider);

    var expiryDateMs; // intentionally left undefined by default
    var loggingContext; // intentionally left undefined by default
    var participantId; // intentionally left undefined by default
    var awaitGlobalRegistration = true;

    joynr.registration.registerProvider(domain, radioProvider, providerQos, expiryDateMs, loggingContext, participantId, awaitGlobalRegistration).then(function() {
        log("provider registered successfully");
        runInteractiveConsole(radioProviderImpl, function() {
            return joynr.registration.unregisterProvider(domain, radioProvider)
            .then(function() {
                joynr.shutdown();
            }).catch(function() {
                joynr.shutdown();
            });
        });
        return null;
    }).catch(function(error) {
        log("error registering provider: " + error.toString());
        joynr.shutdown();
    });
    return loadedJoynr;
}).catch(function(error){
    throw error;
});
<|endoftext|>


<commit_before>require(['jquery', 'uikit', 'uikit!autocomplete','domReady!'], function($, uikit) {

    var api = 'http://api.openweathermap.org/data/2.5', storage = sessionStorage || {};

    // widget init

    $('[data-weather]').each(function() {

        var widget = $(this), config = widget.data('weather');

        loadData(config).done(function(data) {

            widget.find('.js-spinner').addClass('uk-hidden');

            var unit = config.units == 'metric' ? ' °C' : ' °F',
                location = config.location.split(',');
            $('.js-weather-city', widget).html(location[0]);

            $('.js-weather-country', widget).html(location[1]);
            $('.js-weather-temperature', widget).html(Math.round(data.main.temp) + unit);
            $('.js-weather-icon', widget).attr('src', getIconUrl(data.weather[0].icon));

        }).fail(function() {
            widget.replaceWith(($('.js-error', widget)).removeClass('uk-hidden'));
        });

    });

    function loadData(config) {

        var key = 'weather-' + config.id, cache = storage[key];

        if (cache) {
            return $.Deferred().resolve(JSON.parse(cache)).promise();
        }

        return $.getJSON(api + '/weather?callback=?', { id: config.id, units: config.units }, function(data) {
            if (data.cod == 200) {
                storage[key] = JSON.stringify(data);
            }
        });
    }

    function getIconUrl(icon) {

        var icons = {

            '01d': 'sun.svg',
            '01n': 'moon.svg',
            '02d': 'cloud-sun.svg',
            '02n': 'cloud-moon.svg',
            '03d': 'cloud.svg',
            '03n': 'cloud.svg',
            '04d': 'cloud.svg',
            '04n': 'cloud.svg',
            '09d': 'drizzle-sun.svg',
            '09n': 'drizzle-moon.svg',
            '10d': 'rain-sun.svg',
            '10n': 'rain-moon.svg',
            '11d': 'lightning.svg',
            '11n': 'lightning.svg',
            '13d': 'snow.svg',
            '13n': 'snow.svg',
            '50d': 'fog.svg',
            '50n': 'fog.svg'

        };

        return require.toUrl('extensions/system/assets/images/weather-' + icons[icon]);
    }

    // widget settings

    var autocomplete = uikit.autocomplete($('#form-weather-location').parent(), {

        'source': function(release) {

            $.getJSON(api + '/find?callback=?', { q: this.input.val(), type: 'like' }, function(data) {
                if (data.cod == 200) {
                    release(data.list);
                } else {
                    release([]);
                }
            });
        },
        template: '
{{~items}}
{{$item.name}}
{{/items}}
'
    });

    autocomplete.element.on('autocomplete-select', function(e, data){
        autocomplete.input.next().val(data.id);
    });

});
<commit_msg>Added units to cache key in weather widget<commit_after>require(['jquery', 'uikit', 'uikit!autocomplete','domReady!'], function($, uikit) {

    var api = 'http://api.openweathermap.org/data/2.5', storage = sessionStorage || {};

    // widget init

    $('[data-weather]').each(function() {

        var widget = $(this), config = widget.data('weather');

        loadData(config).done(function(data) {

            var location = config.location.split(',');

            $('.js-weather-city', widget).html(location[0]);
            $('.js-weather-country', widget).html(location[1]);
            $('.js-weather-temperature', widget).html(Math.round(data.main.temp) + (config.units == 'metric' ? ' °C' : ' °F'));
            $('.js-weather-icon', widget).attr('src', getIconUrl(data.weather[0].icon));

            widget.find('.js-spinner').addClass('uk-hidden');

        }).fail(function() {
            widget.replaceWith(($('.js-error', widget)).removeClass('uk-hidden'));
        });

    });

    function loadData(config) {

        var key = 'weather-' + config.id + config.units[0], cache = storage[key];

        if (cache) {
            return $.Deferred().resolve(JSON.parse(cache)).promise();
        }

        return $.getJSON(api + '/weather?callback=?', { id: config.id, units: config.units }, function(data) {
            if (data.cod == 200) {
                storage[key] = JSON.stringify(data);
            }
        });
    }

    function getIconUrl(icon) {

        var icons = {

            '01d': 'sun.svg',
            '01n': 'moon.svg',
            '02d': 'cloud-sun.svg',
            '02n': 'cloud-moon.svg',
            '03d': 'cloud.svg',
            '03n': 'cloud.svg',
            '04d': 'cloud.svg',
            '04n': 'cloud.svg',
            '09d': 'drizzle-sun.svg',
            '09n': 'drizzle-moon.svg',
            '10d': 'rain-sun.svg',
            '10n': 'rain-moon.svg',
            '11d': 'lightning.svg',
            '11n': 'lightning.svg',
            '13d': 'snow.svg',
            '13n': 'snow.svg',
            '50d': 'fog.svg',
            '50n': 'fog.svg'

        };

        return require.toUrl('extensions/system/assets/images/weather-' + icons[icon]);
    }

    // widget settings

    var autocomplete = uikit.autocomplete($('#form-weather-location').parent(), {

        'source': function(release) {

            $.getJSON(api + '/find?callback=?', { q: this.input.val(), type: 'like' }, function(data) {
                if (data.cod == 200) {
                    release(data.list);
                } else {
                    release([]);
                }
            });
        },
        template: '
{{~items}}
{{$item.name}}
{{/items}}
'
    });

    autocomplete.element.on('autocomplete-select', function(e, data){
        autocomplete.input.next().val(data.id);
    });

});
<|endoftext|>


<commit_before>export default {
  "data": {
    "checkoutDiscountCodeApplyV2": {
      "checkoutUserErrors": [],
      "userErrors": [],
      "checkout": {
        "id": "Z2lkOi8vc2hvcGlmeS9DaGVja291dC9lM2JkNzFmNzI0OGM4MDZmMzM3MjVhNTNlMzM5MzFlZj9rZXk9NDcwOTJlNDQ4NTI5MDY4ZDFiZTUyZTUwNTE2MDNhZjg=",
        "createdAt": "2017-03-17T16:00:40Z",
        "updatedAt": "2017-03-17T16:00:40Z",
        "requiresShipping": true,
        "shippingLine": null,
        "order": null,
        "orderStatusUrl": null,
        "taxExempt": false,
        "taxesIncluded": false,
        "currencyCode": "CAD",
        "totalPrice": "80.28",
        "lineItemsSubtotalPrice": {
          "amount": "74.99",
          "currencyCode": "CAD"
        },
        "subtotalPrice": "67.50",
        "totalTax": "8.78",
        "paymentDue": "80.28",
        "taxExempt": false,
        "taxesIncluded": false,
        "completedAt": null,
        "shippingAddress": {
          "address1": "123 Cat Road",
          "address2": null,
          "city": "Cat Land",
          "company": "Catmart",
          "country": "Canada",
          "firstName": "Meow",
          "formatted": [
            "Catmart",
            "123 Cat Road",
            "Cat Land ON M3O 0W1",
            "Canada"
          ],
          "lastName": "Meowington",
          "latitude": null,
          "longitude": null,
          "phone": "4161234566",
          "province": "Ontario",
          "zip": "M3O 0W1",
          "name": "Meow Meowington",
          "countryCode": "CA",
          "provinceCode": "ON",
          "id": "291dC9lM2JkNzHJnnf8a89njNJNKAhu1gn7lMzM5MzFlZj9rZXk9NDcwOTJ=="
        },
        "lineItems": {
          "pageInfo": {
            "hasNextPage": false,
            "hasPreviousPage": false
          },
          "edges": [
            {
              "cursor": "eyJsYXN0X2lkIjoiZDUyZWU5ZTEwYmQxMWE0NDlkNmQzMWNkMzBhMGFjNzMifQ==",
              "node": {
                "title": "Intelligent Granite Table",
                "variant": {
                  "id": "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8yOTEwNjA2NDU4NA==",
                  "price": "74.99"
                },
                "quantity": 5,
                "customAttributes": [],
                "discountAllocations": [
                  {
                    "allocatedAmount": {
                      "amount": "7.49",
                      "currencyCode": "CAD"
                    },
                    "discountApplication": {
                      "targetSelection": "ALL",
                      "allocationMethod": "ACROSS",
                      "targetType": "LINE_ITEM",
                      "code": "TENPERCENTOFF",
                      "applicable": true,
                      "value": {
                        "percentage": "10"
                      }
                    }
                  }
                ]
              }
            }
          ]
        },
        "discountApplications": {
          "pageInfo": {
            "hasNextPage": false,
            "hasPreviousPage": false
          },
          "edges": [
            {
              "node": {
                "targetSelection": "ALL",
                "allocationMethod": "ACROSS",
                "targetType": "LINE_ITEM",
                "code": "TENPERCENTOFF",
                "applicable": true,
                "value": {
                  "percentage": "10"
                }
              }
            }
          ]
        }
      }
    }
  }
};
<commit_msg>Remove duplicate properties<commit_after>export default {
  "data": {
    "checkoutDiscountCodeApplyV2": {
      "checkoutUserErrors": [],
      "userErrors": [],
      "checkout": {
        "id": "Z2lkOi8vc2hvcGlmeS9DaGVja291dC9lM2JkNzFmNzI0OGM4MDZmMzM3MjVhNTNlMzM5MzFlZj9rZXk9NDcwOTJlNDQ4NTI5MDY4ZDFiZTUyZTUwNTE2MDNhZjg=",
        "createdAt": "2017-03-17T16:00:40Z",
        "updatedAt": "2017-03-17T16:00:40Z",
        "requiresShipping": true,
        "shippingLine": null,
        "order": null,
        "orderStatusUrl": null,
        "taxExempt": false,
        "taxesIncluded": false,
        "currencyCode": "CAD",
        "totalPrice": "80.28",
        "lineItemsSubtotalPrice": {
          "amount": "74.99",
          "currencyCode": "CAD"
        },
        "subtotalPrice": "67.50",
        "totalTax": "8.78",
        "paymentDue": "80.28",
        "completedAt": null,
        "shippingAddress": {
          "address1": "123 Cat Road",
          "address2": null,
          "city": "Cat Land",
          "company": "Catmart",
          "country": "Canada",
          "firstName": "Meow",
          "formatted": [
            "Catmart",
            "123 Cat Road",
            "Cat Land ON M3O 0W1",
            "Canada"
          ],
          "lastName": "Meowington",
          "latitude": null,
          "longitude": null,
          "phone": "4161234566",
          "province": "Ontario",
          "zip": "M3O 0W1",
          "name": "Meow Meowington",
          "countryCode": "CA",
          "provinceCode": "ON",
          "id": "291dC9lM2JkNzHJnnf8a89njNJNKAhu1gn7lMzM5MzFlZj9rZXk9NDcwOTJ=="
        },
        "lineItems": {
          "pageInfo": {
            "hasNextPage": false,
            "hasPreviousPage": false
          },
          "edges": [
            {
              "cursor": "eyJsYXN0X2lkIjoiZDUyZWU5ZTEwYmQxMWE0NDlkNmQzMWNkMzBhMGFjNzMifQ==",
              "node": {
                "title": "Intelligent Granite Table",
                "variant": {
                  "id": "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8yOTEwNjA2NDU4NA==",
                  "price": "74.99"
                },
                "quantity": 5,
                "customAttributes": [],
                "discountAllocations": [
                  {
                    "allocatedAmount": {
                      "amount": "7.49",
                      "currencyCode": "CAD"
                    },
                    "discountApplication": {
                      "targetSelection": "ALL",
                      "allocationMethod": "ACROSS",
                      "targetType": "LINE_ITEM",
                      "code": "TENPERCENTOFF",
                      "applicable": true,
                      "value": {
                        "percentage": "10"
                      }
                    }
                  }
                ]
              }
            }
          ]
        },
        "discountApplications": {
          "pageInfo": {
            "hasNextPage": false,
            "hasPreviousPage": false
          },
          "edges": [
            {
              "node": {
                "targetSelection": "ALL",
                "allocationMethod": "ACROSS",
                "targetType": "LINE_ITEM",
                "code": "TENPERCENTOFF",
                "applicable": true,
                "value": {
                  "percentage": "10"
                }
              }
            }
          ]
        }
      }
    }
  }
};
<|endoftext|>


<commit_before>import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { isNone } from '@ember/utils';
import { computed } from '@ember/object';
import chroma from 'chroma';

export default Controller.extend({
  intl: service(),
  approvalDeltas: computed('model.@each', function () {
    return this.get('model').map((record) => {
      return record.get('approvalDelta');
    });
  }),
  approvalDeltasLimits: computed('approvalDeltas', function () {
   return chroma.limits(this.get('approvalDeltas'), 'q', 4);
  }),
  missingDataLabel: computed('intl.locale', function() {
    return this.get('intl').t('visualize.time.bubble-chart-legend.missing-data');
  }),

  createTooltip(record){
    const options = {
      style: 'percent',
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }
    let approvals = [];
    record.get('approval').forEach((a,i) => {
      approvals[i] = a ? this.get('intl').formatNumber(a, options) : '?';
    });
    return this.get('intl').t('visualize.time.tooltip', {
      title: record.get('title'),
      approvalBefore: approvals[0],
      approvalAfter: approvals[1],
      impressionsBefore: record.get('impressions')[0],
      impressionsAfter: record.get('impressions')[1]
    });
  },

  colorScale: computed('model', function() {
    return chroma
      .scale(chroma.scale('RdBu')
        .colors(5)
        .reverse()
      )
      .domain(this.get('approvalDeltasLimits'));
  }),
  nullColor: chroma('tan'),
  chartData: computed('model', 'intl.locale', function() {
    let colorFunction = (value) => {
      if (isNone(value)){
        return this.get('nullColor');
      }
      return this.get('colorScale')(value);
    };
    let textColor = (color) => {
        return chroma(color).get('lab.l') < 70 ? 'white' : 'black';
    }
    return this.get('model').map((record) => {
      const color = colorFunction(record.get('approvalDelta'));
      return Object.create({
        id: record.get('id'),
        color,
        textColor: textColor(color),
        label: record.get('title'),
        tooltip: this.createTooltip(record),
        size: record.get('impressionsDelta'),
      });
    });
  }),

  actions: {
    onClick(id) {
      this.transitionToRoute('visualize.time.progress', id);
    }
  }
});
<commit_msg>tweak text color treshold<commit_after>import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { isNone } from '@ember/utils';
import { computed } from '@ember/object';
import chroma from 'chroma';

export default Controller.extend({
  intl: service(),
  approvalDeltas: computed('model.@each', function () {
    return this.get('model').map((record) => {
      return record.get('approvalDelta');
    });
  }),
  approvalDeltasLimits: computed('approvalDeltas', function () {
   return chroma.limits(this.get('approvalDeltas'), 'q', 4);
  }),
  missingDataLabel: computed('intl.locale', function() {
    return this.get('intl').t('visualize.time.bubble-chart-legend.missing-data');
  }),

  createTooltip(record){
    const options = {
      style: 'percent',
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }
    let approvals = [];
    record.get('approval').forEach((a,i) => {
      approvals[i] = a ? this.get('intl').formatNumber(a, options) : '?';
    });
    return this.get('intl').t('visualize.time.tooltip', {
      title: record.get('title'),
      approvalBefore: approvals[0],
      approvalAfter: approvals[1],
      impressionsBefore: record.get('impressions')[0],
      impressionsAfter: record.get('impressions')[1]
    });
  },

  colorScale: computed('model', function() {
    return chroma
      .scale(chroma.scale('RdBu')
        .colors(5)
        .reverse()
      )
      .domain(this.get('approvalDeltasLimits'));
  }),
  nullColor: chroma('tan'),
  chartData: computed('model', 'intl.locale', function() {
    let colorFunction = (value) => {
      if (isNone(value)){
        return this.get('nullColor');
      }
      return this.get('colorScale')(value);
    };
    let textColor = (color) => {
        return chroma(color).get('lab.l') < 40 ? 'white' : 'black';
    }
    return this.get('model').map((record) => {
      const color = colorFunction(record.get('approvalDelta'));
      return Object.create({
        id: record.get('id'),
        color,
        textColor: textColor(color),
        label: record.get('title'),
        tooltip: this.createTooltip(record),
        size: record.get('impressionsDelta'),
      });
    });
  }),

  actions: {
    onClick(id) {
      this.transitionToRoute('visualize.time.progress', id);
    }
  }
});
<|endoftext|>


<commit_before>"use strict";

var _ = require('lodash');
var ace = require('brace');
require('brace/mode/javascript');
require('brace/theme/monokai');
var Range = ace.acequire('ace/range').Range;
var style = require('./utils/styling');
var Program = require('./Runner/Parsing/Program').Program;
var run = require('./Runner/run');
var THREE = require('three'),
	toThree = require('./SceneGraph/to-three');

var fs = require('fs');
var initProgramSourceCode = fs.readFileSync(__dirname + "/example-programs/ex6_trelica_mobius.js", "utf8");

/*
There is a page that contains the editing interface.
This is a description of that page.

The page has a code editor may have a view of the results of that program.
The layout of the page is as follows.
The logic of the UI is ...
*/
/*
//
// Layout (and components)
//

//The page has these elements.
var viewDiv = document.createElement("div");
var codeEditorDiv = document.createElement("div");

//They will have these styles.
var bodyStyle = {
	"margin": "0",
	//"overflow": "hidden"
};
var divStyle = {
	"width": "50%",
	"height": "100%"
};
var viewDivStyle = {
	"float": "left"
};
var codeEditorDivStyle = {
	"float": "right"
};

style.applyStyle(viewDiv, style.join(divStyle, viewDivStyle));
style.applyStyle(codeEditorDiv, style.join(divStyle, codeEditorDivStyle));
style.applyStyle(document.body, bodyStyle);

document.body.appendChild(viewDiv);
document.body.appendChild(codeEditorDiv);

//The code editor and the 3d view are mounted in the elements.
var codeEditor = ace.edit(codeEditorDiv);
codeEditor.getSession().setMode("ace/mode/javascript");
codeEditor.setTheme("ace/theme/monokai");
codeEditor.setValue(initProgramSourceCode);// TODO Change how the program is displayed.
codeEditor.clearSelection();

var realView = View.on(viewDiv);

//
// Traceability logic
//

var initProgram = Program.fromSourceCode(initProgramSourceCode);

console.time("instrument_n_run");
var results = run.withTraceability(initProgram);
console.timeEnd("instrument_n_run");

// threeObjects :
//    - THREE objects corresponding to values of the top level expressions.

//show renderable results
// Generate THREE objects for all the top level expression values.
// Keep the correspondence between each value/sub-value and the THREE objects generated from it.
//    This way we can reference them given a value/sub-value.
//    From a call expression we get its values and from them we get their THREE objects.
// Can we do it in a different way? Something more local?
// TODO: Move THREE object generation to helpers of UI?
console.time("THREE conversion");
var {threeObjects, resultToTHREEObjects} = toThree.convert.keepingCorrespondence(results.results.topLevelExprResults.values());
console.timeEnd("THREE conversion");
var scene = new THREE.Scene();
scene.add.apply(scene, threeObjects);
//realView.setScene(scene);

//var callHighlighting = (function (){
	//
	// Initialization
	//

	function addStyleToDocument() {
		//style for call highlight
		var callHighlightStyle = ".highlight-call-marker {position: absolute; background-color: hsl(47, 100%, 71%); opacity: 0.5; }";
		var callHighlightStyleElem = document.createElement("style");
		callHighlightStyleElem.innerText = callHighlightStyle;
		document.head.appendChild(callHighlightStyleElem);
	}

	addStyleToDocument();

	// **********
	// Functions
	// **********

	//
	// Params: callTraces -> context of the 'trace-call-transform' after running the program.
	// Returns: [{id, range}] -> astNodes whose results are highlightable.
	//
	function highlightableAstNodes(results) {
		return Array.from(results.traceabilityInfo.callTraces.keys())
			.filter(id=>toThree.isRenderable(results.traceabilityInfo.callTraces.get(id)[0].result))
			.map(id=>{
				const {start, end} = JSON.parse(id);
				return {
					id: id,
					range: new Range(start.line-1, start.column, end.line-1, end.column)
				};
			});
	}

	//
	// Returns: AstNode | null (if none found)
	//
	function deepestAstNodeContainingCoord(astNodes, loc) {
		const {line, column} = loc;
		return (
		astNodes
		.filter(h=>h.range.contains(line, column))
		.reduce((prev, curr)=>prev === null || prev.range.containsRange(curr.range) ? curr : prev, null)
		);
	}

	function acceptResults(topLevelResults, callExpressionResults){}
	//
	// TODO Finish rewriting traceability (both business logic and UI).
	//

//})();

var callExprsWithResults = highlightableAstNodes(results);
function deepestHighlightableContainingCoord(row, col) {
	return deepestAstNodeContainingCoord(callExprsWithResults, {line: row, column: col});
}

var currMarker = null;
var currTHREEObjs = null;
var threeObjToOldMaterial = new Map();
var highlightMaterial = new THREE.MeshPhongMaterial();
highlightMaterial.emissive.setHSL(52/360.0, 0.92, 0.49);
highlightMaterial.depthTest = false;
highlightMaterial.depthWrite = false;
highlightMaterial.transparent = true;
highlightMaterial.opacity = 0.8;
function setHighlighted(highlightable) {
	//highlight code
	if(currMarker !== null) {
		codeEditor.getSession().removeMarker(currMarker);
	}
	currMarker = codeEditor.getSession()
		.addMarker(highlightable.range, "highlight-call-marker", "text", true);
	//highlight THREEObject3Ds
	if(currTHREEObjs !== null) {
		currTHREEObjs.forEach(obj=>{
			obj.material = threeObjToOldMaterial.get(obj);
		});
		threeObjToOldMaterial.clear();
		currTHREEObjs = null;
	}
	var resultsToHighlight = results.traceabilityInfo.callTraces.get(highlightable.id)
		.map(callTrace=>callTrace.result);
	var objsToHighlight = resultsToHighlight
		.map(res=>resultToTHREEObjects.get(res))
		.reduce((l1,l2)=>l1.concat(l2));
	var objsWithMaterial = new Set();
	objsToHighlight.forEach(o=>o.traverse(o=>{
		if(o.material !== undefined) {
			objsWithMaterial.add(o);
		}
	}));
	objsWithMaterial.forEach(o=>{
		threeObjToOldMaterial.set(o, o.material);
		o.material = highlightMaterial;
	});
	currTHREEObjs = Array.from(objsWithMaterial);
}
function unsetHighlighted() {
	if(currMarker !== null) {
		codeEditor.getSession().removeMarker(currMarker);
		currMarker = null;
	}
	if(currTHREEObjs !== null) {
		currTHREEObjs.forEach(obj=>{
			obj.material = threeObjToOldMaterial.get(obj);
		});
		threeObjToOldMaterial.clear();
		currTHREEObjs = null;
	}
}

var lastHighlightable = null;
function handleMouseMove(e) {
	var screenCoords = codeEditor.renderer.pixelToScreenCoordinates(e.clientX, e.clientY);
	var docCoords = codeEditor.getSession().screenToDocumentPosition(screenCoords.row, screenCoords.column);
	var highlightable = deepestHighlightableContainingCoord(docCoords.row, docCoords.column);
	if(highlightable === lastHighlightable) {
		return;
	}
	console.time("highlight change");
	if(highlightable !== null) {
		setHighlighted(highlightable);
	} else {
		unsetHighlighted();
	}
	lastHighlightable = highlightable;
	console.timeEnd("highlight change");
	realView.redraw();
}
codeEditor.renderer.container.addEventListener("mousemove", _.throttle(handleMouseMove, 100));

//
// React Three canvas experiment.
//
import React from 'react';
import ReactDOM from 'react-dom';
import OrbitThreeView from './ReactComponents/OrbitThreeView.jsx';

const reactContainer = document.createElement("div");
document.body.appendChild(reactContainer);

//const nyCam = new THREE.PerspectiveCamera(90, 1.0/1.0, 0.1, 1000);
//nyCam.position.set(0.0, 20.0, 30.0);
const nyScene = new THREE.Scene();
nyScene.add(scene);
const dirLight = new THREE.DirectionalLight(0xffffaa, 0.5);
dirLight.position.set(0.1, 1, 0.2);
nyScene.add(dirLight);
nyScene.add(new THREE.GridHelper(100, 1));
nyScene.add(new THREE.AxisHelper(5));

ReactDOM.render(
	React.createElement(
		OrbitThreeView,
		{width:512, height:512, scene: nyScene}),
	reactContainer);
*/

/*
//
// React ProgramTextView test.
//
import React from 'react';
import ReactDOM from 'react-dom';
import ProgramTextView from './ReactComponents/ProgramTextView.jsx';

const programViewContainer = document.createElement("div");
document.body.appendChild(programViewContainer);

programViewContainer.style.width = "512px";
programViewContainer.style.height = "512px";

ReactDOM.render(
	<ProgramTextView
		program={{getSourceCode: ()=>initProgramSourceCode}}/>,
	programViewContainer);
*/

/*
//
//
//
import React from 'react';
import ReactDOM from 'react-dom';
import RealTimeRunEditor from './ReactComponents/RealTimeRunEditor.jsx';

const realtimeEditorContainer = document.createElement("div");
document.body.appendChild(realtimeEditorContainer);
ReactDOM.render(<RealTimeRunEditor/>, realtimeEditorContainer);
*/

/*
//
//
//
import React from 'react';
import ReactDOM from 'react-dom';
import TextEditor from './ReactComponents/TextEditor.jsx';
const textEditorContainer = document.createElement("div");
document.body.appendChild(textEditorContainer);
ReactDOM.render(<TextEditor value={"sphere(5);\n"} onChange={function(){console.log(arguments)}}/>, textEditorContainer);
*/

import React from 'react';
import ReactDOM from 'react-dom';
import App from './ReactComponents/App.jsx';

ReactDOM.render(<App/>, document.getElementById("container"));
<commit_msg>Cleanup.<commit_after>"use strict";

import React from 'react';
import ReactDOM from 'react-dom';
import App from './ReactComponents/App.jsx';

ReactDOM.render(<App/>, document.getElementById("container"));
<|endoftext|>


<commit_before>/**
 * @file Path helper
 * @since 0.1.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*exported _gpfPathDecompose*/ // Normalize path and returns an array of parts
/*exported _gpfPathExtension*/ // Get the extension of the last name of a path (including dot)
/*exported _gpfPathJoin*/ // Join all arguments together and normalize the resulting path
/*exported _gpfPathNormalize*/ // Normalize path
/*exported _gpfPathParent*/ // Get the parent of a path
/*#endif*/

_gpfErrorDeclare("path", {

    /**
     * ### Summary
     *
     * Unreachable path
     *
     * ### Description
     *
     * This error is triggered when trying to get the parent of a root path using gpf.path.parent or
     * gpf.path.join with ..
     * @see gpf.path.join
     * @see gpf.path.parent
     * @since 0.1.9
     */
    unreachablePath:
        "Unreachable path"
});

//region _gpfPathDecompose

function _gpfPathSplit (path) {
    if (-1 < path.indexOf("\\")) {
        // DOS path is case insensitive, hence lowercase it
        return path.toLowerCase().split("\\");
    }
    // Assuming a Unix-like path
    return path.split("/");
}

function _gpfPathRemoveTrailingBlank (splitPath) {
    if (!splitPath[splitPath.length - 1]) {
        splitPath.pop();
    }
}

function _gpfPathUp (splitPath) {
    if (splitPath.length) {
        splitPath.pop();
    } else {
        gpf.Error.unreachablePath();
    }
}

/**
 * Normalize paths and returns an array of parts.
 * If a DOS-like path is detected (use of \), it is lower-cased
 *
 * @param {String} path Path to normalize
 * @return {String[]} Normalized path represented as an array of parts
 * @since 0.1.9
 */
function _gpfPathDecompose (path) {
    var splitPath = _gpfPathSplit(path);
    _gpfPathRemoveTrailingBlank(splitPath);
    return splitPath;
}

//endregion

/**
 * Normalize path
 *
 * @param {String} path Path to normalize
 * @return {String} Normalized path
 * @since 0.1.9
 */
function _gpfPathNormalize (path) {
    return _gpfPathDecompose(path).join("/");
}

/**
 * Get the last name of a path
 *
 * @param {String} path Path to analyze
 * @return {String} Name
 * @since 0.1.9
 */
function _gpfPathName (path) {
    if (path) {
        return _gpfPathDecompose(path).pop();
    }
    return "";
}

/**
 * Get the extension of the last name of a path (including dot)
 *
 * @param {String} path Path to analyze
 * @return {String} Extension (including dot)
 * @since 0.1.9
 */
function _gpfPathExtension (path) {
    var name = _gpfPathName(path),
        pos = name.lastIndexOf(".");
    if (-1 === pos) {
        return "";
    }
    return name.substr(pos);
}

function _gpfPathAppend (splitPath, relativePath) {
    _gpfPathDecompose(relativePath).forEach(function (relativeItem) {
        if (".." === relativeItem) {
            _gpfPathUp(splitPath);
        } else {
            splitPath.push(relativeItem);
        }
    });
}

/**
 * Join all arguments together and normalize the resulting path
 *
 * @param {String} path Base path
 * @param {...String} relativePath Relative parts to append to the base path
 * @return {String} Joined path
 * @throws {gpf.Error.UnreachablePath}
 * @since 0.1.9
 */
function _gpfPathJoin (path) {
    var splitPath = _gpfPathDecompose(path);
    [].slice.call(arguments, 1).forEach(_gpfPathAppend.bind(null, splitPath));
    return splitPath.join("/");
}

function _gpfPathSafeShiftIdenticalBeginning (splitFromPath, splitToPath) {
    while (splitFromPath[0] === splitToPath[0]) {
        splitFromPath.shift();
        splitToPath.shift();
    }
}

function _gpfPathShiftIdenticalBeginning (splitFromPath, splitToPath) {
    if (splitFromPath.length * splitToPath.length) { // equivalent to splitFromPath.length && splitToPath.length
        _gpfPathSafeShiftIdenticalBeginning(splitFromPath, splitToPath);
    }
}

/**
 * Get the parent of a path
 *
 * @param {String} path Path to analyze
 * @return {String} Parent path
 * @throws {gpf.Error.UnreachablePath}
 * @since 0.1.9
 */
function _gpfPathParent (path) {
    path = _gpfPathDecompose(path);
    _gpfPathUp(path);
    return path.join("/");
}

/**
 * Solve the relative path from from to to
 *
 * @param {String} from From path
 * @param {String} to To path
 * @return {String} Relative path
 * @since 0.1.9
 */
function _gpfPathRelative (from, to) {
    var length,
        splitFrom = _gpfPathDecompose(from),
        splitTo = _gpfPathDecompose(to);
    _gpfPathShiftIdenticalBeginning(splitFrom, splitTo);
    // For each remaining part in from, unshift .. in to
    length = splitFrom.length + 1;
    while (--length) {
        splitTo.unshift("..");
    }
    return splitTo.join("/");
}

/**
 * @namespace gpf.path
 * @description Root namespace for path manipulation.
 *
 * As the library works with several hosts (Windows and Unix-like, see {@tutorial LOADING}),
 * the API accepts any kind of [path separator](https://en.wikipedia.org/wiki/Path_%28computing%29).
 * However, they can't be mixed.
 *
 * When giving a path, the rule is:
 * - If the path contains at least one \, it is considered a Windows one
 * - Otherwise, the path is considered a Unix one
 *
 * On the other hand, all path returned by the API are using the Unix-like formalism.
 *
 * @since 0.1.9
 */
gpf.path = {

    /**
     * @gpf:sameas _gpfPathJoin
     * @since 0.1.9
     */
    join: _gpfPathJoin,

    /**
     * @gpf:sameas _gpfPathParent
     * @since 0.1.9
     */
    parent: _gpfPathParent,

    /**
     * @gpf:sameas _gpfPathName
     * @since 0.1.9
     */
    name: _gpfPathName,

    /**
     * Get the last name of a path without the extension
     *
     * @param {String} path Path to analyze
     * @return {String} Name without the extension
     * @since 0.1.9
     */
    nameOnly: function (path) {
        var name = _gpfPathName(path),
            pos = name.lastIndexOf(".");
        if (-1 === pos) {
            return name;
        }
        return name.substr(0, pos);
    },

    /**
     * @gpf:sameas _gpfPathExtension
     * @since 0.1.9
     */
    extension: _gpfPathExtension,

    /**
     * @gpf:sameas _gpfPathRelative
     * @since 0.1.9
     */
    relative: _gpfPathRelative

};

/*#ifndef(UMD)*/

gpf.internals._gpfPathNormalize = _gpfPathNormalize;

/*#endif*/
<commit_msg>Handles absolute path (#244)<commit_after>/**
 * @file Path helper
 * @since 0.1.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*global _gpfArrayForEach*/
/*global _gpfEmptyFunc*/
/*exported _gpfPathDecompose*/ // Normalize path and returns an array of parts
/*exported _gpfPathExtension*/ // Get the extension of the last name of a path (including dot)
/*exported _gpfPathJoin*/ // Join all arguments together and normalize the resulting path
/*exported _gpfPathNormalize*/ // Normalize path
/*exported _gpfPathParent*/ // Get the parent of a path
/*#endif*/

_gpfErrorDeclare("path", {

    /**
     * ### Summary
     *
     * Unreachable path
     *
     * ### Description
     *
     * This error is triggered when trying to get the parent of a root path using gpf.path.parent or
     * gpf.path.join with ..
     * @see gpf.path.join
     * @see gpf.path.parent
     * @since 0.1.9
     */
    unreachablePath:
        "Unreachable path"
});

//region _gpfPathDecompose

function _gpfPathSplit (path) {
    if (-1 < path.indexOf("\\")) {
        // DOS path is case insensitive, hence lowercase it
        return path.toLowerCase().split("\\");
    }
    // Assuming a Unix-like path
    return path.split("/");
}

function _gpfPathRemoveTrailingBlank (splitPath) {
    if (!splitPath[splitPath.length - 1]) {
        splitPath.pop();
    }
}

function _gpfPathUp (splitPath) {
    if (splitPath.length) {
        splitPath.pop();
    } else {
        gpf.Error.unreachablePath();
    }
}

/**
 * Normalize paths and returns an array of parts.
 * If a DOS-like path is detected (use of \), it is lower-cased
 *
 * @param {String} path Path to normalize
 * @return {String[]} Normalized path represented as an array of parts
 * @since 0.1.9
 */
function _gpfPathDecompose (path) {
    var splitPath = _gpfPathSplit(path);
    _gpfPathRemoveTrailingBlank(splitPath);
    return splitPath;
}

//endregion

/**
 * Normalize path
 *
 * @param {String} path Path to normalize
 * @return {String} Normalized path
 * @since 0.1.9
 */
function _gpfPathNormalize (path) {
    return _gpfPathDecompose(path).join("/");
}

/**
 * Get the last name of a path
 *
 * @param {String} path Path to analyze
 * @return {String} Name
 * @since 0.1.9
 */
function _gpfPathName (path) {
    if (path) {
        return _gpfPathDecompose(path).pop();
    }
    return "";
}

/**
 * Get the extension of the last name of a path (including dot)
 *
 * @param {String} path Path to analyze
 * @return {String} Extension (including dot)
 * @since 0.1.9
 */
function _gpfPathExtension (path) {
    var name = _gpfPathName(path),
        pos = name.lastIndexOf(".");
    if (-1 === pos) {
        return "";
    }
    return name.substr(pos);
}

var _gpfPathAppendPatterns = {

    "": function (splitPath) {
        splitPath.length = 0;
        splitPath.push(""); // Will start with /
    },

    ".": _gpfEmptyFunc,

    "..": function (splitPath) {
        _gpfPathUp(splitPath);
    }

};

function _gpfPathAppend (splitPath, relativePath) {
    _gpfArrayForEach(_gpfPathDecompose(relativePath), function (relativeItem) {
        var pattern = _gpfPathAppendPatterns[relativeItem];
        if (pattern) {
            pattern(splitPath);
        } else {
            splitPath.push(relativeItem);
        }
    });
}

/**
 * Join all arguments together and normalize the resulting path
 *
 * @param {String} path Base path
 * @param {...String} relativePath Relative parts to append to the base path
 * @return {String} Joined path
 * @throws {gpf.Error.UnreachablePath}
 * @since 0.1.9
 */
function _gpfPathJoin (path) {
    var splitPath = _gpfPathDecompose(path);
    [].slice.call(arguments, 1).forEach(_gpfPathAppend.bind(null, splitPath));
    return splitPath.join("/");
}

function _gpfPathSafeShiftIdenticalBeginning (splitFromPath, splitToPath) {
    while (splitFromPath[0] === splitToPath[0]) {
        splitFromPath.shift();
        splitToPath.shift();
    }
}

function _gpfPathShiftIdenticalBeginning (splitFromPath, splitToPath) {
    if (splitFromPath.length * splitToPath.length) { // equivalent to splitFromPath.length && splitToPath.length
        _gpfPathSafeShiftIdenticalBeginning(splitFromPath, splitToPath);
    }
}

/**
 * Get the parent of a path
 *
 * @param {String} path Path to analyze
 * @return {String} Parent path
 * @throws {gpf.Error.UnreachablePath}
 * @since 0.1.9
 */
function _gpfPathParent (path) {
    path = _gpfPathDecompose(path);
    _gpfPathUp(path);
    return path.join("/");
}

/**
 * Solve the relative path from from to to
 *
 * @param {String} from From path
 * @param {String} to To path
 * @return {String} Relative path
 * @since 0.1.9
 */
function _gpfPathRelative (from, to) {
    var length,
        splitFrom = _gpfPathDecompose(from),
        splitTo = _gpfPathDecompose(to);
    _gpfPathShiftIdenticalBeginning(splitFrom, splitTo);
    // For each remaining part in from, unshift .. in to
    length = splitFrom.length + 1;
    while (--length) {
        splitTo.unshift("..");
    }
    return splitTo.join("/");
}

/**
 * @namespace gpf.path
 * @description Root namespace for path manipulation.
 *
 * As the library works with several hosts (Windows and Unix-like, see {@tutorial LOADING}),
 * the API accepts any kind of [path separator](https://en.wikipedia.org/wiki/Path_%28computing%29).
 * However, they can't be mixed.
 *
 * When giving a path, the rule is:
 * - If the path contains at least one \, it is considered a Windows one
 * - Otherwise, the path is considered a Unix one
 *
 * On the other hand, all path returned by the API are using the Unix-like formalism.
 *
 * @since 0.1.9
 */
gpf.path = {

    /**
     * @gpf:sameas _gpfPathJoin
     * @since 0.1.9
     */
    join: _gpfPathJoin,

    /**
     * @gpf:sameas _gpfPathParent
     * @since 0.1.9
     */
    parent: _gpfPathParent,

    /**
     * @gpf:sameas _gpfPathName
     * @since 0.1.9
     */
    name: _gpfPathName,

    /**
     * Get the last name of a path without the extension
     *
     * @param {String} path Path to analyze
     * @return {String} Name without the extension
     * @since 0.1.9
     */
    nameOnly: function (path) {
        var name = _gpfPathName(path),
            pos = name.lastIndexOf(".");
        if (-1 === pos) {
            return name;
        }
        return name.substr(0, pos);
    },

    /**
     * @gpf:sameas _gpfPathExtension
     * @since 0.1.9
     */
    extension: _gpfPathExtension,

    /**
     * @gpf:sameas _gpfPathRelative
     * @since 0.1.9
     */
    relative: _gpfPathRelative

};

/*#ifndef(UMD)*/

gpf.internals._gpfPathNormalize = _gpfPathNormalize;

/*#endif*/
<|endoftext|>


<commit_before>/**
 * Martian - Core JavaScript API for MindTouch
 *
 * Copyright (c) 2015 MindTouch Inc.
 * www.mindtouch.com  oss@mindtouch.com
 *
 * 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.
 */
import { Uri } from './uri';
function _handleHttpError(response) {
    return new Promise((resolve, reject) => {

        // Throw for all non-2xx status codes, except for 304
        if(!response.ok && response.status !== 304) {
            reject(new Error(response.statusText));
        } else {
            resolve(response);
        }
    });
}
function _doFetch({ method, headers, body = null }) {
    let requestHeaders = new Headers(headers);
    let requestData = { method: method, headers: requestHeaders, credentials: 'include' };
    if(body !== null) {
        requestData.body = body;
    }
    let request = new Request(this._url.toString(), requestData);
    return fetch(request).then(_handleHttpError);
}
function _cloneHeaders() {
    let cloned = {};
    Object.keys(this._headers).forEach((key) => {
        cloned[key] = this._headers[key];
    });
    return cloned;
}
export class Plug {
    constructor(url = '/', { uriParts = {}, headers = {}, timeout = null, beforeRequest = (params) => params } = {}) {

        // Initialize the url for this instance
        this._url = new Uri(url);
        if('segments' in uriParts) {
            this._url.addSegments(uriParts.segments);
        }
        if('query' in uriParts) {
            this._url.addQueryParams(uriParts.query);
        }
        if('excludeQuery' in uriParts) {
            this._url.removeQueryParam(uriParts.excludeQuery);
        }

        this._beforeRequest = beforeRequest;
        this._timeout = timeout;
        this._headers = headers;
    }
    get url() {
        return this._url.toString();
    }
    get headers() {
        return new Headers(this._headers);
    }
    at(...segments) {
        var values = [];
        segments.forEach(function(segment) {
            values.push(segment.toString());
        });
        return new Plug(this._url.toString(), {
            headers: this._headers,
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            uriParts: { segments: values }
        });
    }
    withParam(key, value) {
        let params = {};
        params[key] = value;
        return new Plug(this._url.toString(), {
            headers: this._headers,
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            uriParts: { query: params }
        });
    }
    withParams(values = {}) {
        return new Plug(this._url.toString(), {
            headers: this._headers,
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            uriParts: { query: values }
        });
    }
    withoutParam(key) {
        return new Plug(this._url.toString(), {
            headers: this._headers,
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            uriParts: { excludeQuery: key }
        });
    }
    withHeader(key, value) {
        let newHeaders = _cloneHeaders.call(this);
        newHeaders[key] = value;
        return new Plug(this._url.toString(), {
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            headers: newHeaders
        });
    }
    withHeaders(values) {
        let newHeaders = _cloneHeaders.call(this);
        Object.keys(values).forEach((key) => {
            newHeaders[key] = values[key];
        });
        return new Plug(this._url.toString(), {
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            headers: newHeaders
        });
    }
    withoutHeader(key) {
        let newHeaders = _cloneHeaders.call(this);
        delete newHeaders[key];
        return new Plug(this._url.toString(), {
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            headers: newHeaders
        });
    }
    get(method = 'GET') {
        let params = this._beforeRequest({ method: method, headers: _cloneHeaders.call(this) });
        return _doFetch.call(this, params);
    }
    getText() {
        return this.get().then((r) => r.text());
    }
    getJson() {
        return this.get().then((r) => r.json());
    }
    post(body, mime, method = 'POST') {
        this._headers['Content-Type'] = mime;
        let params = this._beforeRequest({ method: method, body: body, headers: _cloneHeaders.call(this) });
        return _doFetch.call(this, params);
    }
    put(body, mime) {
        return this.post(body, mime, 'PUT');
    }
    head() {
        return this.get('HEAD');
    }
    options() {
        return this.get('OPTIONS');
    }
    delete() {
        return this.post(null, null, 'DELETE');
    }
}
<commit_msg>more info in http error handling rejection<commit_after>/**
 * Martian - Core JavaScript API for MindTouch
 *
 * Copyright (c) 2015 MindTouch Inc.
 * www.mindtouch.com  oss@mindtouch.com
 *
 * 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.
 */
import { Uri } from './uri';
function _handleHttpError(response) {
    return new Promise((resolve, reject) => {

        // Throw for all non-2xx status codes, except for 304
        if(!response.ok && response.status !== 304) {
            Promise.all([
                response.text(),
                response.json()
            ]).then(([ text, json ]) => {
                reject({
                    message: response.statusText,
                    status: response.status,
                    responseText: text,
                    responseJson: json
                });
            });
        } else {
            resolve(response);
        }
    });
}
function _doFetch({ method, headers, body = null }) {
    let requestHeaders = new Headers(headers);
    let requestData = { method: method, headers: requestHeaders, credentials: 'include' };
    if(body !== null) {
        requestData.body = body;
    }
    let request = new Request(this._url.toString(), requestData);
    return fetch(request).then(_handleHttpError);
}
function _cloneHeaders() {
    let cloned = {};
    Object.keys(this._headers).forEach((key) => {
        cloned[key] = this._headers[key];
    });
    return cloned;
}
export class Plug {
    constructor(url = '/', { uriParts = {}, headers = {}, timeout = null, beforeRequest = (params) => params } = {}) {

        // Initialize the url for this instance
        this._url = new Uri(url);
        if('segments' in uriParts) {
            this._url.addSegments(uriParts.segments);
        }
        if('query' in uriParts) {
            this._url.addQueryParams(uriParts.query);
        }
        if('excludeQuery' in uriParts) {
            this._url.removeQueryParam(uriParts.excludeQuery);
        }

        this._beforeRequest = beforeRequest;
        this._timeout = timeout;
        this._headers = headers;
    }
    get url() {
        return this._url.toString();
    }
    get headers() {
        return new Headers(this._headers);
    }
    at(...segments) {
        var values = [];
        segments.forEach(function(segment) {
            values.push(segment.toString());
        });
        return new Plug(this._url.toString(), {
            headers: this._headers,
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            uriParts: { segments: values }
        });
    }
    withParam(key, value) {
        let params = {};
        params[key] = value;
        return new Plug(this._url.toString(), {
            headers: this._headers,
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            uriParts: { query: params }
        });
    }
    withParams(values = {}) {
        return new Plug(this._url.toString(), {
            headers: this._headers,
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            uriParts: { query: values }
        });
    }
    withoutParam(key) {
        return new Plug(this._url.toString(), {
            headers: this._headers,
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            uriParts: { excludeQuery: key }
        });
    }
    withHeader(key, value) {
        let newHeaders = _cloneHeaders.call(this);
        newHeaders[key] = value;
        return new Plug(this._url.toString(), {
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            headers: newHeaders
        });
    }
    withHeaders(values) {
        let newHeaders = _cloneHeaders.call(this);
        Object.keys(values).forEach((key) => {
            newHeaders[key] = values[key];
        });
        return new Plug(this._url.toString(), {
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            headers: newHeaders
        });
    }
    withoutHeader(key) {
        let newHeaders = _cloneHeaders.call(this);
        delete newHeaders[key];
        return new Plug(this._url.toString(), {
            timeout: this._timeout,
            beforeRequest: this._beforeRequest,
            headers: newHeaders
        });
    }
    get(method = 'GET') {
        let params = this._beforeRequest({ method: method, headers: _cloneHeaders.call(this) });
        return _doFetch.call(this, params);
    }
    getText() {
        return this.get().then((r) => r.text());
    }
    getJson() {
        return this.get().then((r) => r.json());
    }
    post(body, mime, method = 'POST') {
        this._headers['Content-Type'] = mime;
        let params = this._beforeRequest({ method: method, body: body, headers: _cloneHeaders.call(this) });
        return _doFetch.call(this, params);
    }
    put(body, mime) {
        return this.post(body, mime, 'PUT');
    }
    head() {
        return this.get('HEAD');
    }
    options() {
        return this.get('OPTIONS');
    }
    delete() {
        return this.post(null, null, 'DELETE');
    }
}
<|endoftext|>


<commit_before>'use strict';

((root) => {
  class Parallax {
    constructor(nodes) {
      if (!nodes || typeof nodes !== 'object') {
        return;
      }

      this.nodes = nodes;

      if (!this.performChecks) {
        this.show();

        return;
      }

      this.show();
      this.register();
    }

    performChecks() {
      if (/iP(ad|hone|od).*OS\s7.*/.test(navigator.userAgent)) {
        return false;
      }

      if (!window.requestAnimationFrame) {
        return false;
      }

      return true;
    }

    loop(callback) {
      for (let i = 0; i < this.nodes.length; i++) {
        callback(this.nodes[i]);
      }
    }

    show() {
      function display(node) {
        node.style.display = 'block';
      }

      if (!this.nodes.length) {
        display(this.nodes);

        return;
      }

      this.loop(node => {
        display(node);
      });
    }

    register() {
      this.init();

      window.addEventListener('resize', () => this.init());
    }

    init() {}
  }

  const exp = item => new Parallax(item);

  if (typeof module === 'object') {
    module.exports = exp;
  } else {
    root.prlx = exp;
  }
})(this);
<commit_msg>:art: Improve loop helper<commit_after>'use strict';

((root) => {
  class Parallax {
    constructor(nodes) {
      if (!nodes || typeof nodes !== 'object') {
        return;
      }

      this.nodes = nodes;

      if (!this.performChecks) {
        this.show();

        return;
      }

      this.show();
      this.register();
    }

    performChecks() {
      if (/iP(ad|hone|od).*OS\s7.*/.test(navigator.userAgent)) {
        return false;
      }

      if (!window.requestAnimationFrame) {
        return false;
      }

      return true;
    }

    loopNodes(callback) {
      if (!this.nodes.length) {
        callback(this.nodes);

        return;
      }

      for (let i = 0; i < this.nodes.length; i++) {
        callback(this.nodes[i]);
      }
    }

    show() {
      function display(node) {
        node.style.display = 'block';
      }

      this.loopNodes(node => {
        display(node);
      });
    }

    register() {
      this.init();

      window.addEventListener('resize', () => this.init());
    }

    init() {}
  }

  const exp = item => new Parallax(item);

  if (typeof module === 'object') {
    module.exports = exp;
  } else {
    root.prlx = exp;
  }
})(this);
<|endoftext|>


<commit_before>'use strict';
// Load required libraries
const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const documentclient = new AWS.DynamoDB.DocumentClient();

module.exports.handler = (event, context, callback) => {

	// Set from and to variables, use from and to in event if present.
	let from;
	if (Number(event.from) > 1) from = Number(event.from);
	else from = 1;

	let to;
	if (Number(event.to) > 1) to = Number(event.to);
	else to = new Date() / 1000;

	// Set scan limit to 20 if not present or greater than 20
	let limit = process.env.LIMIT;
	if (Number(event.limit) < process.env.LIMIT) limit = event.limit;

	// Set scanning parameters
	let params = {
		TableName: process.env.TABLE_NAME,
		// Only get Coordinates and Action data from the table
		ProjectionExpression: 'Coordinates, #b',
		// Only return items that fall within start and stop parameters
		FilterExpression: 'Added BETWEEN :start AND :stop',
		ExpressionAttributeNames: {
			// Set an 'alias' for the word, 'Action', because 'Action' is a reserved word in DynamoDB
			'#b': 'Action'
		},
		ExpressionAttributeValues: {
			// Set an 'alias' for start and stop variables
			':start': from,
			':stop': to
		},
		Limit: limit
	};

	if (event.hasOwnProperty('exclusivestartkey') && event.exclusivestartkey !== '') {
		params.ExclusiveStartKey = {};
		params.ExclusiveStartKey.Id = event.exclusivestartkey;
	}

	documentclient.scan(params, function(err,data) {
		// Log error if scanning returns err
		if (err) {
			console.error('Unable to scan the table. ', JSON.stringify(err, null, 2));
			callback(err);
		}
		else callback(null, data); // Returns the item data back to the client
	});

};
<commit_msg>Return error messages to client<commit_after>'use strict';
// Load required libraries
const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const documentclient = new AWS.DynamoDB.DocumentClient();

module.exports.handler = (event, context, callback) => {

	// Set from and to variables, use from and to in event if present.
	let from;
	if (Number(event.from) > 1) from = Number(event.from);
	else from = 1;

	let to;
	if (Number(event.to) > 1) to = Number(event.to);
	else to = new Date() / 1000;

	// Set scan limit to 20 if not present or greater than 20
	let limit = process.env.LIMIT;
	if (Number(event.limit) < process.env.LIMIT) limit = event.limit;

	// Set scanning parameters
	let params = {
		TableName: process.env.TABLE_NAME,
		// Only get Coordinates and Action data from the table
		ProjectionExpression: 'Coordinates, #b',
		// Only return items that fall within start and stop parameters
		FilterExpression: 'Added BETWEEN :start AND :stop',
		ExpressionAttributeNames: {
			// Set an 'alias' for the word, 'Action', because 'Action' is a reserved word in DynamoDB
			'#b': 'Action'
		},
		ExpressionAttributeValues: {
			// Set an 'alias' for start and stop variables
			':start': from,
			':stop': to
		},
		Limit: limit
	};

	if (event.hasOwnProperty('exclusivestartkey') && event.exclusivestartkey !== '') {
		params.ExclusiveStartKey = {};
		params.ExclusiveStartKey.Id = event.exclusivestartkey;
	}

	documentclient.scan(params, function(err,data) {
		// Log error if scanning returns err
		if (err) {
			console.error('Unable to scan the table. ', JSON.stringify(err, null, 2));
			callback(null, 'Unable to retrieve the data.');
		}
		else callback(null, data); // Returns the item data back to the client
	});

};
<|endoftext|>


<commit_before>/* global PIXI */
import 'pixi.js'
import 'pixi-particles'

import Leap from 'leapjs'
import { Howl } from 'howler'

import Hand from 'entities/hand.js'

import Socket from './socket'

const WIDTH = 1200
const HEIGHT = 675
const RATIO = WIDTH / HEIGHT

const MUSIC = [
  'bensound-dubstep',
  'bensound-moose'
]

const TEXTURES = [
  'open',
  'closed',
  'point',
  'pinch',
  'stars',
  'planet',
  'moon',
  'particle'
]

class Room {
  constructor (elementId, data) {
    window.room = this
    this.data = data
    this.canvas = document.getElementById(elementId)
    this.textures = {}
    this.music = {}
    this.entities = {}
  }

  load (callback) {
    for (var name of MUSIC) {
      this.music[name] = new Howl({
        src: [require(`assets/${name}.webm`), require(`assets/${name}.mp3`)],
        loop: true
      })
    }
    for (name of TEXTURES) {
      PIXI.loader.add(name, require(`assets/${name}.png`))
    }
    PIXI.loader.once('complete', () => {
      for (name of TEXTURES) {
        this.textures[name] = PIXI.loader.resources[name].texture
      }
      callback()
    })
    PIXI.loader.load()
  }

  init () {
    this.engine = new PIXI.Application(WIDTH, HEIGHT, {
      view: this.canvas,
      antialias: true
    })
    this.world = new PIXI.Container()
    this.socket = new Socket()
    this.engine.stage.addChild(this.world)
    this.size()
    this.stars = new PIXI.Sprite(this.textures['stars'])
    this.stars.anchor.x = 0.5
    this.stars.anchor.y = 0.5
    this.stars.scale.x = 5
    this.stars.scale.y = 5
    this.world.addChild(this.stars)
    this.planet = new PIXI.Sprite(this.textures['planet'])
    this.planet.anchor.x = 0.5
    this.planet.anchor.y = 0.5
    this.planet.scale.x = 0.1
    this.planet.scale.y = 0.1
    this.world.addChild(this.planet)
    this.channels = []
    for (var name of MUSIC) {
      let id = this.music[name].play()
      this.music[name].volume(0, id)
      this.channels.push(id)
    }
    Leap.loop({}, (frame) => this.loop(frame.timestamp, frame.hands))
  }

  size () {
    this.world.position.x = this.engine.renderer.width / 2
    this.world.position.y = this.engine.renderer.height / 2
    let ratio = this.canvas.scrollWidth / this.canvas.scrollHeight
    if (ratio < RATIO) {
      this.world.scale.y = ratio / RATIO
    }
    if (ratio > RATIO) {
      this.world.scale.x = RATIO / ratio
    }
  }

  loop (ms, hands) {
    let alive = []
    let spin = 0
    let zoom = 0
    let tx = 0
    let ty = 0
    hands.forEach(hand => {
      if (hand.valid && hand.confidence > 0.3) {
        let entity = this.entities[hand.id] || this.spawnHand(hand.id, hand.type)
        alive.push(hand.id.toString())
        entity.position = hand.palmPosition
        entity.rotation = [hand.pitch(), hand.roll(), hand.yaw()]
        entity.pinch = hand.pinchStrength
        entity.grab = hand.grabStrength
        if (entity.pinch < 0.5 && entity.grab < 0.5) {
          if (hand.type === 'left') {
            spin += entity.rotation[0]
            zoom -= entity.rotation[1]
            tx += entity.rotation[1]
            ty -= entity.rotation[0]
          } else {
            spin -= entity.rotation[0]
            zoom += entity.rotation[1]
            tx += entity.rotation[1]
            ty -= entity.rotation[0]
          }
        }
        if (entity.grab > 0.7) {
          let volume = (entity.position[1] - 50) / 400.0
          if (volume < 0) {
            volume = 0
          } else if (volume > 1) {
            volume = 1
          }
          this.socket.send('volume', volume)
          if (hand.type === 'left') {
            this.music[MUSIC[0]].volume(volume, this.channels[0])
          } else {
            this.music[MUSIC[1]].volume(volume, this.channels[1])
          }
        }
        entity.update(ms)
      }
    })
    for (var id in this.entities) {
      if (alive.indexOf(id) < 0) {
        this.entities[id].remove(this.world)
        delete this.entities[id]
      }
    }
    this.stars.rotation += spin * 0.01
    this.planet.rotation += spin * 0.01
    this.planet.scale.x += zoom * 0.001
    this.planet.scale.y += zoom * 0.001
    this.planet.position.x += tx
    this.planet.position.y += ty
  }

  fini () {
    for (var id in this.entities) {
      this.entities[id].remove(this.world)
      delete this.entities[id]
    }
    for (var name of TEXTURES) {
      this.textures[name].destroy(true)
      delete this.textures[name]
    }
    for (name of MUSIC) {
      this.music[name].unload()
    }
    PIXI.loader.reset()
    this.world.destroy()
    this.engine.destroy()
    window.room = undefined
  }

  spawnHand (id, type) {
    this.entities[id] = new Hand(this.textures, type === 'left')
    this.entities[id].add(this.world)
    return this.entities[id]
  }
}

export default Room
<commit_msg>trying out gestures triggers<commit_after>/* global PIXI */
import 'pixi.js'
import 'pixi-particles'

import Leap from 'leapjs'
import { Howl } from 'howler'

import Hand from 'entities/hand.js'

import Socket from './socket'

const WIDTH = 1200
const HEIGHT = 675
const RATIO = WIDTH / HEIGHT

const MUSIC = [
  'bensound-dubstep',
  'bensound-moose'
]

const TEXTURES = [
  'open',
  'closed',
  'point',
  'pinch',
  'stars',
  'planet',
  'moon',
  'particle'
]

class Room {
  constructor (elementId, data) {
    window.room = this
    this.data = data
    this.canvas = document.getElementById(elementId)
    this.textures = {}
    this.music = {}
    this.entities = {}
  }

  load (callback) {
    for (var name of MUSIC) {
      this.music[name] = new Howl({
        src: [require(`assets/${name}.webm`), require(`assets/${name}.mp3`)],
        loop: true
      })
    }
    for (name of TEXTURES) {
      PIXI.loader.add(name, require(`assets/${name}.png`))
    }
    PIXI.loader.once('complete', () => {
      for (name of TEXTURES) {
        this.textures[name] = PIXI.loader.resources[name].texture
      }
      callback()
    })
    PIXI.loader.load()
  }

  init () {
    this.engine = new PIXI.Application(WIDTH, HEIGHT, {
      view: this.canvas,
      antialias: true
    })
    this.world = new PIXI.Container()
    this.socket = new Socket()
    this.engine.stage.addChild(this.world)
    this.size()
    this.stars = new PIXI.Sprite(this.textures['stars'])
    this.stars.anchor.x = 0.5
    this.stars.anchor.y = 0.5
    this.stars.scale.x = 5
    this.stars.scale.y = 5
    this.world.addChild(this.stars)
    this.planet = new PIXI.Sprite(this.textures['planet'])
    this.planet.anchor.x = 0.5
    this.planet.anchor.y = 0.5
    this.planet.scale.x = 0.1
    this.planet.scale.y = 0.1
    this.world.addChild(this.planet)
    this.channels = []
    for (var name of MUSIC) {
      let id = this.music[name].play()
      this.music[name].volume(0, id)
      this.channels.push(id)
    }
    Leap.loop({}, (frame) => this.loop(frame.timestamp, frame.hands, frame.gestures))
  }

  size () {
    this.world.position.x = this.engine.renderer.width / 2
    this.world.position.y = this.engine.renderer.height / 2
    let ratio = this.canvas.scrollWidth / this.canvas.scrollHeight
    if (ratio < RATIO) {
      this.world.scale.y = ratio / RATIO
    }
    if (ratio > RATIO) {
      this.world.scale.x = RATIO / ratio
    }
  }

  loop (ms, hands, gestures) {
    let alive = []
    let spin = 0
    let zoom = 0
    let tx = 0
    let ty = 0
    hands.forEach(hand => {
      if (hand.valid && hand.confidence > 0.3) {
        let entity = this.entities[hand.id] || this.spawnHand(hand.id, hand.type)
        alive.push(hand.id.toString())
        entity.position = hand.palmPosition
        entity.rotation = [hand.pitch(), hand.roll(), hand.yaw()]
        entity.pinch = hand.pinchStrength
        entity.grab = hand.grabStrength
        if (entity.pinch < 0.5 && entity.grab < 0.5) {
          if (hand.type === 'left') {
            spin += entity.rotation[0]
            zoom -= entity.rotation[1]
            tx += entity.rotation[1]
            ty -= entity.rotation[0]
          } else {
            spin -= entity.rotation[0]
            zoom += entity.rotation[1]
            tx += entity.rotation[1]
            ty -= entity.rotation[0]
          }
        }
        if (entity.grab > 0.7) {
          let volume = (entity.position[1] - 50) / 400.0
          if (volume < 0) {
            volume = 0
          } else if (volume > 1) {
            volume = 1
          }
          this.socket.send('volume', volume)
          if (hand.type === 'left') {
            this.music[MUSIC[0]].volume(volume, this.channels[0])
          } else {
            this.music[MUSIC[1]].volume(volume, this.channels[1])
          }
        }
        entity.update(ms)
      }
    })
    for (var id in this.entities) {
      if (alive.indexOf(id) < 0) {
        this.entities[id].remove(this.world)
        delete this.entities[id]
      }
    }
    this.stars.rotation += spin * 0.01
    this.planet.rotation += spin * 0.01
    this.planet.scale.x += zoom * 0.001
    this.planet.scale.y += zoom * 0.001
    this.planet.position.x += tx
    this.planet.position.y += ty

    if (gestures.length > 0) {
      var g = gestures[0]
      if (g.type === 'swipe' && g.state === 'stop') {
        console.log(gestures)
        var xMov = Math.abs(g.direction[0])
        // var yMov = Math.abs(g.direction[1])
        if (xMov > 0.3) {
          if (g.direction[0] < 0) {
            console.log('left')
          } else {
            console.log('right')
          }
        }
      }
    }
  }

  fini () {
    for (var id in this.entities) {
      this.entities[id].remove(this.world)
      delete this.entities[id]
    }
    for (var name of TEXTURES) {
      this.textures[name].destroy(true)
      delete this.textures[name]
    }
    for (name of MUSIC) {
      this.music[name].unload()
    }
    PIXI.loader.reset()
    this.world.destroy()
    this.engine.destroy()
    window.room = undefined
  }

  spawnHand (id, type) {
    this.entities[id] = new Hand(this.textures, type === 'left')
    this.entities[id].add(this.world)
    return this.entities[id]
  }
}

export default Room
<|endoftext|>


<commit_before>#!/usr/bin/env node
var argv = require('yargs')
    .count('verbose')
    .alias('v', 'verbose')
    .argv;

VERBOSE_LEVEL = argv.verbose;

function WARN()  { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); }
function INFO()  { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); }
function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); }

// WARN("Showing only important stuff");
// INFO("Showing semi-important stuff too");
// DEBUG("Extra chatty mode");

const main = require('./main')
const assert = require('assert')
const uuid = require('uuid')
const path = require('path')
const fs = require('fs')
const app = process.argv[2]
const title = process.argv[3]

const screenshotsDir = argv.screenshotsDir || 'screenshots'
const sessionId = argv.live ? uuid.v4() : '.'
const dir = path.join(process.cwd(), screenshotsDir, sessionId)

try {
    fs.mkdirSync(dir)
} catch (err) {
    if (/EEXIST: file already exists/.test(err.message)) {
        DEBUG('Directory already exists')
    } else {
        console.error(err)
        process.exit(1)
    }
}

//const screenshotById = (winId, dir, format) => screencapture(winId, dir, format)

function filterEmptyTitle(obj) {
    if (obj.title === '') return false
    return true
}

        // [ { winid: 2438,
        //     app: 'Google Chrome',
        //     title: 'Logfile by z-vr · Pull Request #1 · Sobesednik/browsershot',
        //     pid: 372 } ]

function screenshotWindow(winId, dir, live, i) {
    DEBUG('screenshot window winid %s live %s %i', winId, live, i)
    const index = (live) ? i || 1 : null
    return main.screenshotById(winId, dir, index, argv.cursor) // make cursor part of aruments
        .then((res) => {
            WARN(res)
            if (live) {
                return screenshotWindow(winId, dir, live, index + 1)
            }
            return res
        })
}

function getWindow(app, title, filterTitle, live) {
    DEBUG('get window app %s title %s filterTable %s live %s', app, title, filterTitle, live)
    let cachedWinId

    return main.getWindows(app, title)
        .then(res => {
            if (filterTitle) {
                return res.filter(filterEmptyTitle)
            }
            return res
        })
        .then(res => {
            assert(Array.isArray(res))
            assert(res.length)
            return res
        })
        .then(res => res[0])
        .then(res => {
            assert(res.winid, 'Window must have a winid')
            cachedWinId = res.winid
            return cachedWinId
        })
        .then(res => screenshotWindow(res, dir, live))
        .then((res) => {
            console.log(res)
        })
}

function getList(app, title, filterTitle, live) {
    DEBUG('get list app %s title %s filterTable %s live %s', app, title, filterTitle, live)
    return main.getWindows(app, title)
        .then(res => {
            if (filterTitle) {
                return res.filter(filterEmptyTitle)
            }
            return res
        })
        .then((res) => {
            console.log(res)
            return live ? getList(app, title, filterTitle, live) : res
        })
}

DEBUG(123)

const fn = argv.capture ? getWindow : getList
const exec = fn.bind(null, argv.app, argv.title, !argv.all, argv.live)

exec()

<commit_msg>remove semicolons<commit_after>#!/usr/bin/env node
var argv = require('yargs')
    .count('verbose')
    .alias('v', 'verbose')
    .argv

VERBOSE_LEVEL = argv.verbose

function WARN()  { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments) }
function INFO()  { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments) }
function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments) }

// WARN("Showing only important stuff");
// INFO("Showing semi-important stuff too");
// DEBUG("Extra chatty mode");

const main = require('./main')
const assert = require('assert')
const uuid = require('uuid')
const path = require('path')
const fs = require('fs')
const app = process.argv[2]
const title = process.argv[3]

const screenshotsDir = argv.screenshotsDir || 'screenshots'
const sessionId = argv.live ? uuid.v4() : '.'
const dir = path.join(process.cwd(), screenshotsDir, sessionId)

try {
    fs.mkdirSync(dir)
} catch (err) {
    if (/EEXIST: file already exists/.test(err.message)) {
        DEBUG('Directory already exists')
    } else {
        console.error(err)
        process.exit(1)
    }
}

//const screenshotById = (winId, dir, format) => screencapture(winId, dir, format)

function filterEmptyTitle(obj) {
    if (obj.title === '') return false
    return true
}

        // [ { winid: 2438,
        //     app: 'Google Chrome',
        //     title: 'Logfile by z-vr · Pull Request #1 · Sobesednik/browsershot',
        //     pid: 372 } ]

function screenshotWindow(winId, dir, live, i) {
    DEBUG('screenshot window winid %s live %s %i', winId, live, i)
    const index = (live) ? i || 1 : null
    return main.screenshotById(winId, dir, index, argv.cursor) // make cursor part of aruments
        .then((res) => {
            WARN(res)
            if (live) {
                return screenshotWindow(winId, dir, live, index + 1)
            }
            return res
        })
}

function getWindow(app, title, filterTitle, live) {
    DEBUG('get window app %s title %s filterTable %s live %s', app, title, filterTitle, live)
    let cachedWinId

    return main.getWindows(app, title)
        .then(res => {
            if (filterTitle) {
                return res.filter(filterEmptyTitle)
            }
            return res
        })
        .then(res => {
            assert(Array.isArray(res))
            assert(res.length)
            return res
        })
        .then(res => res[0])
        .then(res => {
            assert(res.winid, 'Window must have a winid')
            cachedWinId = res.winid
            return cachedWinId
        })
        .then(res => screenshotWindow(res, dir, live))
        .then((res) => {
            console.log(res)
        })
}

function getList(app, title, filterTitle, live) {
    DEBUG('get list app %s title %s filterTable %s live %s', app, title, filterTitle, live)
    return main.getWindows(app, title)
        .then(res => {
            if (filterTitle) {
                return res.filter(filterEmptyTitle)
            }
            return res
        })
        .then((res) => {
            console.log(res)
            return live ? getList(app, title, filterTitle, live) : res
        })
}

DEBUG(123)

const fn = argv.capture ? getWindow : getList
const exec = fn.bind(null, argv.app, argv.title, !argv.all, argv.live)

exec()

<|endoftext|>


<commit_before>window.onscroll=function(e){
	var pagenav=document.getElementById('pagenav'), css=pagenav.getAttribute('class');
	if(document.body.scrollTop>470){
		if(css.indexOf("navbar-inverse")<0){
			pagenav.setAttribute("class",css.trim()+" navbar-inverse");
		}
	}else{
		pagenav.setAttribute("class",css.replace("navbar-inverse","").trim());
	}
};
<commit_msg>Update site.js<commit_after>window.onscroll=function(e){
	var pagenav=document.getElementById('pagenav'), css=pagenav.getAttribute('class');
	if(document.body.scrollTop>520){
		if(css.indexOf("navbar-inverse")<0){
			pagenav.setAttribute("class",css.trim()+" navbar-inverse");
		}
	}else{
		pagenav.setAttribute("class",css.replace("navbar-inverse","").trim());
	}
};
<|endoftext|>


<commit_before>/** @enum {number} */
MP4.Tags.Identifiers = {
  ESDescriptor: 0x03,
  DecConfigDescriptor: 0x04
};

/** @type {Object.<number,string>} */
MP4.Tags.ObjectTypes = /** @dict */ {
  0x40: "aac",
  0x66: "aac",
  0x67: "aac",
  0x68: "aac",
  0x69: "mp3",
  0x6b: "mp3",
  0xa5: "ac3",
  0xa9: "dts",
  0xdd: "vorbis"
};

/**
 * MP4 Descriptor tag
 * @param {DataView} data
 * @param {number=} offset
 * @constructor
 */
MP4.Tags.Descriptor = function(data, offset) {
  offset = offset || 0;
  this.type = data.getUint8(offset);
  this.size = 0;
  this.headerSize = 1;
  this.dataSize = 0;

  var count = 4;
  while (this.headerSize++, count--) {
    var c = data.getUint8(offset+1+(3-count));
    this.size = (this.size << 7) | (c & 0x7f);
    if (!(c & 0x80)) break;
  }
};

/**
 * MP4 Elementary Stream Descriptor
 * @param {DataView} data
 * @param {number=} offset
 * @constructor
 * @extends MP4.Tags.Descriptor
 */
MP4.Tags.ESDescriptor = function(data, offset) {
  offset = offset || 0;
  MP4.Tags.Descriptor.call(this, data, offset);

  if (this.type !== MP4.Tags.Identifiers.ESDescriptor) {
    this.dataSize = this.size-this.headerSize;
    return;
  }

  offset += this.headerSize;
  this.dataSize = 3; // = [id (2 bytes)]+[flags (2 bytes)]

  var flags = data.getUint8(offset+2);

  if (flags & 0x80) this.dataSize += 2;
  if (flags & 0x40) this.dataSize += 1+data.getUint8(offset+this.dataSize);
  if (flags & 0x20) this.dataSize += 2;
};

/**
 * MP4 Decoder Configuration Descriptor
 * @param {DataView} data
 * @param {number=} offset
 * @constructor
 * @extends MP4.Tags.Descriptor
 */
MP4.Tags.DecConfigDescriptor = function(data, offset) {
  offset = offset || 0;
  MP4.Tags.Descriptor.call(this, data, offset);

  if (this.type !== MP4.Tags.Identifiers.DecConfigDescriptor) {
    this.objectType = null;
    this.dataSize = this.size-this.headerSize;
    return;
  }

  offset += this.headerSize;
  this.objectType = data.getUint8(offset);
  this.dataSize = 13;
};
<commit_msg>Report 'mp3' as '.mp3' (consistent with media type descriptor)<commit_after>/** @enum {number} */
MP4.Tags.Identifiers = {
  ESDescriptor: 0x03,
  DecConfigDescriptor: 0x04
};

/** @type {Object.<number,string>} */
MP4.Tags.ObjectTypes = /** @dict */ {
  0x40: "aac",
  0x66: "aac",
  0x67: "aac",
  0x68: "aac",
  0x69: ".mp3",
  0x6b: ".mp3",
  0xa5: "ac3",
  0xa9: "dts",
  0xdd: "vorbis"
};

/**
 * MP4 Descriptor tag
 * @param {DataView} data
 * @param {number=} offset
 * @constructor
 */
MP4.Tags.Descriptor = function(data, offset) {
  offset = offset || 0;
  this.type = data.getUint8(offset);
  this.size = 0;
  this.headerSize = 1;
  this.dataSize = 0;

  var count = 4;
  while (this.headerSize++, count--) {
    var c = data.getUint8(offset+1+(3-count));
    this.size = (this.size << 7) | (c & 0x7f);
    if (!(c & 0x80)) break;
  }
};

/**
 * MP4 Elementary Stream Descriptor
 * @param {DataView} data
 * @param {number=} offset
 * @constructor
 * @extends MP4.Tags.Descriptor
 */
MP4.Tags.ESDescriptor = function(data, offset) {
  offset = offset || 0;
  MP4.Tags.Descriptor.call(this, data, offset);

  if (this.type !== MP4.Tags.Identifiers.ESDescriptor) {
    this.dataSize = this.size-this.headerSize;
    return;
  }

  offset += this.headerSize;
  this.dataSize = 3; // = [id (2 bytes)]+[flags (2 bytes)]

  var flags = data.getUint8(offset+2);

  if (flags & 0x80) this.dataSize += 2;
  if (flags & 0x40) this.dataSize += 1+data.getUint8(offset+this.dataSize);
  if (flags & 0x20) this.dataSize += 2;
};

/**
 * MP4 Decoder Configuration Descriptor
 * @param {DataView} data
 * @param {number=} offset
 * @constructor
 * @extends MP4.Tags.Descriptor
 */
MP4.Tags.DecConfigDescriptor = function(data, offset) {
  offset = offset || 0;
  MP4.Tags.Descriptor.call(this, data, offset);

  if (this.type !== MP4.Tags.Identifiers.DecConfigDescriptor) {
    this.objectType = null;
    this.dataSize = this.size-this.headerSize;
    return;
  }

  offset += this.headerSize;
  this.objectType = data.getUint8(offset);
  this.dataSize = 13;
};
<|endoftext|>


<commit_before>//cvjs Text
cvjs.prototype.Text = function(o)
{
	//Set the opacity
	if(typeof o.opacity !== 'undefined'){ this.ctx.globalAlpha = o.opacity; }

	//Get the font size
	var size = (typeof o.size !== 'undefined')? o.size.toString().replace('px', '') + 'px' : '16px';

	//Get the font family
	var font = (typeof o.font !== 'undefined')? o.font : 'Arial';

	//Add the font style
	this.ctx.font = size + ' ' + font;

	//Add the text baseline  alphabetic|top|hanging|middle|ideographic|bottom
	if(typeof o.base !== 'undefined'){ this.ctx.textBaseline = o.base; }

	//Add the font color
	if(typeof o.color !== 'undefined'){ this.ctx.fillStyle = o.color; }

	//Check the align  center|end|left|right|start
	if(typeof o.align !== 'undefined'){ this.ctx.textAlign = o.align; }

	//Check for max width
	if(typeof o.mwidth !== 'undefined')
	{
		//Add the text with maxwidth
		this.ctx.fillText(o.text, o.x, o.y, o.mwidth);
	}
	else
	{
		//Add the text
		this.ctx.fillText(o.text, o.x, o.y);
	}

	//Reset the global alpha
	this.ctx.globalAlpha = 1;
};
<commit_msg>Fix bug<commit_after>//cvjs Text
cvjs.prototype.Text = function(o)
{
	//Set the opacity
	if(typeof o.opacity !== 'undefined'){ this.ctx.globalAlpha = o.opacity; }

	//Get the font size
	var size = (typeof o.size !== 'undefined')? o.size.toString().replace('px', '') + 'px' : '16px';

	//Get the font family
	var font = (typeof o.font !== 'undefined')? o.font : 'Arial';

	//Add the font style
	this.ctx.font = size + ' ' + font;

	//Add the text baseline  alphabetic|top|hanging|middle|ideographic|bottom
	if(typeof o.base !== 'undefined')
	{
		//Set the user baseline
		this.ctx.textBaseline = o.base;
	}
	else
	{
		//Set the default baseline
		this.ctx.textBaseline = 'top';
	}

	//Add the font color
	if(typeof o.color !== 'undefined'){ this.ctx.fillStyle = o.color; }

	//Check the align  center|end|left|right|start
	if(typeof o.align !== 'undefined'){ this.ctx.textAlign = o.align; }

	//Check for max width
	if(typeof o.mwidth !== 'undefined')
	{
		//Add the text with maxwidth
		this.ctx.fillText(o.text, o.x, o.y, o.mwidth);
	}
	else
	{
		//Add the text
		this.ctx.fillText(o.text, o.x, o.y);
	}

	//Reset the global alpha
	this.ctx.globalAlpha = 1;
};
<|endoftext|>


<commit_before>function Tool() {
	this.$$watchers = [];
}

Tool.prototype.$watch = function(watchFn, listenerFn) {
	var watcher = {
		watchFn: watchFn,
		listenerFn: listenerFn,
		lastVal: null
	}

	this.$$watchers.push(watcher);
}

Tool.prototype.$digest = function() {
	var self = this;

	for (var watch in this.$$watchers) {
		var newVal = watch.watchFn(self);
		var oldVal = watch.last;
		if (newVal !== oldVal) {
			watch.listenerFn(newVal, oldVal, self);
			watch.last = newVal;
		}
	}
}

function has (obj, key) {
	return Object.prototype.hasOwnProperty.call(obj, key);
}<commit_msg>added digestOnce<commit_after>function Tool() {
	this.$$watchers = [];
}

Tool.prototype.$watch = function(watchFn, listenerFn) {
	var watcher = {
		watchFn: watchFn,
		listenerFn: listenerFn,
		lastVal: null
	}

	this.$$watchers.push(watcher);
}

Tool.prototype.$digest = function() {
	var self = this;

	for (var watch in this.$$watchers) {
		var newVal = watch.watchFn(self);
		var oldVal = watch.last;
		if (newVal !== oldVal) {
			watch.listenerFn(newVal, oldVal, self);
			watch.last = newVal;
		}
	}
}

Tool.prototype.$$digestOnce = function() {
	var self = this,
		dirty;

	for (var t in this.$$watchers) {
		var newVal = watch.watchFn(self);
		var oldVal = watch.last;

		if (newVal !== oldVal) {
			watch.listenerFn(newVal, oldVal);
			dirty = true;
			watch.last = newVal;
		}
	}

	return dirty;
}

function has (obj, key) {
	return Object.prototype.hasOwnProperty.call(obj, key);
}<|endoftext|>


<commit_before>"use strict";

/**
 * Creates a new tree, with a parent node and its direct children.
 *
 * @param {Any} node - the parent/root node of the tree.
 * @param {Tree[]} [children] - the children of the root, each of them subtrees.
 * @return {Tree}
 */
function Tree (node, children) {
    if ( children === undefined ) {
        children = [];
    } else if ( !children.length ) {
        children = [ children ];
    }
    /**
     * A recursive tree data structure.
     *
     * @typedef Tree
     * @property {String} borjes - 'tree'
     * @property {Any} node - the (unboxed) root of the tree.
     * @property {Tree[]} children - the subtrees children of the root.
     */
    return {
        borjes: 'tree',
        node: node,
        children: children
    };
}

/**
 * Adds some children to the root node of a tree.
 *
 * @param {Tree} tree
 * @param {Tree[]} children
 */
Tree.add_children = function (tree, children) {
    tree.children = tree.children.concat(children);
};

var id = function (x) { return x; };

/**
 * Converts a tree into a sexp, that is an array where the first element is the
 * root of the tree, and the next elements are sexp's corresponding to the
 * children of the root.
 *
 * @param {Tree} tree
 * @param {function} map - this function can be used to transform the tree nodes
 * before including them in the sexp. It must take an object (the node) and
 * return another object (what to include in the sexp array).
 * @return {Any[]}
 */
Tree.to_sexp = function (tree, map) {
    if (map === undefined) { map = id; }
    var sexp = [ map(tree.node) ];
    for (var i=0; i<tree.children.length; i++) {
        sexp.push(Tree.to_sexp(tree.children[i], map));
    }
    return sexp;
};

module.exports = Tree;
<commit_msg>Tree children need not be trees themselves<commit_after>"use strict";

/**
 * Creates a new tree, with a parent node and its direct children.
 *
 * @param {Any} node - the parent/root node of the tree.
 * @param {Borjes[]} [children] - the children of the root.
 * @return {Tree}
 */
function Tree (node, children) {
    if ( children === undefined ) {
        children = [];
    } else if ( !children.length ) {
        children = [ children ];
    }
    /**
     * A recursive tree data structure.
     *
     * @typedef Tree
     * @property {String} borjes - 'tree'
     * @property {Any} node - the (unboxed) root of the tree.
     * @property {Tree[]} children - the subtrees children of the root.
     */
    return {
        borjes: 'tree',
        node: node,
        children: children
    };
}

/**
 * Adds some children to the root node of a tree.
 *
 * @param {Tree} tree
 * @param {Borjes[]} children
 */
Tree.add_children = function (tree, children) {
    tree.children = tree.children.concat(children);
};

var id = function (x) { return x; };

/**
 * Converts a tree into a sexp, that is an array where the first element is the
 * root of the tree, and the next elements are sexp's corresponding to the
 * children of the root.
 *
 * @param {Tree} tree
 * @param {function} map - this function can be used to transform the tree nodes
 * before including them in the sexp. It must take an object (the node) and
 * return another object (what to include in the sexp array).
 * @return {Any[]}
 */
Tree.to_sexp = function (tree, map) {
    if (map === undefined) { map = id; }
    if (tree.borjes !== 'tree') {
        return map(tree);
    }
    var sexp = [ map(tree.node) ];
    for (var i=0; i<tree.children.length; i++) {
        sexp.push(Tree.to_sexp(tree.children[i], map));
    }
    return sexp;
};

module.exports = Tree;
<|endoftext|>