<commit_before>import React, { Component, PropTypes, View, Text, TouchableHighlight } from 'react-native';
import Icon from '../Icon';
import { TYPO } from '../config';

export default class Item extends Component {

    static propTypes = {
        icon: PropTypes.string,
        value: PropTypes.string.isRequired,
        onPress: PropTypes.func,
        active: PropTypes.bool,
        disabled: PropTypes.bool
    };

    static defaultProps = {
        active: false,
        disabled: false
    };

    render() {
        const { icon, value, onPress } = this.props;

        return (
            <TouchableHighlight
                onPress={onPress}
                underlayColor={'#e8e8e8'}
                style={styles.touchable}
            >
                <View style={styles.item}>
                    <Icon
                        name={icon}
                        color={'rgba(0,0,0,.54)'}
                        size={22}
                        style={styles.icon}
                    />
                    <View style={styles.value}>
                        <Text style={[TYPO.paperFontBody2, { color: 'rgba(0,0,0,.87)' }]}>
                            {value}
                        </Text>

                    </View>
                </View>
            </TouchableHighlight>

        );
    }
}

const styles = {
    touchable: {
        paddingHorizontal: 16,
        marginVertical: 8,
        height: 48
    },
    item: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
    },
    icon: {
        position: 'relative',
    },
    value: {
        flex: 1,
        paddingLeft: 34,
        top: 2
    }
};<commit_msg>Drawer menu items with label support<commit_after>import React, { Component, PropTypes, View, Text, TouchableHighlight } from 'react-native';
import Icon from '../Icon';
import { TYPO } from '../config';

export default class Item extends Component {

    static propTypes = {
        icon: PropTypes.string,
        value: PropTypes.string.isRequired,
        label: PropTypes.string,
        onPress: PropTypes.func,
        active: PropTypes.bool,
        disabled: PropTypes.bool
    };

    static defaultProps = {
        active: false,
        disabled: false
    };

    render() {
        const { icon, value, label, onPress } = this.props;

        return (
            <TouchableHighlight
                onPress={onPress}
                underlayColor={'#e8e8e8'}
                style={styles.touchable}
            >
                <View style={styles.item}>
                    <Icon
                        name={icon}
                        color={'rgba(0,0,0,.54)'}
                        size={22}
                        style={styles.icon}
                    />
                    <View style={styles.value}>
                        <Text style={[TYPO.paperFontBody2, { color: 'rgba(0,0,0,.87)' }]}>
                            {value}
                        </Text>

                    </View>
                    <View style={styles.label}>
                        <Text style={[TYPO.paperFontBody2, { color: 'rgba(0,0,0,.87)' }]}>
                            {label}
                        </Text>
                    </View>
                </View>
            </TouchableHighlight>

        );
    }
}

const styles = {
    touchable: {
        paddingHorizontal: 16,
        marginVertical: 8,
        height: 48
    },
    item: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
    },
    icon: {
        position: 'relative',
    },
    value: {
        flex: 1,
        paddingLeft: 34,
        top: 2
    },
    label: {
        top: 2
    }
};<|endoftext|>


<commit_before>require('./logging');
var mqtt = require('mqtt');
var Web3 = require('web3');
var lightwallet = require('eth-lightwallet');
var HookedWeb3Provider = require("hooked-web3-provider");
var fs = require('fs');

var membershipcontract = require('../app/contracts/LocalsMembership.json');
var membershipcontractaddress = "0x83883514f7fcb0cf627829d067f0e8488201f6b9";
var host = "http://kingflurkel.dtdns.net:8545";
var keystoreFile = "adamswallet.json";

var validationcontract = require('../app/contracts/LocalsValidation.json');

web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(host));

var contents = fs.readFileSync(keystoreFile, 'utf8');
var global_keystore = lightwallet.keystore.deserialize(contents);

global_keystore.passwordProvider = function(callback) {
  callback(null, 'testing')
};

console.log("Your wallet accounts:",global_keystore.getAddresses());

var account = fixaddress(global_keystore.getAddresses()[0].toString());
console.log('Your first account is ', account);

web3 = new Web3();
var provider = new HookedWeb3Provider({
  host: host,
  transaction_signer: global_keystore
});
web3.setProvider(provider);

web3_monitor = new Web3();
web3_monitor.setProvider(new web3.providers.HttpProvider(host));

var gasPrice;

web3.eth.getGasPrice(function(err, result) {

  gasPrice = result.toNumber(10);
  console.log('gasprice is ', gasPrice);

  connectMQTT();
  printBalance(account);

});

function connectMQTT() {

  console.log('connecting MQTT now');

  var client = mqtt.connect('ws://opantwerpen.be:15674');

  client.on('connect', function() {
    console.log('Adam is connected');
    client.subscribe('adam');
  });

  client.on('message', function(topic, message) {
    // message is Buffer
    console.log('Adam received a message');
    console.log(message.toString());

    var msg = message.toString();

    var commandarray = msg.split("|");

    console.log(commandarray);
    switch (commandarray[0]) {
      case "requestmembership":
        var memberaddress = fixaddress(commandarray[1]);
        console.log('requestmembership for address ', memberaddress);

        if (isMember(memberaddress)) {
          console.log('already a member');
        } else {
          console.log('not a member yet');
          // TODO : maak hem member...
          requestMembership(memberaddress);
        }
        break;
      case "validate":
        var contractaddress = fixaddress(commandarray[3]);
        console.log('validate for contractaddress ', contractaddress);
        validate(contractaddress, function(err, res) {
          console.log('validated');
        });
        break;

      default:
        console.log('unknown command:', commandarray[0]);
        break;
    }
  });
}

var MyContract = web3.eth.contract(membershipcontract.abi);
var myContractInstance = MyContract.at(membershipcontractaddress);

myContractInstance.MemberAdded(function(err, res) {

  console.log('MEMBERADDED triggered SUSKE');
  console.log('err', err);
  console.log('res', res);
  printBalance(account);

});

function validate(contractaddress, cb) {

  web3.eth.getGasPrice(function(err, result) {

    var gasPrice = result.toNumber(10);

    // creation of contract object
    var Myvalidationcontract = web3.eth.contract(validationcontract.abi);
    var myContractInstance = Myvalidationcontract.at(contractaddress);

    var options = {
      from: account,
      value: 3.5 * 1e18,
      gas: 3141590,
      gasPrice: gasPrice,
      nonce: Math.floor(Math.random(999999)) + new Date().getTime(),
    };

    console.log('contract to validate ', contractaddress);
    console.log('contract options', options);

    var result = myContractInstance.addValidation.sendTransaction(options,
      function(err, result) {
        if (err != null) {
          console.log(err);
          console.log("ERROR: Transaction didn't go through. See console.");
        } else {
          console.log("Transaction Successful!");
          console.log(result);
        }
      }
    );

    myContractInstance.ValidationAdded(function(err, res) {

      console.log('ValidationAdded triggered SUSKE');
      console.log('err', err);
      console.log('res', res);

      cb(err, res);

    });
  });

}

function isMember(address) {
  //  var MyContract = web3.eth.contract(membershipcontract.abi);
  //  var myContractInstance = MyContract.at(membershipcontractaddress);
  var r = myContractInstance.membershipStatus(address);
  console.log('membershipStatus voor', address, '=', r.toNumber(10));
  return (r.toNumber(10) != 0);
}

// Add 0x to address
function fixaddress(address) {
  if (!address.startsWith('0x')) {
    return ('0x' + address);
  }
  return address;
}

function requestMembership(address) {

  address = fixaddress(address);

  // var MyContract = web3.eth.contract(membershipcontract.abi);
  //console.log("Mycontract: ", MyContract);
  //  var myContractInstance = MyContract.at(membershipcontractaddress);

  var options = {
    from: account,
    value: 6 * 1e18,
    gas: 3141590,
    gasPrice: gasPrice,
    nonce: Math.floor(Math.random(999999)) + new Date().getTime(),
  };

  var newMember = fixaddress(address);

  console.log('adding member ', newMember);
  console.log('contract options', options);

  var result = myContractInstance.addMember.sendTransaction(newMember, options,
    function(err, result) {
      if (err != null) {
        console.log(err);
        console.log("ERROR: Transaction didn't go through. See console.");
      } else {
        console.log("Transaction Successful!");
        console.log("Transaction hash=", result);
        printBalance(account);
      }
    }
  );
}

function printBalance(account) {
  var wei = web3.eth.getBalance(account).toNumber(10);
  console.log('Account', account, 'has Ξ', web3.fromWei(wei, 'ether'));
}
<commit_msg>strange...<commit_after>require('./logging');
var mqtt = require('mqtt');
var Web3 = require('web3');
var lightwallet = require('eth-lightwallet');
var HookedWeb3Provider = require("hooked-web3-provider");
var fs = require('fs');

var membershipcontract = require('../app/contracts/LocalsMembership.json');
var membershipcontractaddress = "0x83883514f7fcb0cf627829d067f0e8488201f6b9";
var host = "http://kingflurkel.dtdns.net:8545";
var keystoreFile = "adamswallet.json";

var validationcontract = require('../app/contracts/LocalsValidation.json');

web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(host));

var contents = fs.readFileSync(keystoreFile, 'utf8');
var global_keystore = lightwallet.keystore.deserialize(contents);

global_keystore.passwordProvider = function(callback) {
  callback(null, 'testing')
};

console.log("Your wallet accounts:",global_keystore.getAddresses());
console.log("it s a",typeof global_keystore.getAddresses()[0]);

var account = fixaddress(global_keystore.getAddresses()[0].toString());
console.log('Your first account is ', account);

web3 = new Web3();
var provider = new HookedWeb3Provider({
  host: host,
  transaction_signer: global_keystore
});
web3.setProvider(provider);

web3_monitor = new Web3();
web3_monitor.setProvider(new web3.providers.HttpProvider(host));

var gasPrice;

web3.eth.getGasPrice(function(err, result) {

  gasPrice = result.toNumber(10);
  console.log('gasprice is ', gasPrice);

  connectMQTT();
  printBalance(account);

});

function connectMQTT() {

  console.log('connecting MQTT now');

  var client = mqtt.connect('ws://opantwerpen.be:15674');

  client.on('connect', function() {
    console.log('Adam is connected');
    client.subscribe('adam');
  });

  client.on('message', function(topic, message) {
    // message is Buffer
    console.log('Adam received a message');
    console.log(message.toString());

    var msg = message.toString();

    var commandarray = msg.split("|");

    console.log(commandarray);
    switch (commandarray[0]) {
      case "requestmembership":
        var memberaddress = fixaddress(commandarray[1]);
        console.log('requestmembership for address ', memberaddress);

        if (isMember(memberaddress)) {
          console.log('already a member');
        } else {
          console.log('not a member yet');
          // TODO : maak hem member...
          requestMembership(memberaddress);
        }
        break;
      case "validate":
        var contractaddress = fixaddress(commandarray[3]);
        console.log('validate for contractaddress ', contractaddress);
        validate(contractaddress, function(err, res) {
          console.log('validated');
        });
        break;

      default:
        console.log('unknown command:', commandarray[0]);
        break;
    }
  });
}

var MyContract = web3.eth.contract(membershipcontract.abi);
var myContractInstance = MyContract.at(membershipcontractaddress);

myContractInstance.MemberAdded(function(err, res) {

  console.log('MEMBERADDED triggered SUSKE');
  console.log('err', err);
  console.log('res', res);
  printBalance(account);

});

function validate(contractaddress, cb) {

  web3.eth.getGasPrice(function(err, result) {

    var gasPrice = result.toNumber(10);

    // creation of contract object
    var Myvalidationcontract = web3.eth.contract(validationcontract.abi);
    var myContractInstance = Myvalidationcontract.at(contractaddress);

    var options = {
      from: account,
      value: 3.5 * 1e18,
      gas: 3141590,
      gasPrice: gasPrice,
      nonce: Math.floor(Math.random(999999)) + new Date().getTime(),
    };

    console.log('contract to validate ', contractaddress);
    console.log('contract options', options);

    var result = myContractInstance.addValidation.sendTransaction(options,
      function(err, result) {
        if (err != null) {
          console.log(err);
          console.log("ERROR: Transaction didn't go through. See console.");
        } else {
          console.log("Transaction Successful!");
          console.log(result);
        }
      }
    );

    myContractInstance.ValidationAdded(function(err, res) {

      console.log('ValidationAdded triggered SUSKE');
      console.log('err', err);
      console.log('res', res);

      cb(err, res);

    });
  });

}

function isMember(address) {
  //  var MyContract = web3.eth.contract(membershipcontract.abi);
  //  var myContractInstance = MyContract.at(membershipcontractaddress);
  var r = myContractInstance.membershipStatus(address);
  console.log('membershipStatus voor', address, '=', r.toNumber(10));
  return (r.toNumber(10) != 0);
}

// Add 0x to address
function fixaddress(address) {
  if (!address.startsWith('0x')) {
    return ('0x' + address);
  }
  return address;
}

function requestMembership(address) {

  address = fixaddress(address);

  // var MyContract = web3.eth.contract(membershipcontract.abi);
  //console.log("Mycontract: ", MyContract);
  //  var myContractInstance = MyContract.at(membershipcontractaddress);

  var options = {
    from: account,
    value: 6 * 1e18,
    gas: 3141590,
    gasPrice: gasPrice,
    nonce: Math.floor(Math.random(999999)) + new Date().getTime(),
  };

  var newMember = fixaddress(address);

  console.log('adding member ', newMember);
  console.log('contract options', options);

  var result = myContractInstance.addMember.sendTransaction(newMember, options,
    function(err, result) {
      if (err != null) {
        console.log(err);
        console.log("ERROR: Transaction didn't go through. See console.");
      } else {
        console.log("Transaction Successful!");
        console.log("Transaction hash=", result);
        printBalance(account);
      }
    }
  );
}

function printBalance(account) {
  var wei = web3.eth.getBalance(account).toNumber(10);
  console.log('Account', account, 'has Ξ', web3.fromWei(wei, 'ether'));
}
<|endoftext|>


<commit_before>var FireGrapher = (function() {
  "use strict";

  FireGrapher = function () {
    return;
  };

  FireGrapher.prototype.graph = function (cssSelector, firebaseRef, config) {
    this.cssSelector = cssSelector;
    this.firebaseRef = firebaseRef;
    this.updateConfig(config);

    this.drawGraph();

    // Parse path
    var nodes = config.path.split("/");
    console.log(nodes);

    console.log("Parsing paths");
    this.parsePathNode(["/"], nodes, 0).then(function(paths) {
      console.log("Paths parsed");
      console.log(paths);
      paths.forEach(function(path) {
        console.log(path);
        this.firebaseRef.child(path).on("child_added", function(childSnapshot) {
          var data = childSnapshot.val();
          var pathParts = path.split("/");
          var lastPathPart = pathParts[pathParts.length - 2];

          var line;
          if (config.line[0] === "$") {
            line = lastPathPart;
          }
          else {
            line = data[config.line];
          }

          this.addToLineGraph({
            "line": line,
            "xCoord": data[config.xCoord.value],
            "yCoord": data[config.yCoord.value]
          });
        }.bind(this));
      }.bind(this));
    }.bind(this));
  };

  FireGrapher.prototype.parsePathNode = function(paths, nodes, nodeIndex) {
    return new RSVP.Promise(function(resolve) {
      console.log("Calling parsePathNode() with index " + nodeIndex);
      var node = nodes[nodeIndex];
      if (node[0] === "*") {
        console.assert(nodeIndex === nodes.length - 1, "WHATTTT?");
        console.log(nodeIndex + ": individual record");
        console.log(paths);
        resolve(paths);
      }
      else if (node[0] === "$") {
        console.log(nodeIndex + ": param");

        var pathPromises = [];
        paths.forEach(function(path) {
          pathPromises.push(new RSVP.Promise(function(subResolve) {
            console.log(path);
            this.firebaseRef.child(path).once("value", function(dataSnapshot) {
              console.log(dataSnapshot);
              var newPaths = [];

              dataSnapshot.forEach(function(childSnapshot) {
                console.log(childSnapshot.name());
                newPaths.push(path + childSnapshot.name() + "/");
              }.bind(this));

              subResolve(newPaths);
            }.bind(this));
          }.bind(this)));
        }.bind(this));

        new RSVP.all(pathPromises).then(function(promisesData) {
          var newPaths = [];
          promisesData.forEach(function(promiseData) {
            promiseData.forEach(function(path) {
              newPaths.push(path);
            });
          });
          console.log(newPaths);

          this.parsePathNode(newPaths, nodes, nodeIndex + 1).then(function(finalPaths) {
            console.log("Final paths: " + nodeIndex);
            console.log(finalPaths);
            resolve(finalPaths);
          });
        }.bind(this));
      }
      else {
        console.log(nodeIndex + ": regular node");

        var newPaths = [];
        paths.forEach(function(path) {
          newPaths.push(path += node + "/");
        });

        this.parsePathNode(newPaths, nodes, nodeIndex + 1).then(function(finalPaths) {
          console.log("Final paths: " + nodeIndex);
            console.log(finalPaths);
          resolve(finalPaths);
        });
      }
    }.bind(this));
  };

  FireGrapher.prototype.addToLineGraph = function(newDataPoint) {
    // create a set of data if not exists
    if (typeof this.graphData[newDataPoint.line] === "undefined") {
      this.graphData[newDataPoint.line] = [];
    }

    // Update the data at the datapoint
    this.graphData[newDataPoint.line][newDataPoint.xCoord] = newDataPoint.yCoord;
    var newConfig = { xCoord: {}, yCoord: {} };
    if (this.config.xCoord.min > newDataPoint.xCoord) {
      newConfig.xCoord.min = newDataPoint.xCoord;
    }
    if (this.config.xCoord.max < newDataPoint.xCoord) {
      newConfig.xCoord.max = newDataPoint.xCoord;
    }
    if (this.config.yCoord.min > newDataPoint.yCoord) {
      newConfig.yCoord.min = newDataPoint.yCoord;
    }
    if (this.config.yCoord.max < newDataPoint.yCoord) {
      newConfig.yCoord.max = newDataPoint.yCoord;
    }
    this.updateConfig(newConfig);
    if (newConfig.xCoord.min || newConfig.xCoord.max || newConfig.yCoord.min || newConfig.yCoord.max) {
      this.renderGraph();
    }

    // create a d3 line if one does not exist exists
    var line = this.graphLines[newDataPoint.line];
    if (typeof line === "undefined") {
      line = this.addLineToGraph(newDataPoint.line, this.graphData[newDataPoint.line]);
    }
    else {
      // update the line with the data
      this.graph.select(this.cssSelector + " path." + newDataPoint.line)
        .data([this.graphData[newDataPoint.line]])
        .attr("d", line);
    }
  };

  FireGrapher.prototype.updateConfig = function(config) {
    // build default config if not exists
    this.config = (this.config) ? this.config : {};
    this.config.type = (this.config.type) ? this.config.type : null;
    this.config.graph = (this.config.graph) ? this.config.graph : {};
    this.config.xCoord = (this.config.xCoord) ? this.config.xCoord : {};
    this.config.yCoord = (this.config.yCoord) ? this.config.yCoord : {};

    // set config to new values
    this.config.type = (config.type && ["grid", "line", "scatter"].indexOf(config.type) !== -1) ? config.type : (this.config.type) ? this.config.type : null;
    if (this.config.type === null) {
      throw new Error("Invalid chart type. Must be \"grid\", \"line\", or \"scatter\"");
    }
    this.config.graph = {
      width : (config.graph && config.graph.width) ? config.graph.width : (this.config.graph.width) ? this.config.graph.width : 500,
      height : (config.graph && config.graph.height) ? config.graph.height : (this.config.graph.height) ? this.config.graph.height : 150
    };
    this.config.xCoord = {
      min : (config.xCoord && config.xCoord.min) ? config.xCoord.min : (this.config.xCoord.min) ? this.config.xCoord.min : 0,
      max : (config.xCoord && config.xCoord.max) ? config.xCoord.max : (this.config.xCoord.max) ? this.config.xCoord.max : 50
    };
    this.config.yCoord = {
      min : (config.yCoord && config.yCoord.min) ? config.yCoord.min : (this.config.yCoord.min) ? this.config.yCoord.min : 0,
      max : (config.yCoord && config.yCoord.max) ? config.yCoord.max : (this.config.yCoord.max) ? this.config.yCoord.max : 200
    };
  };

  FireGrapher.prototype.renderGraph = function() {
    console.log("Config has changed, syncing.");
    // updating the interpolations to new scales
    this.interpolateXCoord = d3.scale.linear().domain([this.config.xCoord.min, this.config.xCoord.max]).range([0, this.config.graph.width]);
    this.interpolateYCoord = d3.scale.linear().domain([this.config.yCoord.min, this.config.yCoord.max]).range([this.config.graph.height, 0]);

    // removing old scales
    if (this.graph.select(this.cssSelector + " g.x")[0][0] !== null) {
      this.graph.select(this.cssSelector + " g.x").remove();
    }

    if (this.graph.select(this.cssSelector + " g.y")[0][0] !== null) {
      this.graph.select(this.cssSelector + " g.y").remove();
    }

    // adding new scales
    this.graph.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + this.config.graph.height + ")")
      .call(d3.svg.axis()
        .scale(this.interpolateXCoord)
        .ticks(4).tickSubdivide(1).tickSize(-this.config.graph.height, -this.config.graph.height, -50))
      // move the labels to where they can be seen
      .selectAll("text")
      .attr("y", 15)
      .style("text-anchor", "start");
    this.graph.append("g")
      .attr("class", "y axis")
      .call(d3.svg.axis()
        .orient("left")
        .scale(this.interpolateYCoord)
        .ticks(8).tickSubdivide(0).tickSize(-this.config.graph.width, -this.config.graph.width, -50))
      // move the labels to where they can be seen
      .selectAll("text")
      .attr("x", 5)
      .attr("y", -10)
      .style("text-anchor", "start");

    // removing old lines
    while (this.graph.select(this.cssSelector + " path").remove()[0][0] !== null);
    // adding lines to new graph
    for (var key in this.graphLines) {
      if (this.graphLines.hasOwnProperty(key)) {
        this.addLineToGraph(key, this.graphData[key]);
      }
    }
  };

  FireGrapher.prototype.addLineToGraph = function(name, data) {
    var line = d3.svg.line()
      .x(function(value, index) {
        return this.interpolateXCoord(index);
      }.bind(this))
      .y(function(value) {
        return this.interpolateYCoord(value);
      }.bind(this))
      .interpolate("basis");
    this.graph.append("svg:path").attr("d", line(this.graphData[name])).attr("class", name);
    this.graphLines[name] = line;
  };

  FireGrapher.prototype.drawGraph = function() {
    this.drawLineGraph();
  };

  FireGrapher.prototype.drawLineGraph = function() {
    this.graphData = {};
    this.graphLines = {};

    this.graph = d3.select(this.cssSelector).append("svg:svg").attr("width", "100%").attr("height", "100%");
    this.renderGraph();
  };

  return FireGrapher;
})();

/* jshint -W117 */
if (typeof module !== "undefined") {
  module.exports = FireGrapher;
}<commit_msg>Removing line definition when missing values<commit_after>var FireGrapher = (function() {
  "use strict";

  FireGrapher = function () {
    return;
  };

  FireGrapher.prototype.graph = function (cssSelector, firebaseRef, config) {
    this.cssSelector = cssSelector;
    this.firebaseRef = firebaseRef;
    this.updateConfig(config);

    this.drawGraph();

    // Parse path
    var nodes = config.path.split("/");
    console.log(nodes);

    console.log("Parsing paths");
    this.parsePathNode(["/"], nodes, 0).then(function(paths) {
      console.log("Paths parsed");
      console.log(paths);
      paths.forEach(function(path) {
        console.log(path);
        this.firebaseRef.child(path).on("child_added", function(childSnapshot) {
          var data = childSnapshot.val();
          var pathParts = path.split("/");
          var lastPathPart = pathParts[pathParts.length - 2];

          var line;
          if (config.line[0] === "$") {
            line = lastPathPart;
          }
          else {
            line = data[config.line];
          }

          this.addToLineGraph({
            "line": line,
            "xCoord": data[config.xCoord.value],
            "yCoord": data[config.yCoord.value]
          });
        }.bind(this));
      }.bind(this));
    }.bind(this));
  };

  FireGrapher.prototype.parsePathNode = function(paths, nodes, nodeIndex) {
    return new RSVP.Promise(function(resolve) {
      console.log("Calling parsePathNode() with index " + nodeIndex);
      var node = nodes[nodeIndex];
      if (node[0] === "*") {
        console.assert(nodeIndex === nodes.length - 1, "WHATTTT?");
        console.log(nodeIndex + ": individual record");
        console.log(paths);
        resolve(paths);
      }
      else if (node[0] === "$") {
        console.log(nodeIndex + ": param");

        var pathPromises = [];
        paths.forEach(function(path) {
          pathPromises.push(new RSVP.Promise(function(subResolve) {
            console.log(path);
            this.firebaseRef.child(path).once("value", function(dataSnapshot) {
              console.log(dataSnapshot);
              var newPaths = [];

              dataSnapshot.forEach(function(childSnapshot) {
                console.log(childSnapshot.name());
                newPaths.push(path + childSnapshot.name() + "/");
              }.bind(this));

              subResolve(newPaths);
            }.bind(this));
          }.bind(this)));
        }.bind(this));

        new RSVP.all(pathPromises).then(function(promisesData) {
          var newPaths = [];
          promisesData.forEach(function(promiseData) {
            promiseData.forEach(function(path) {
              newPaths.push(path);
            });
          });
          console.log(newPaths);

          this.parsePathNode(newPaths, nodes, nodeIndex + 1).then(function(finalPaths) {
            console.log("Final paths: " + nodeIndex);
            console.log(finalPaths);
            resolve(finalPaths);
          });
        }.bind(this));
      }
      else {
        console.log(nodeIndex + ": regular node");

        var newPaths = [];
        paths.forEach(function(path) {
          newPaths.push(path += node + "/");
        });

        this.parsePathNode(newPaths, nodes, nodeIndex + 1).then(function(finalPaths) {
          console.log("Final paths: " + nodeIndex);
            console.log(finalPaths);
          resolve(finalPaths);
        });
      }
    }.bind(this));
  };

  FireGrapher.prototype.addToLineGraph = function(newDataPoint) {
    // create a set of data if not exists
    if (typeof this.graphData[newDataPoint.line] === "undefined") {
      this.graphData[newDataPoint.line] = [];
    }

    // Update the data at the datapoint
    for (var i = this.graphData[newDataPoint.line].length; i < newDataPoint.xCoord; i++) {
      this.graphData[newDataPoint.line][i] = null;
    }
    this.graphData[newDataPoint.line][parseInt(newDataPoint.xCoord)] = parseInt(newDataPoint.yCoord);

    // update graph as necessary
    var newConfig = { xCoord: {}, yCoord: {} };
    if (this.config.xCoord.min > newDataPoint.xCoord) {
      newConfig.xCoord.min = newDataPoint.xCoord;
    }
    if (this.config.xCoord.max < newDataPoint.xCoord) {
      newConfig.xCoord.max = newDataPoint.xCoord;
    }
    if (this.config.yCoord.min > newDataPoint.yCoord) {
      newConfig.yCoord.min = newDataPoint.yCoord;
    }
    if (this.config.yCoord.max < newDataPoint.yCoord) {
      newConfig.yCoord.max = newDataPoint.yCoord;
    }
    this.updateConfig(newConfig);
    if (newConfig.xCoord.min || newConfig.xCoord.max || newConfig.yCoord.min || newConfig.yCoord.max) {
      this.renderGraph();
    }

    // create a d3 line if one does not exist exists
    var line = this.graphLines[newDataPoint.line];
    if (typeof line === "undefined") {
      line = this.addLineToGraph(newDataPoint.line, this.graphData[newDataPoint.line]);
    }
    else {
      // update the line with the data
      this.graph.select(this.cssSelector + " path." + newDataPoint.line)
        .data([this.graphData[newDataPoint.line]])
        .attr("d", line);
    }

    console.log(this.graphData[newDataPoint.line]);
  };

  FireGrapher.prototype.updateConfig = function(config) {
    // build default config if not exists
    this.config = (this.config) ? this.config : {};
    this.config.type = (this.config.type) ? this.config.type : null;
    this.config.graph = (this.config.graph) ? this.config.graph : {};
    this.config.xCoord = (this.config.xCoord) ? this.config.xCoord : {};
    this.config.yCoord = (this.config.yCoord) ? this.config.yCoord : {};

    // set config to new values
    this.config.type = (config.type && ["grid", "line", "scatter"].indexOf(config.type) !== -1) ? config.type : (this.config.type) ? this.config.type : null;
    if (this.config.type === null) {
      throw new Error("Invalid chart type. Must be \"grid\", \"line\", or \"scatter\"");
    }
    this.config.graph = {
      width : (config.graph && config.graph.width) ? config.graph.width : (this.config.graph.width) ? this.config.graph.width : 500,
      height : (config.graph && config.graph.height) ? config.graph.height : (this.config.graph.height) ? this.config.graph.height : 150
    };
    this.config.xCoord = {
      min : (config.xCoord && config.xCoord.min) ? config.xCoord.min : (this.config.xCoord.min) ? this.config.xCoord.min : 0,
      max : (config.xCoord && config.xCoord.max) ? config.xCoord.max : (this.config.xCoord.max) ? this.config.xCoord.max : 50
    };
    this.config.yCoord = {
      min : (config.yCoord && config.yCoord.min) ? config.yCoord.min : (this.config.yCoord.min) ? this.config.yCoord.min : 0,
      max : (config.yCoord && config.yCoord.max) ? config.yCoord.max : (this.config.yCoord.max) ? this.config.yCoord.max : 200
    };
  };

  FireGrapher.prototype.renderGraph = function() {
    console.log("Config has changed, syncing.");
    // updating the interpolations to new scales
    this.interpolateXCoord = d3.scale.linear().domain([this.config.xCoord.min, this.config.xCoord.max]).range([0, this.config.graph.width]);
    this.interpolateYCoord = d3.scale.linear().domain([this.config.yCoord.min, this.config.yCoord.max]).range([this.config.graph.height, 0]);

    // removing old scales
    if (this.graph.select(this.cssSelector + " g.x")[0][0] !== null) {
      this.graph.select(this.cssSelector + " g.x").remove();
    }

    if (this.graph.select(this.cssSelector + " g.y")[0][0] !== null) {
      this.graph.select(this.cssSelector + " g.y").remove();
    }

    // adding new scales
    this.graph.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + this.config.graph.height + ")")
      .call(d3.svg.axis()
        .scale(this.interpolateXCoord)
        .ticks(4).tickSubdivide(1).tickSize(-this.config.graph.height, -this.config.graph.height, -50))
      // move the labels to where they can be seen
      .selectAll("text")
      .attr("y", 15)
      .style("text-anchor", "start");
    this.graph.append("g")
      .attr("class", "y axis")
      .call(d3.svg.axis()
        .orient("left")
        .scale(this.interpolateYCoord)
        .ticks(8).tickSubdivide(0).tickSize(-this.config.graph.width, -this.config.graph.width, -50))
      // move the labels to where they can be seen
      .selectAll("text")
      .attr("x", 5)
      .attr("y", -10)
      .style("text-anchor", "start");

    // removing old lines
    while (this.graph.select(this.cssSelector + " path").remove()[0][0] !== null);
    // adding lines to new graph
    for (var key in this.graphLines) {
      if (this.graphLines.hasOwnProperty(key)) {
        this.addLineToGraph(key, this.graphData[key]);
      }
    }
  };

  FireGrapher.prototype.addLineToGraph = function(name, data) {
    var line = d3.svg.line()
      .defined(function(d) { return d != null; })
      .x(function(value, index) {
        return this.interpolateXCoord(index);
      }.bind(this))
      .y(function(value) {
        return this.interpolateYCoord(value);
      }.bind(this))
      .interpolate("basis");
    this.graph.append("svg:path").attr("d", line(this.graphData[name])).attr("class", name);
    this.graphLines[name] = line;
  };

  FireGrapher.prototype.drawGraph = function() {
    this.drawLineGraph();
  };

  FireGrapher.prototype.drawLineGraph = function() {
    this.graphData = {};
    this.graphLines = {};

    this.graph = d3.select(this.cssSelector).append("svg:svg").attr("width", "100%").attr("height", "100%");
    this.renderGraph();
  };

  return FireGrapher;
})();

/* jshint -W117 */
if (typeof module !== "undefined") {
  module.exports = FireGrapher;
}<|endoftext|>


<commit_before>import React from 'react'
import {
  connect
} from 'react-redux'

import SMMButton from '../buttons/SMMButton'
import AmazonPanel from '../panels/AmazonPanel'
import {
  ScreenSize
} from '../../reducers/mediaQuery'

class MainView extends React.PureComponent {
  render () {
    const screenSize = this.props.screenSize
    const styles = {
      main: {
        height: '100%',
        padding: screenSize === ScreenSize.SUPER_SMALL ? '6% 5%' : '6% 10%',
        color: '#000',
        display: 'flex',
        flexDirection: 'column',
        overflow: screenSize < ScreenSize.MEDIUM ? 'hidden' : 'auto'
      },
      content: {
        flex: '1 0 auto',
        padding: screenSize === ScreenSize.SUPER_SMALL ? '20px 10px' : '20px',
        fontSize: '16px',
        backgroundColor: 'rgba(59,189,159,1)',
        boxShadow: '0px 0px 10px 10px rgba(59,189,159,1)'
      },
      affiliate: {
        padding: screenSize === ScreenSize.SUPER_SMALL ? '20px 10px' : '20px',
        backgroundColor: 'rgba(59,189,159,1)',
        boxShadow: '0px 0px 10px 10px rgba(59,189,159,1)',
        display: 'flex',
        flexWrap: 'wrap',
        alignItems: 'flex-start',
        flex: '0 0 auto'
      },
      header: {
        fontSize: '18px',
        padding: '6px 12px',
        width: '100%',
        margin: '20px 0',
        backgroundColor: '#fff8af',
        borderRadius: '6px',
        border: '4px solid #f8ca00',
        boxShadow: '0 0 0 4px black'
      }
    }
    return (

            Welcome to Super Mario Maker Database!

          You can share your Super Mario Maker courses platform independently on this website. Supported platforms are Wii U, 3DS and Cemu. For Cemu there is even a save file editor. Just navigate to 'Client'.

          It also features courses for Super Mario 64 Maker, a popular ROM hack by Kaze Emanuar.

          To use all features on this website it is recommended to sign in with Google.

          All content on this website is user-created. We do not share any copyrighted stuff.

            Affiliates

          <SMMButton link='https://sm64o.com/' blank text='Super Mario 64 Online' iconSrc='/img/sm64o.png' iconColor='bright' noText />
          <SMMButton link='http://sm64hacks.com/' blank text='Super Mario 64 Hacks' iconSrc='/img/sm64hacks.png' iconColor='bright' noText />

        <AmazonPanel />

    )
  }
}
export default connect(state => ({
  screenSize: state.getIn(['mediaQuery', 'screenSize'])
}))(MainView)
<commit_msg>Update MainView.js<commit_after>import React from 'react'
import {
  connect
} from 'react-redux'

import SMMButton from '../buttons/SMMButton'
import AmazonPanel from '../panels/AmazonPanel'
import {
  ScreenSize
} from '../../reducers/mediaQuery'

class MainView extends React.PureComponent {
  render () {
    const screenSize = this.props.screenSize
    const styles = {
      main: {
        height: '100%',
        padding: screenSize === ScreenSize.SUPER_SMALL ? '6% 5%' : '6% 10%',
        color: '#000',
        display: 'flex',
        flexDirection: 'column',
        overflow: screenSize < ScreenSize.MEDIUM ? 'hidden' : 'auto'
      },
      content: {
        flex: '1 0 auto',
        padding: screenSize === ScreenSize.SUPER_SMALL ? '20px 10px' : '20px',
        fontSize: '16px',
        backgroundColor: 'rgba(59,189,159,1)',
        boxShadow: '0px 0px 10px 10px rgba(59,189,159,1)'
      },
      affiliate: {
        padding: screenSize === ScreenSize.SUPER_SMALL ? '20px 10px' : '20px',
        backgroundColor: 'rgba(59,189,159,1)',
        boxShadow: '0px 0px 10px 10px rgba(59,189,159,1)',
        display: 'flex',
        flexWrap: 'wrap',
        alignItems: 'flex-start',
        flex: '0 0 auto'
      },
      header: {
        fontSize: '18px',
        padding: '6px 12px',
        width: '100%',
        margin: '20px 0',
        backgroundColor: '#fff8af',
        borderRadius: '6px',
        border: '4px solid #f8ca00',
        boxShadow: '0 0 0 4px black'
      }
    }
    return (

            Welcome to Super Mario Maker Database!

          You can share your Super Mario Maker courses platform independently on this website. Supported platforms are Wii U, 3DS and Cemu. For Cemu there is even a save file editor. Just navigate to 'Client'.

          It also features courses for Super Mario 64 Maker, a popular ROM hack by Kaze Emanuar.

          To use all features on this website it is recommended to sign in with Google.

          All content on this website is user-created. We do not share any copyrighted stuff.

            Affiliates

          <SMMButton link='https://sm64o.com/' blank text='Super Mario 64 Online' iconSrc='/img/sm64o.png' iconColor='bright' noText />
          <SMMButton link='http://mariomods.net/' blank text='Mario Making Mods' iconSrc='/img/MMM.png' iconColor='bright' noText />
          <SMMButton link='http://sm64hacks.com/' blank text='Super Mario 64 Hacks' iconSrc='/img/sm64hacks.png' iconColor='bright' noText />

        <AmazonPanel />

    )
  }
}
export default connect(state => ({
  screenSize: state.getIn(['mediaQuery', 'screenSize'])
}))(MainView)
<|endoftext|>


<commit_before>var __pickr = (function(){

	'use strict';

	var startScreen = undefined,
		gameHolder = undefined,
		gameOverView = undefined,
		grid = undefined,
		cells = undefined,
		mutant = undefined,
		increment = undefined,
		colorHistory = undefined,
		difficulty = 0,
		score = 0,
		highScore = 0,
		lives = 5,
		counters = undefined,
		scoreDisplay = undefined,
		highScoreDisplay = undefined,
		difficultyDisplay = undefined,
		livesDisplay = undefined,
		colorDisplay = undefined,
		timerDisplay = undefined,
		roundTime = 10000,
		timeLeft = roundTime,
		startTime = undefined,
		boop = undefined,
		canInteract = true,
		playingGame = false;

	 window.requestAnimationFrame = (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame);

	var animationTimes = {
		quick : 300,
		medium : 600,
		longish : 100
	}

	var sounds = {
		nope : document.getElementById('nope'),
		pop : document.getElementById('pop')
	}

	var thisRGB = {
		r : 0,
		g : 0,
		b : 0
	},
	mutantRGB = {
		r : 0,
		g : 0,
		b : 0
	}

	var correctSelections = [];

	function continueGame(game){
		// console.log(game);

		resetGame();
		resetValues();

		thisRGB = game.thisRGB;
		mutantRGB = game.mutantRGB;
		mutant = game.mutant;
		score = game.score;
		correctSelections = game.correctSelections;
		scoreDisplay.innerHTML = "Score " + score;
		lives = game.lives;
		highScoreDisplay.innerHTML = "High score " + localStorage.getItem('highScore');
		timeLeft = game.timeLeft;
		// startTime = (Date.now() * 1) - (roundTime - timeLeft);

		startTime = (Date.now() * 1) - (roundTime - timeLeft);

		// console.log(game);

		// console.log("(%f * 1) - (%f - %f)", Date.now() * 1, roundTime, timeLeft);

		var e = 0,
			f = 0;

		if(correctSelections.length <= 10){
			difficulty = 1;
		} else if(correctSelections.length > 10 && correctSelections.length <= 20){
			difficulty = 1.5;
		} else if(correctSelections.length > 20 && correctSelections.length <= 30){
			difficulty = 2;
		} else if(correctSelections.length > 30 && correctSelections.length <= 40){
			difficulty = 4;
		} else if(correctSelections.length > 40 && correctSelections.length <= 50){
			difficulty = 5;
		} else {
			difficulty = 8;
		}

		while(e < cells.length){

			cells[e].style.backgroundColor = "rgb(" + thisRGB.r + "," + thisRGB.g + "," + thisRGB.b + ")";

			if(e !== mutant){
				cells[e].addEventListener(boop, incorrect, false);
			}

			e += 1;
		}

		cells[mutant].style.backgroundColor = "rgb(" + mutantRGB.r + "," + mutantRGB.g + "," + mutantRGB.b + ")";
		cells[mutant].addEventListener(boop, correct, false);

		while(f < 5){

			if(f < lives){
				livesDisplay[f].setAttribute('data-lost', 'false');
			} else {
				livesDisplay[f].setAttribute('data-lost', 'true');
			}

			f += 1;

		}

		var h = 0;

		while(h < correctSelections.length){

			var oldSwatch = document.createElement('span');
			oldSwatch.style.backgroundColor = "rgb(" + correctSelections[h].r + "," + correctSelections[h].g + "," + correctSelections[h].b + ")"
			colorHistory.appendChild(oldSwatch);

			h += 1;

		}

		// startTime = Date.now() * 1;
		drawTimer();

		startScreen.setAttribute('data-is-active-view', 'false');
		gameHolder.setAttribute('data-is-active-view', 'true');

	}

	function preloadImages(){

		var images = ["./assets/images/lives_lost.png"];

		for(var d = 0; d < images.length; d += 1){

			var img = new Image();
			img.src = images[d].src;

		}

	}

	function resetValues(){
		lives = 5;
		score = 0;
		difficulty = 1;
		correctSelections = [];
		colorHistory.innerHTML = "";
		difficultyDisplay.innerHTML = "Difficulty x" + difficulty;
		scoreDisplay.innerHTML = "Score 0";

		var g = 0;

		while(g < livesDisplay.length){

			livesDisplay[g].setAttribute('data-lost', 'false');

			g += 1;
		}

		colorDisplay.innerHTML = "";

	}

	function drawTimer(){

		/*if(startTime === undefined || startTime <= 0){
			startTime = Date.now() * 1;
		}*/

		if(playingGame){
			var currentTime = Date.now() * 1

			timeLeft = roundTime - (currentTime - startTime);

			timerDisplay.style.width = ((timeLeft / roundTime) * 100) + "%";

			// console.log(timeLeft);

			if(timeLeft <= 0){

				// console.log(playingGame, currentTime, timeLeft);
				playingGame = false;
				updateGameState();
				// console.log("INC 1");
				incorrect();

				// console.log(lives);

				if(lives > 0){
					resetGame();
					newSet();
				}

			} else {
				updateGameState();

			}
		}

		window.requestAnimationFrame(drawTimer);

	}

	function gameOver(){

		var c = 0,
			ca = 0;

		while(c < livesDisplay.length){

			livesDisplay[c].setAttribute('data-lost', 'false');

			c += 1;
		}

		while(ca < correctSelections.length){

			var swatch = document.createElement('li');

			swatch.style.backgroundColor = "rgb(" + correctSelections[ca].r + "," + correctSelections[ca].g + "," + correctSelections[ca].b + ")";

			colorDisplay.appendChild(swatch);

			ca += 1;

		}

		gameHolder.setAttribute('data-is-active-view', 'false');
		gameOverView.setAttribute('data-is-active-view', 'true');

		document.getElementById('finalScore').innerHTML = "You scored " + score + "!";

		if(score > highScore){
			highScore = score;
		}

		localStorage.removeItem('storedGame');
		canInteract = true;

	}

	function resetGame(){
		var b = 0;

		while(b < cells.length){

			if(b !== mutant){
				cells[b].removeEventListener(boop, incorrect, false);
			} else {
				cells[b].removeEventListener(boop, correct, false);
				cells[b].setAttribute('data-reveal', 'false');
			}

			b += 1;

		}

	}

	function updateGameState(){

		var gameState = {
			correctSelections : correctSelections,
			thisRGB : thisRGB,
			mutantRGB : mutantRGB,
			mutant : mutant,
			score : score,
			highScore : highScore,
			lives :lives,
			timeLeft : timeLeft
		};

		// console.log("Current State:");
		// console.log(gameState);

		localStorage.setItem('storedGame', JSON.stringify(gameState));

	}

	function incorrect(evt){
		// console.log("incorrect");

		if(canInteract){
			var element = this;

			// console.log(element === window)

			if(element !== window && element !== undefined){
				element.setAttribute('class', 'wobble');

				(function(el){

					setTimeout(function(){
						el.setAttribute('class', '');
					}, animationTimes.quick);

				})(element);
			}

			livesDisplay[lives - 1].setAttribute('data-lost', 'true');

			// sounds.nope.currentTime = 0;
			// sounds.nope.play();

			if(lives - 1 > 0){
				lives -= 1;
			} else {
				lives -= 1;
				cells[mutant].setAttribute('data-reveal', 'true');

				canInteract = false;

				playingGame = false;

				setTimeout(function(){
					gameOver();
				}, 2000);

			}

			updateGameState();
		}

	}

	function correct(){
		// console.log("correct");

		if(canInteract){

			// sounds.pop.currentTime = 0;
			// sounds.pop.play();

			var newSwatch = document.createElement('span');
			newSwatch.style.backgroundColor = "rgb(" + mutantRGB.r + "," + mutantRGB.g + "," + mutantRGB.b + ")"
			colorHistory.appendChild(newSwatch);

			correctSelections.push(mutantRGB);
			score += Math.ceil(1 * difficulty);

			if(score > highScore){
				highScore = score;
				highScoreDisplay.innerHTML = "High score " + highScore;
				localStorage.setItem('highScore', highScore);
			}

			if(correctSelections.length % 10 === 0 && lives < 5){
				lives += 1;
				livesDisplay[lives - 1].setAttribute('data-lost', 'false');
			}

			resetGame();
			newSet();

			updateGameState();

		}

	}

	function newColor(color){

		if(color === undefined){
			thisRGB.r = Math.random() * 255 | 0;
			thisRGB.g = Math.random() * 255 | 0;
			thisRGB.b = Math.random() * 255 | 0;
		} else {
			thisRGB.r = color.r;
			thisRGB.g = color.g;
			thisRGB.b = color.b;
		}

	}

	function newMutant(){
		mutant = Math.random() * cells.length | 0;
	}

	function drawGrid(mutant){

		var a = 0,
			rc = {
				r : thisRGB.r,
				g : thisRGB.g,
				b : thisRGB.b
			},
			shouldInvert = Math.round(Math.random());

		if(shouldInvert === 0){
			shouldInvert = -1;
		}

		while(a < cells.length){

			cells[a].style.backgroundColor = "rgb(" + rc.r + "," + rc.g + "," + rc.b + ")";

			if(a !== mutant){
				cells[a].addEventListener(boop, incorrect, false);
			}

			a += 1;
		}

		var cV = [rc.r, rc.g, rc.b].sort(function(a, b){
			 return (b-a);
		});

		if(cV[0] === rc.r){
			rc.r += (increment * shouldInvert) / difficulty | 0; // / 0.2126;
		} else if(cV[0] === rc.g){
			rc.g += (increment * shouldInvert) / difficulty | 0; // * 0.7152;
		} else if(cV[0] === rc.b){
			rc.b += (increment * shouldInvert) / difficulty | 0; // / 0.0722;
		}

		cells[mutant].style.backgroundColor = "rgb(" + rc.r + "," + rc.g + "," + rc.b + ")";
		cells[mutant].addEventListener(boop, correct, false);

		mutantRGB = rc;

	}

	function newSet(){

		if(correctSelections.length <= 10){
			difficulty = 1;
		} else if(correctSelections.length > 10 && correctSelections.length <= 20){
			difficulty = 1.5;
		} else if(correctSelections.length > 20 && correctSelections.length <= 30){
			difficulty = 2;
		} else if(correctSelections.length > 30 && correctSelections.length <= 40){
			difficulty = 4;
		} else if(correctSelections.length > 40 && correctSelections.length <= 50){
			difficulty = 5;
		} else {
			difficulty = 8;
		}

		difficultyDisplay.innerHTML = "Difficulty x" + difficulty;
		scoreDisplay.innerHTML = "Score " + score;
		highScoreDisplay.innerHTML = "High score " + highScore;

		startTime = Date.now() * 1;

		newColor();
		newMutant();
		drawGrid(mutant);

		playingGame = true;

		updateGameState();

	}

	function checkSavedGame(){
		return localStorage.getItem('storedGame');
	}

	function addEvents(){

		document.getElementById('begin').addEventListener(boop, function(){

			playingGame = true;

			resetGame();
			resetValues();
			newSet();

			startScreen.setAttribute('data-is-active-view', 'false');
			gameHolder.setAttribute('data-is-active-view', 'true');

		}, false);

		document.getElementById('tryAgainBtn').addEventListener(boop, function(){

			playingGame = true;

			resetGame();
			newSet();
			resetValues();

			gameOverView.setAttribute('data-is-active-view', 'false');
			gameHolder.setAttribute('data-is-active-view', 'true');

		}, false);

		document.getElementById('menuBtn').addEventListener(boop, function(){
			updateGameState();

			document.getElementById('continueBtn').setAttribute('data-visible', 'true');

			gameHolder.setAttribute('data-is-active-view', 'false');
			gameOverView.setAttribute('data-is-active-view', 'false');
			startScreen.setAttribute('data-is-active-view', 'true');
			playingGame = false;
		});

		var continueBtn = document.getElementById('continueBtn');

		continueBtn.addEventListener(boop, function(){

			if(checkSavedGame() !== null){
				var storedGame = JSON.parse(localStorage.getItem('storedGame'));
				playingGame = true;
				continueGame(storedGame);

			}

		}, false);

	}

	//Source from http://ctrlq.org/code/19616-detect-touch-screen-javascript
	function is_touch_device() {
		return (('ontouchstart' in window) || (navigator.MaxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0));
	}

	function init(){

		// console.log("Initialised");

		startScreen = document.getElementById('startScreen');
		gameHolder = document.getElementById('gameHolder');
		gameOverView = document.getElementById('gameOver');
		grid = document.getElementById('gameGrid');
		cells = grid.getElementsByTagName('span');
		increment = 20,
		colorHistory = document.getElementById('colorHistory');
		counters = document.getElementById('counters');
		scoreDisplay = document.getElementById('score');
		highScoreDisplay = document.getElementById('highScore');
		difficultyDisplay = document.getElementById('difficultyFactor');
		colorDisplay = document.getElementById('youPicked');
		timerDisplay = document.getElementById('runningOut');
		livesDisplay = document.getElementById('lives').getElementsByClassName('life');

		var storedHighScore = localStorage.getItem('highScore');

		if(storedHighScore !== null){
			highScore = parseInt(storedHighScore);
			highScoreDisplay.innerHTML = "High score" + highScore;
		}

		if(checkSavedGame() !== null){
			continueBtn.setAttribute('data-visible', 'true');
		}

		if(!is_touch_device()){
			boop = "click";
		} else {
			boop = "touchend";
		}

		addEvents();
		drawTimer();

		//setInterval(incorrect, 3000);

	}

	return{
		init : init
	};

})();

(function(){
	__pickr.init();
})();<commit_msg>Disabled new set when time runs out<commit_after>var __pickr = (function(){

	'use strict';

	var startScreen = undefined,
		gameHolder = undefined,
		gameOverView = undefined,
		grid = undefined,
		cells = undefined,
		mutant = undefined,
		increment = undefined,
		colorHistory = undefined,
		difficulty = 0,
		score = 0,
		highScore = 0,
		lives = 5,
		counters = undefined,
		scoreDisplay = undefined,
		highScoreDisplay = undefined,
		difficultyDisplay = undefined,
		livesDisplay = undefined,
		colorDisplay = undefined,
		timerDisplay = undefined,
		roundTime = 8000,
		timeLeft = roundTime,
		startTime = undefined,
		boop = undefined,
		canInteract = true,
		playingGame = false;

	window.requestAnimationFrame = (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame);

	var animationTimes = {
		quick : 300,
		medium : 600,
		longish : 100
	}

	var sounds = {
		nope : document.getElementById('nope'),
		pop : document.getElementById('pop')
	}

	var thisRGB = {
		r : 0,
		g : 0,
		b : 0
	},
	mutantRGB = {
		r : 0,
		g : 0,
		b : 0
	}

	var correctSelections = [];

	function continueGame(game){

		resetGame();
		resetValues();

		thisRGB = game.thisRGB;
		mutantRGB = game.mutantRGB;
		mutant = game.mutant;
		score = game.score;
		correctSelections = game.correctSelections;
		scoreDisplay.innerHTML = "Score " + score;
		lives = game.lives;
		highScoreDisplay.innerHTML = "High score " + localStorage.getItem('highScore');
		timeLeft = game.timeLeft;

		startTime = (Date.now() * 1) - (roundTime - timeLeft);

		var e = 0,
			f = 0;

		if(correctSelections.length <= 10){
			difficulty = 1;
		} else if(correctSelections.length > 10 && correctSelections.length <= 20){
			difficulty = 1.5;
		} else if(correctSelections.length > 20 && correctSelections.length <= 30){
			difficulty = 2;
		} else if(correctSelections.length > 30 && correctSelections.length <= 40){
			difficulty = 4;
		} else if(correctSelections.length > 40 && correctSelections.length <= 50){
			difficulty = 5;
		} else {
			difficulty = 8;
		}

		while(e < cells.length){

			cells[e].style.backgroundColor = "rgb(" + thisRGB.r + "," + thisRGB.g + "," + thisRGB.b + ")";

			if(e !== mutant){
				cells[e].addEventListener(boop, incorrect, false);
			}

			e += 1;
		}

		cells[mutant].style.backgroundColor = "rgb(" + mutantRGB.r + "," + mutantRGB.g + "," + mutantRGB.b + ")";
		cells[mutant].addEventListener(boop, correct, false);

		while(f < 5){

			if(f < lives){
				livesDisplay[f].setAttribute('data-lost', 'false');
			} else {
				livesDisplay[f].setAttribute('data-lost', 'true');
			}

			f += 1;

		}

		var h = 0;

		while(h < correctSelections.length){

			var oldSwatch = document.createElement('span');
			oldSwatch.style.backgroundColor = "rgb(" + correctSelections[h].r + "," + correctSelections[h].g + "," + correctSelections[h].b + ")"
			colorHistory.appendChild(oldSwatch);

			h += 1;

		}

		drawTimer();

		startScreen.setAttribute('data-is-active-view', 'false');
		gameHolder.setAttribute('data-is-active-view', 'true');

	}

	function preloadImages(){

		var images = ["./assets/images/lives_lost.png"];

		for(var d = 0; d < images.length; d += 1){

			var img = new Image();
			img.src = images[d].src;

		}

	}

	function resetValues(){
		lives = 5;
		score = 0;
		difficulty = 1;
		correctSelections = [];
		colorHistory.innerHTML = "";
		difficultyDisplay.innerHTML = "Difficulty x" + difficulty;
		scoreDisplay.innerHTML = "Score 0";

		var g = 0;

		while(g < livesDisplay.length){

			livesDisplay[g].setAttribute('data-lost', 'false');

			g += 1;
		}

		colorDisplay.innerHTML = "";

	}

	function drawTimer(){

		if(playingGame){
			var currentTime = Date.now() * 1;

			timeLeft = roundTime - (currentTime - startTime);

			timerDisplay.style.width = ((timeLeft / roundTime) * 100) + "%";

			if(timeLeft <= 0){

				updateGameState();
				incorrect();
				if(lives > 0){
					startTime = Date.now() * 1;
				}

			} else {
				updateGameState();

			}
		}

		window.requestAnimationFrame(drawTimer);

	}

	function gameOver(){

		var c = 0,
			ca = 0;

		while(c < livesDisplay.length){

			livesDisplay[c].setAttribute('data-lost', 'false');

			c += 1;
		}

		while(ca < correctSelections.length){

			var swatch = document.createElement('li');

			swatch.style.backgroundColor = "rgb(" + correctSelections[ca].r + "," + correctSelections[ca].g + "," + correctSelections[ca].b + ")";

			colorDisplay.appendChild(swatch);

			ca += 1;

		}

		gameHolder.setAttribute('data-is-active-view', 'false');
		gameOverView.setAttribute('data-is-active-view', 'true');

		document.getElementById('finalScore').innerHTML = "You scored " + score + "!";

		if(score > highScore){
			highScore = score;
		}

		localStorage.removeItem('storedGame');
		canInteract = true;

	}

	function resetGame(){
		var b = 0;

		while(b < cells.length){

			if(b !== mutant){
				cells[b].removeEventListener(boop, incorrect, false);
			} else {
				cells[b].removeEventListener(boop, correct, false);
				cells[b].setAttribute('data-reveal', 'false');
			}

			b += 1;

		}

	}

	function updateGameState(){

		var gameState = {
			correctSelections : correctSelections,
			thisRGB : thisRGB,
			mutantRGB : mutantRGB,
			mutant : mutant,
			score : score,
			highScore : highScore,
			lives :lives,
			timeLeft : timeLeft
		};

		localStorage.setItem('storedGame', JSON.stringify(gameState));

	}

	function incorrect(evt){

		if(canInteract){
			var element = this;

			if(element !== window && element !== undefined){
				element.setAttribute('class', 'wobble');

				(function(el){

					setTimeout(function(){
						el.setAttribute('class', '');
					}, animationTimes.quick);

				})(element);
			}

			livesDisplay[lives - 1].setAttribute('data-lost', 'true');

			// sounds.nope.currentTime = 0;
			// sounds.nope.play();

			if(lives - 1 > 0){
				lives -= 1;
			} else {
				lives -= 1;
				cells[mutant].setAttribute('data-reveal', 'true');

				canInteract = false;

				playingGame = false;

				setTimeout(function(){
					gameOver();
				}, 2000);

			}

			updateGameState();
		}

	}

	function correct(){

		if(canInteract){

			var newSwatch = document.createElement('span');
			newSwatch.style.backgroundColor = "rgb(" + mutantRGB.r + "," + mutantRGB.g + "," + mutantRGB.b + ")"
			colorHistory.appendChild(newSwatch);

			correctSelections.push(mutantRGB);
			score += Math.ceil(1 * difficulty);

			if(score > highScore){
				highScore = score;
				highScoreDisplay.innerHTML = "High score " + highScore;
				localStorage.setItem('highScore', highScore);
			}

			if(correctSelections.length % 10 === 0 && lives < 5){
				lives += 1;
				livesDisplay[lives - 1].setAttribute('data-lost', 'false');
			}

			resetGame();
			newSet();

			updateGameState();

		}

	}

	function newColor(color){

		if(color === undefined){
			thisRGB.r = Math.random() * 255 | 0;
			thisRGB.g = Math.random() * 255 | 0;
			thisRGB.b = Math.random() * 255 | 0;
		} else {
			thisRGB.r = color.r;
			thisRGB.g = color.g;
			thisRGB.b = color.b;
		}

	}

	function newMutant(){
		mutant = Math.random() * cells.length | 0;
	}

	function drawGrid(mutant){

		var a = 0,
			rc = {
				r : thisRGB.r,
				g : thisRGB.g,
				b : thisRGB.b
			},
			shouldInvert = Math.round(Math.random());

		if(shouldInvert === 0){
			shouldInvert = -1;
		}

		while(a < cells.length){

			cells[a].style.backgroundColor = "rgb(" + rc.r + "," + rc.g + "," + rc.b + ")";

			if(a !== mutant){
				cells[a].addEventListener(boop, incorrect, false);
			}

			a += 1;
		}

		var cV = [rc.r, rc.g, rc.b].sort(function(a, b){
			 return (b-a);
		});

		if(cV[0] === rc.r){
			rc.r += (increment * shouldInvert) / difficulty | 0; // / 0.2126;
		} else if(cV[0] === rc.g){
			rc.g += (increment * shouldInvert) / difficulty | 0; // * 0.7152;
		} else if(cV[0] === rc.b){
			rc.b += (increment * shouldInvert) / difficulty | 0; // / 0.0722;
		}

		cells[mutant].style.backgroundColor = "rgb(" + rc.r + "," + rc.g + "," + rc.b + ")";
		cells[mutant].addEventListener(boop, correct, false);

		mutantRGB = rc;

	}

	function newSet(){

		if(correctSelections.length <= 10){
			difficulty = 1;
		} else if(correctSelections.length > 10 && correctSelections.length <= 20){
			difficulty = 1.5;
		} else if(correctSelections.length > 20 && correctSelections.length <= 30){
			difficulty = 2;
		} else if(correctSelections.length > 30 && correctSelections.length <= 40){
			difficulty = 4;
		} else if(correctSelections.length > 40 && correctSelections.length <= 50){
			difficulty = 5;
		} else {
			difficulty = 8;
		}

		difficultyDisplay.innerHTML = "Difficulty x" + difficulty;
		scoreDisplay.innerHTML = "Score " + score;
		highScoreDisplay.innerHTML = "High score " + highScore;

		startTime = Date.now() * 1;

		newColor();
		newMutant();
		drawGrid(mutant);

		playingGame = true;

		updateGameState();

	}

	function checkSavedGame(){
		return localStorage.getItem('storedGame');
	}

	function addEvents(){

		document.getElementById('begin').addEventListener(boop, function(){

			playingGame = true;

			resetGame();
			resetValues();
			newSet();

			startScreen.setAttribute('data-is-active-view', 'false');
			gameHolder.setAttribute('data-is-active-view', 'true');

		}, false);

		document.getElementById('tryAgainBtn').addEventListener(boop, function(){

			playingGame = true;

			resetGame();
			newSet();
			resetValues();

			gameOverView.setAttribute('data-is-active-view', 'false');
			gameHolder.setAttribute('data-is-active-view', 'true');

		}, false);

		document.getElementById('menuBtn').addEventListener(boop, function(){
			updateGameState();

			document.getElementById('continueBtn').setAttribute('data-visible', 'true');

			gameHolder.setAttribute('data-is-active-view', 'false');
			gameOverView.setAttribute('data-is-active-view', 'false');
			startScreen.setAttribute('data-is-active-view', 'true');
			playingGame = false;
		});

		var continueBtn = document.getElementById('continueBtn');

		continueBtn.addEventListener(boop, function(){

			if(checkSavedGame() !== null){
				var storedGame = JSON.parse(localStorage.getItem('storedGame'));
				playingGame = true;
				continueGame(storedGame);

			}

		}, false);

	}

	//Source from http://ctrlq.org/code/19616-detect-touch-screen-javascript
	function is_touch_device() {
		return (('ontouchstart' in window) || (navigator.MaxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0));
	}

	function init(){

		startScreen = document.getElementById('startScreen');
		gameHolder = document.getElementById('gameHolder');
		gameOverView = document.getElementById('gameOver');
		grid = document.getElementById('gameGrid');
		cells = grid.getElementsByTagName('span');
		increment = 20,
		colorHistory = document.getElementById('colorHistory');
		counters = document.getElementById('counters');
		scoreDisplay = document.getElementById('score');
		highScoreDisplay = document.getElementById('highScore');
		difficultyDisplay = document.getElementById('difficultyFactor');
		colorDisplay = document.getElementById('youPicked');
		timerDisplay = document.getElementById('runningOut');
		livesDisplay = document.getElementById('lives').getElementsByClassName('life');

		var storedHighScore = localStorage.getItem('highScore');

		if(storedHighScore !== null){
			highScore = parseInt(storedHighScore);
			highScoreDisplay.innerHTML = "High score" + highScore;
		}

		if(checkSavedGame() !== null){
			continueBtn.setAttribute('data-visible', 'true');
		}

		if(!is_touch_device()){
			boop = "click";
		} else {
			boop = "touchend";
		}

		addEvents();
		drawTimer();

	}

	return{
		init : init
	};

})();

(function(){
	__pickr.init();
})();<|endoftext|>


<commit_before>/**
 * `<FormElement />` component renders form value into one of then `<Field />`,
 * `<Fieldset />` or `<RepeatingFieldset />` component:
 *
 *    <FormElement value={...} />
 *
 * This component is the main building block for composite form elements such as
 * `<Fieldset />` and `<RepeatingFieldset />` which use it to render its
 * children.
 *
 * Also `<FormElement />` can be used by application developer as a form in
 * "controlled mode":
 *
 *    <FormElement value={...} onUpdate={...} />
 *
 * The argument passed to `onUpdate` should be passed to `<FormElement />` as
 * `value` to render the updated form.
 *
 * @jsx React.DOM
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var React                         = require('react/addons');
var PropTypes                     = React.PropTypes;
var cloneWithProps                = React.addons.cloneWithProps;
var {ContextTypes}                = require('./FormConfiguration');
var FormPropTypes                 = require('./PropTypes');
var invariant                     = require('./invariant');
var {isList, isMapping, isScalar} = require('./schema');

var FormElement = React.createClass({

  propTypes: {
    value: FormPropTypes.Value,
    onUpdate: PropTypes.func
  },

  contextTypes: ContextTypes,

  render() {
    var value = this.props.value;
    var schema = this.props.value.schema;
    var component = schema.props.component;

    if (this.props.onUpdate) {
      value = value.update({onUpdate: this.onUpdate});
    }

    if (component) {
      return this.transferPropsTo(
        React.isValidComponent(component) ?
          cloneWithProps(component, {value}) :
          <component value={value} />
      );
    }

    return this.renderFormElementForSchema(schema);
  },

  renderFormElementForSchema(schema) {
    var component;
    if (isList(schema)) {
      component = this.context.repeatingFieldsetConstructor || require('./RepeatingFieldset');
    } else if (isMapping(schema)) {
      component = this.context.fieldsetConstructor || require('./Fieldset');
    } else if (isScalar(schema)) {
      component = this.context.fieldConstructor || require('./Field');
    } else {
      invariant(false, 'invalid schema node: ' + schema);
    }
    return this.transferPropsTo(<component value={this.props.value} />);
  },

//shouldComponentUpdate({value}) {
//  return !this.props.value.equals(value);
//},

  onUpdate(value) {
    this.props.value.onUpdate(value);
    this.props.onUpdate(this.props.value.for_(value.root()));
  }
});

module.exports = FormElement;
<commit_msg>Remove incorrect optimization<commit_after>/**
 * `<FormElement />` component renders form value into one of then `<Field />`,
 * `<Fieldset />` or `<RepeatingFieldset />` component:
 *
 *    <FormElement value={...} />
 *
 * This component is the main building block for composite form elements such as
 * `<Fieldset />` and `<RepeatingFieldset />` which use it to render its
 * children.
 *
 * Also `<FormElement />` can be used by application developer as a form in
 * "controlled mode":
 *
 *    <FormElement value={...} onUpdate={...} />
 *
 * The argument passed to `onUpdate` should be passed to `<FormElement />` as
 * `value` to render the updated form.
 *
 * @jsx React.DOM
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var React                         = require('react/addons');
var PropTypes                     = React.PropTypes;
var cloneWithProps                = React.addons.cloneWithProps;
var {ContextTypes}                = require('./FormConfiguration');
var FormPropTypes                 = require('./PropTypes');
var invariant                     = require('./invariant');
var {isList, isMapping, isScalar} = require('./schema');

var FormElement = React.createClass({

  propTypes: {
    value: FormPropTypes.Value,
    onUpdate: PropTypes.func
  },

  contextTypes: ContextTypes,

  render() {
    var value = this.props.value;
    var schema = this.props.value.schema;
    var component = schema.props.component;

    if (this.props.onUpdate) {
      value = value.update({onUpdate: this.onUpdate});
    }

    if (component) {
      return this.transferPropsTo(
        React.isValidComponent(component) ?
          cloneWithProps(component, {value}) :
          <component value={value} />
      );
    }

    return this.renderFormElementForSchema(schema);
  },

  renderFormElementForSchema(schema) {
    var component;
    if (isList(schema)) {
      component = this.context.repeatingFieldsetConstructor || require('./RepeatingFieldset');
    } else if (isMapping(schema)) {
      component = this.context.fieldsetConstructor || require('./Fieldset');
    } else if (isScalar(schema)) {
      component = this.context.fieldConstructor || require('./Field');
    } else {
      invariant(false, 'invalid schema node: ' + schema);
    }
    return this.transferPropsTo(<component value={this.props.value} />);
  },

// TODO: Make sure to provide correctness, the onUpdate callback isn't always
// propagated correctly
//shouldComponentUpdate({value}) {
//  return !this.props.value.equals(value);
//},

  onUpdate(value) {
    this.props.value.onUpdate(value);
    this.props.onUpdate(this.props.value.for_(value.root()));
  }
});

module.exports = FormElement;
<|endoftext|>


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var lastEvt = {}; // Hash of all watched files.

function watchGivenFile (watch) {
  //fs.watchFile(watch, function crash (oldStat, newStat) {
  if(lastEvt[watch]) return;
  lastEvt[watch] = (new Date()).valueOf()
  fs.watch(watch, function crash (evt, filename) {
    // we only care about modification time, not access time.
    /*if (
      newStat.mtime.getTime() === oldStat.mtime.getTime()
    ) return;
    */
    //DEBOUNCE
    now = (new Date).valueOf();
    if (lastEvt[watch]) {
      if (now - lastEvt[watch] < 2000) {
        return;
      }
    }
    lastEvt[watch] = now;

    // Handle new files. Re-watch parent directory.
    if (evt === 'rename' &! watch.match(fileExtensionPattern)) {
      findAllWatchFiles(watch, watchGivenFile);
    }

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

    var child = exports.child;
    var extension = getExtension(watch);
    sys.debug("detected change at "+watch+" - "+evt+" ext:"+extension);
    if ("coffee" === extension) {
      sys.debug("compiling with coffeescript.");
      exec("coffee -c "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
      // The JS file update should cause a restart, so don't do it here.
      /*if (programExt === "coffee") {
        // Don't restart for client side updates.
        if (program !== NO_PROGRAM && watch.indexOf('public/') === -1) process.kill(child.pid);
      }*/
    } else if (extension === "styl") {
      sys.debug('compiling with stylus.');
      exec("stylus "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "eco") {
      sys.debug('compiling with eco.');
      exec("eco -o "+p.dirname(watch)+" "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "jade") {
      if (watch.indexOf("client") > -1) {
        sys.debug('compiling with clientjade wrapper.');
        exec("clientjade.py " + p.dirname(watch) + " ./public",function(err, stderr, stdout) {
              if (err) sys.debug(err);
              if (stderr) sys.debug(stderr);
              if (stdout) sys.debug(stdout);
        });
      }
    } else if (extension === "js" && programExt === "coffee") {
      // Do nothing. TODO: why is this here.
    } else if (extension === "js" && watch.indexOf("public") !== -1) {
      // JS updates in the client folder don't trigger a restart.
    } else {

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

var findAllWatchFiles = function(path, callback) {
  fs.stat(path, function(err, stats){
    if (err) {
      sys.error('Error retrieving stats for file: ' + path);
    } else {
      if (stats.isDirectory()) {
        //callback(p.normalize(path));
        fs.readdir(path, function(err, fileNames) {
          if(err) {
            sys.puts('Error reading path: ' + path);
          }
          else {
            fileNames.forEach(function (fileName) {
              if ( fileName.charAt(0) !== '.'
//                && fileName !== 'node_modules'
                && fileName !== 'components'
                && fileName !== 'bower_components'
                && fileName !== 'run'
                )
                findAllWatchFiles(path + '/' + fileName, callback);
            });
          }
        });
      } else {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var lastEvt = {}; // Hash of all watched files.

function watchGivenFile (watch) {
  //fs.watchFile(watch, function crash (oldStat, newStat) {
  if(lastEvt[watch]) return;
  lastEvt[watch] = (new Date()).valueOf()
  fs.watch(watch, function crash (evt, filename) {
    // we only care about modification time, not access time.
    /*if (
      newStat.mtime.getTime() === oldStat.mtime.getTime()
    ) return;
    */
    //DEBOUNCE
    now = (new Date).valueOf();
    if (lastEvt[watch]) {
      if (now - lastEvt[watch] < 2000) {
        return;
      }
    }
    lastEvt[watch] = now;

    // Handle new files. Re-watch parent directory.
    if (evt === 'rename' &! watch.match(fileExtensionPattern)) {
      findAllWatchFiles(watch, watchGivenFile);
    }

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

    var child = exports.child;
    var extension = getExtension(watch);
    sys.debug("detected change at "+watch+" - "+evt+" ext:"+extension);
    if ("coffee" === extension) {
      sys.debug("compiling with coffeescript.");
      exec("coffee -m -c "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
      // The JS file update should cause a restart, so don't do it here.
      /*if (programExt === "coffee") {
        // Don't restart for client side updates.
        if (program !== NO_PROGRAM && watch.indexOf('public/') === -1) process.kill(child.pid);
      }*/
    } else if (extension === "styl") {
      sys.debug('compiling with stylus.');
      exec("stylus "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "eco") {
      sys.debug('compiling with eco.');
      exec("eco -o "+p.dirname(watch)+" "+watch,function(err, stderr, stdout) {
            if (err) sys.debug(err);
            if (stderr) sys.debug(stderr);
            if (stdout) sys.debug(stdout);
      });
    } else if (extension === "jade") {
      if (watch.indexOf("client") > -1) {
        sys.debug('compiling with clientjade wrapper.');
        exec("clientjade.py " + p.dirname(watch) + " ./public",function(err, stderr, stdout) {
              if (err) sys.debug(err);
              if (stderr) sys.debug(stderr);
              if (stdout) sys.debug(stdout);
        });
      }
    } else if (extension === "js" && programExt === "coffee") {
      // Do nothing. TODO: why is this here.
    } else if (extension === "js" && watch.indexOf("public") !== -1) {
      // JS updates in the client folder don't trigger a restart.
    } else {

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

var findAllWatchFiles = function(path, callback) {
  fs.stat(path, function(err, stats){
    if (err) {
      sys.error('Error retrieving stats for file: ' + path);
    } else {
      if (stats.isDirectory()) {
        //callback(p.normalize(path));
        fs.readdir(path, function(err, fileNames) {
          if(err) {
            sys.puts('Error reading path: ' + path);
          }
          else {
            fileNames.forEach(function (fileName) {
              if ( fileName.charAt(0) !== '.'
//                && fileName !== 'node_modules'
                && fileName !== 'components'
                && fileName !== 'bower_components'
                && fileName !== 'run'
                )
                findAllWatchFiles(path + '/' + fileName, callback);
            });
          }
        });
      } else {

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


<commit_before>import React from 'react';
import styled from 'styled-components';
import OutlineButton from 'ui/components/styled/OutlineButton';
import API from 'api';
import UIState from 'ui/UIState';
import omit from 'lodash/omit';
import { Group } from 'api/models/group';

const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
`;

const Text = styled.span`
  color: #858585;
`;

export class MultiSelectView extends React.Component {

  groupMocks = () => {
    const group = API.addGroup({ name: 'Grouped Mocks' });

    if (group) {
      UIState.selectedItems.forEach((item) => {
        if (item instanceof Group) {
          return;
        }

        if (item.groupId) {
          API.mockRequest({ ...omit(item, ['id']), groupId: group.id });
          return;
        }

        API.updateMock(item.id, { ...item, groupId: group.id })
      });
    }

    this.props.select(group.mocks[0]);

    const groups = UIState.groups.map((item) => {
      if (item.id === group.id) {
        return { ...item, isOpen: true }
      }

      return item;
    });

    UIState.update({ groups });
  };

  render() {
    return (
      <Container>

          <OutlineButton onClick={ this.groupMocks }>Group</OutlineButton>
          <Text>these mocks</Text>

      </Container>
    );
  }

}

export default MultiSelectView;
<commit_msg>Fix group not opening when grouping mocks into a new group<commit_after>import React from 'react';
import styled from 'styled-components';
import OutlineButton from 'ui/components/styled/OutlineButton';
import API from 'api';
import UIState from 'ui/UIState';
import omit from 'lodash/omit';
import { Group } from 'api/models/group';

const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
`;

const Text = styled.span`
  color: #858585;
`;

export class MultiSelectView extends React.Component {

  groupMocks = () => {
    const group = API.addGroup({ name: 'Grouped Mocks' });

    if (group) {
      UIState.selectedItems.forEach((item) => {
        if (item instanceof Group) {
          return;
        }

        if (item.groupId) {
          API.mockRequest({ ...omit(item, ['id']), groupId: group.id });
          return;
        }

        API.updateMock(item.id, { ...item, groupId: group.id })
      });
    }

    const groups = [
      ...UIState.groups,
      {
        id: group.id,
        isOpen: true,
        lastState: null
      }
    ];

    const firstMock = group.mocks[0];
    UIState.update({ groups, selectedItems: [firstMock] });
  };

  render() {
    return (
      <Container>

          <OutlineButton onClick={ this.groupMocks }>Group</OutlineButton>
          <Text>these mocks</Text>

      </Container>
    );
  }

}

export default MultiSelectView;
<|endoftext|>


<commit_before>var Q = require('q');
var utils = require('./utils');
var debug = require('debug')('home-controller:insteon:x10');
var toByte = utils.toByte;

var CODES = [0x6, 0xE, 0x2, 0xA, 0x1, 0x9, 0x5, 0xD, 0x7, 0xF, 0x3, 0xB, 0x0, 0x8, 0x4, 0xC];
var ON_CODE = 0x2;
var OFF_CODE = 0x3;

function X10(id, insteon) {
  this.id = id;
  this.house = id.substring(0,1);
  this.unit = id.substring(1);

  var houseCodeIndex = this.house.toUpperCase().charCodeAt(0) - 'A'.charCodeAt(0);
  var unitCodeIndex = parseInt(this.unit) - 1;

  this.houseCode = CODES[houseCodeIndex] << 4;
  this.unitCode = CODES[unitCodeIndex];

  this.unitCmd = {
    exitOnAck: true,
    raw: '0263' + toByte(this.houseCode + this.unitCode) + '00',
    id: this.id
  };

  this.insteon = insteon;
}
X10.prototype.turnOn = function (next) {
  return this.send(ON_CODE, next);
};

X10.prototype.turnOff = function (next) {
  return this.send(OFF_CODE, next);
};

X10.prototype.send = function(code, next) {
  var insteon = this.insteon;

  var cmd = {
    exitOnAck: true,
    raw: '0263' + toByte(this.houseCode + code) + '80',
    id: this.id
  };

  debug('sending x10 unit', this.unitCmd);

  var deferred = Q.defer();
  deferred.resolve(
    insteon.sendCommand(this.unitCmd)
    .then(function () {
      debug('sending x10 cmd', cmd);
      return insteon.sendCommand(cmd);
    })
  );

  return deferred.promise.nodeify(next);
};

X10.prototype.cancelPending = function() {
  this.insteon.cancelPending(this.id);
};

module.exports = X10;<commit_msg>[fix] add missing delay between X10 unit and cmd messages<commit_after>var Q = require('q');
var utils = require('./utils');
var debug = require('debug')('home-controller:insteon:x10');
var toByte = utils.toByte;

var CODES = [0x6, 0xE, 0x2, 0xA, 0x1, 0x9, 0x5, 0xD, 0x7, 0xF, 0x3, 0xB, 0x0, 0x8, 0x4, 0xC];
var ON_CODE = 0x2;
var OFF_CODE = 0x3;

function X10(id, insteon) {
  this.id = id;
  this.house = id.substring(0,1);
  this.unit = id.substring(1);

  var houseCodeIndex = this.house.toUpperCase().charCodeAt(0) - 'A'.charCodeAt(0);
  var unitCodeIndex = parseInt(this.unit) - 1;

  this.houseCode = CODES[houseCodeIndex] << 4;
  this.unitCode = CODES[unitCodeIndex];

  this.unitCmd = {
    exitOnAck: true,
    raw: '0263' + toByte(this.houseCode + this.unitCode) + '00',
    id: this.id
  };

  this.insteon = insteon;
}
X10.prototype.turnOn = function (next) {
  return this.send(ON_CODE, next);
};

X10.prototype.turnOff = function (next) {
  return this.send(OFF_CODE, next);
};

X10.prototype.send = function(code, next) {
  var insteon = this.insteon;

  var cmd = {
    exitOnAck: true,
    raw: '0263' + toByte(this.houseCode + code) + '80',
    id: this.id
  };

  debug('sending x10 unit', this.unitCmd);

  var deferred = Q.defer();
  deferred.resolve(
    insteon.sendCommand(this.unitCmd)
    .delay(500)
    .then(function () {
      debug('sending x10 cmd', cmd);
      return insteon.sendCommand(cmd);
    })
  );

  return deferred.promise.nodeify(next);
};

X10.prototype.cancelPending = function() {
  this.insteon.cancelPending(this.id);
};

module.exports = X10;<|endoftext|>


<commit_before>'use strict';

var Blueprint = require('ember-cli/lib/models/blueprint');
var path = require('path');

/**
  Find the non-coffeescript version of the blueprint to bootstrap off
 */
module.exports = function(dasherizedName, project) {
  var projectPaths = project ? project.blueprintLookupPaths() : [];

  projectPaths = projectPaths.filter(function(p) {
    return !p.match(/ember-cli-coffeescript/);
  });

  projectPaths = projectPaths.concat(legacyBlueprintsPath());

  return Blueprint.lookup(dasherizedName, {
    paths: projectPaths
  });
};

function legacyBlueprintsPath() {
  return path.join(
    path.dirname(
      require.resolve('ember-cli-legacy-blueprints')
    ),
    'blueprints'
  );
}
<commit_msg>Check specific coffeescript path<commit_after>'use strict';

var Blueprint = require('ember-cli/lib/models/blueprint');
var path = require('path');
var coffeeScriptPath = path.resolve(__dirname, '../..', 'blueprints');

/**
  Find the non-coffeescript version of the blueprint to bootstrap off
 */
module.exports = function(dasherizedName, project) {
  var projectPaths = project ? project.blueprintLookupPaths() : [];

  projectPaths = projectPaths.filter(function(p) {
    return p !== coffeeScriptPath;
  });

  projectPaths = projectPaths.concat(legacyBlueprintsPath());

  return Blueprint.lookup(dasherizedName, {
    paths: projectPaths
  });
};

function legacyBlueprintsPath() {
  return path.join(
    path.dirname(
      require.resolve('ember-cli-legacy-blueprints')
    ),
    'blueprints'
  );
}
<|endoftext|>