<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require("./logger.js")(__filename);

const firewalla = require('./Firewalla.js');
const HostTool = require('./HostTool.js');
const hostTool = new HostTool();

const ip = require('ip');

const exec = require('child-process-promise').exec

const sem = require('../sensor/SensorEventManager.js').getInstance();

const util = require('util');

const sclient = require('../util/redis_manager.js').getSubscriptionClient();
var instance = null;

class ShieldManager {
  constructor() {
    if (!instance) {
      sclient.on("message", (channel, message) => {
        switch (channel) {
          case "System:VPNSubnetChanged":
            const newVpnSubnet = message;
            this._updateVPNOutgoingRules(newVpnSubnet);
            break;
          default:

        }
      });
      if (firewalla.isMain()) {
        sclient.subscribe("System:VPNSubnetChanged");

        sem.on("DeviceUpdate", (event) => {
          // add/update device ip address to trusted_ip_set/trusted_ip_set6
          const host = event.host;
          if (host.ipv4Addr) {
            log.info("Update device ip in trusted_ip_set: " + host.ipv4Addr);
            const cmd = util.format("sudo ipset add -! trusted_ip_set %s", host.ipv4Addr);
            exec(cmd);
          }
          if (host.ipv6Addr && host.ipv6Addr.length > 0) {
            host.ipv6Addr.forEach(ipv6Addr => {
              log.info("Update device ip in trusted_ip_set6: " + ipv6Addr);
              const cmd = util.format("sudo ipset add -! trusted_ip_set6 %s", ipv6Addr);
              exec(cmd);
            });
          }
          // update ip address to protected_ip_set/protected_ip_set6
          if (host.mac && this.protected_macs[host.mac]) {
            this.activateShield(host.mac);
          }
        });

        this.protected_macs = {};

        this._updateTrustedIPSet();
        setInterval(() => {
          this._updateTrustedIPSet();
          this._updateProtectedIPSet();
        }, 300000); // update trusted_ip_set and protected_ip_set once every 5 minutes
      }
      instance = this;
    }
    return instance;
  }

  async addIncomingRule(protocol, dstIp, dstPort) {
    log.info(util.format("Add incoming rule to %s:%s, protocol %s", dstIp, dstPort, protocol));
    const cmd = util.format("sudo iptables -w -C FW_SHIELD -p %s -d %s --dport %s -j RETURN || sudo iptables -w -I FW_SHIELD -p %s -d %s --dport %s -j RETURN",
      protocol, dstIp, dstPort, protocol, dstIp, dstPort);
    await exec(cmd);
  }

  async removeIncomingRule(protocol, dstIp, dstPort) {
    log.info(util.format("Remove incoming rule to %s:%s, protocol %s", dstIp, dstPort, protocol));
    const cmd = util.format("sudo iptables -w -C FW_SHIELD -p %s -d %s --dport %s -j RETURN && sudo iptables -w -D FW_SHIELD -p %s -d %s --dport %s -j RETURN",
      protocol, dstIp, dstPort, protocol, dstIp, dstPort);
    await exec(cmd);
  }

  async _updateProtectedIPSet() {
    const macs = Object.keys(this.protected_macs);
    for (let i in macs) {
      await this.activateShield(macs[i]);
    }
  }

  async _updateTrustedIPSet() {
    const macEntries = await hostTool.getAllMACEntries();
    const allIpv4Addrs = {};
    const allIpv6Addrs = {};
    for (let i in macEntries) {
      const macEntry = macEntries[i];
      const ipv4Addr = macEntry.ipv4Addr;
      if (ipv4Addr && ip.isV4Format(ipv4Addr)) {
        allIpv4Addrs[ipv4Addr] = 1;
      }
      let ipv6Addrs = [];
      if (macEntry.ipv6Addr)
        ipv6Addrs = JSON.parse(macEntry.ipv6Addr);
      if (ipv6Addrs && ipv6Addrs.length > 0) {
        for (let j in ipv6Addrs) {
          const ipv6Addr = ipv6Addrs[j];
          if (ipv6Addr && ip.isV6Format(ipv6Addr)) {
            allIpv6Addrs[ipv6Addr] = 1;
          }
        }
      }
    }
    for (let ip in allIpv4Addrs) {
      log.info("Add ip to trusted_ip_set: " + ip);
      const cmd = util.format("sudo ipset add -! trusted_ip_set %s", ip);
      await exec(cmd);
    }
    for (let ip in allIpv6Addrs) {
      log.info("Add ip to trusted_ip_set6: " + ip);
      const cmd = util.format("sudo ipset add -! trusted_ip_set6 %s", ip);
      await exec(cmd);
    }
  }

  async _updateVPNOutgoingRules(vpnSubnet) {
    if (this.vpnSubnet) {
      // remove old vpn subnet
      const cmd = util.format("sudo ipset -! del trusted_ip_set %s", this.vpnSubnet);
      await exec(cmd);
      this.vpnSubnet = null;
    }
    if (vpnSubnet) {
      // add new vpn subnet
      const cmd = util.format("sudo ipset add -! trusted_ip_set %s", vpnSubnet);
      await exec(cmd);
      this.vpnSubnet = vpnSubnet;
    }
  }

  async activateShield(mac) {
    if (!mac) {
      // enable shield globally
      let cmd = "sudo iptables -w -C FORWARD -j FW_SHIELD || sudo iptables -w -A FORWARD -j FW_SHIELD";
      await exec(cmd).catch((err) => {
        log.error("Failed to activate global shield in iptables", err);
      });

      cmd = "sudo ip6tables -w -C FORWARD -j FW_SHIELD || sudo ip6tables -w -A FORWARD -j FW_SHIELD";
      await exec(cmd).catch((err) => {
        log.error("Failed to activate global shield in ip6tables", err);
      });
    } else {
      // per-device shield
      const macEntry = await hostTool.getMACEntry(mac);
      if (!macEntry) {
        log.error("Cannot find host info of " + mac);
        return;
      }

      if (this.protected_macs[mac]) {
        const legacyMacEntry = this.protected_macs[mac];
        const legacyIpv6Addrs = (legacyMacEntry.ipv6Addrs || []).sort();
        const ipv6Addrs = (macEntry.ipv6Addrs || []).sort();
        if (macEntry.ipv4Addr !== legacyMacEntry.ipv4Addr || ipv6Addrs.length !== legacyIpv6Addrs.length || !ipv6Addrs.every((value, index) => {return value === legacyIpv6Addrs[index]})) {
          // ip addresses may be changed
          log.info("IP addresses of " + mac + " have been changed.")
          await this.deactivateShield(mac);
        } else {
          log.info("IP addresses of " + mac + " are not changed.");
        }
      }

      this.protected_macs[mac] = macEntry;
      const ipv4Addr = macEntry.ipv4Addr;
      if (ipv4Addr && ip.isV4Format(ipv4Addr)) {
        log.info("Add ip to protected_ip_set: " + ipv4Addr);
        const cmd = util.format("sudo ipset add -! protected_ip_set %s", ipv4Addr);
        await exec(cmd).catch((err) => {
          log.error("Failed to add " + ipv4Addr + " to protected_ip_set", err);
        });
      }
      let ipv6Addrs = [];
      if (macEntry.ipv6Addr)
        ipv6Addrs = JSON.parse(macEntry.ipv6Addr);
      if (ipv6Addrs && ipv6Addrs.length > 0) {
        for (let j in ipv6Addrs) {
          const ipv6Addr = ipv6Addrs[j];
          if (ipv6Addr && ip.isV6Format(ipv6Addr)) {
            log.info("Add ip to protected_ip_set6: " + ipv6Addr);
            const cmd = util.format("sudo ipset add -! protected_ip_set6 %s", ipv6Addr);
            await exec(cmd).catch((err) => {
              log.error("Failed to add " + ipv4Addr + " to protected_ip_set6", err);
            });
          }
        }
      }
    }
  }

  async deactivateShield(mac) {
    if (!mac) {
      // disable shield globally
      let cmd = "sudo iptables -w -C FORWARD -j FW_SHIELD && sudo iptables -w -D FORWARD -j FW_SHIELD";
      await exec(cmd).catch((err) => {
        log.error("Failed to deactivate global shield in iptables", err);
      });

      cmd = "sudo ip6tables -w -C FORWARD -j FW_SHIELD && sudo ip6tables -w -D FORWARD -j FW_SHIELD";
      await exec(cmd).catch((err) => {
        log.error("Failed to deactivate global shield in ip6tables", err);
      });
    } else {
      if (this.protected_macs[mac]) {
        const macEntry = this.protected_macs[mac];
        if (!macEntry)
          return;
        const ipv4Addr = macEntry.ipv4Addr;
        if (ipv4Addr && ip.isV4Format(ipv4Addr)) {
          log.info("Remove ip from protected_ip_set: " + ipv4Addr);
          const cmd = util.format("sudo ipset del -! protected_ip_set %s", ipv4Addr);
          await exec(cmd).catch((err) => {
            log.error("Failed to remove " + ipv4Addr + " from protected_ip_set", err);
          });
        }
        let ipv6Addrs = [];
        if (macEntry.ipv6Addr)
          ipv6Addrs = JSON.parse(macEntry.ipv6Addr);
        if (ipv6Addrs && ipv6Addrs.length > 0) {
          for (let j in ipv6Addrs) {
            const ipv6Addr = ipv6Addrs[j];
            if (ipv6Addr && ip.isV6Format(ipv6Addr)) {
              log.info("Remove ip from protected_ip_set6: " + ipv6Addr);
              const cmd = util.format("sudo ipset add -! protected_ip_set6 %s", ipv6Addr);
              await exec(cmd).catch((err) => {
                log.error("Failed to remove " + ipv6Addr + " from protected_ip_set6", err);
              });
            }
          }
        }
        delete this.protected_macs[mac];
      } else {
        log.warn("Device " + mac + " is not protected, no need to deactivate shield.");
      }
    }
  }
}

module.exports = ShieldManager;<commit_msg>change to log.debug<commit_after>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require("./logger.js")(__filename);

const firewalla = require('./Firewalla.js');
const HostTool = require('./HostTool.js');
const hostTool = new HostTool();

const ip = require('ip');

const exec = require('child-process-promise').exec

const sem = require('../sensor/SensorEventManager.js').getInstance();

const util = require('util');

const sclient = require('../util/redis_manager.js').getSubscriptionClient();
var instance = null;

class ShieldManager {
  constructor() {
    if (!instance) {
      sclient.on("message", (channel, message) => {
        switch (channel) {
          case "System:VPNSubnetChanged":
            const newVpnSubnet = message;
            this._updateVPNOutgoingRules(newVpnSubnet);
            break;
          default:

        }
      });
      if (firewalla.isMain()) {
        sclient.subscribe("System:VPNSubnetChanged");

        sem.on("DeviceUpdate", (event) => {
          // add/update device ip address to trusted_ip_set/trusted_ip_set6
          const host = event.host;
          if (host.ipv4Addr) {
            log.info("Update device ip in trusted_ip_set: " + host.ipv4Addr);
            const cmd = util.format("sudo ipset add -! trusted_ip_set %s", host.ipv4Addr);
            exec(cmd);
          }
          if (host.ipv6Addr && host.ipv6Addr.length > 0) {
            host.ipv6Addr.forEach(ipv6Addr => {
              log.info("Update device ip in trusted_ip_set6: " + ipv6Addr);
              const cmd = util.format("sudo ipset add -! trusted_ip_set6 %s", ipv6Addr);
              exec(cmd);
            });
          }
          // update ip address to protected_ip_set/protected_ip_set6
          if (host.mac && this.protected_macs[host.mac]) {
            this.activateShield(host.mac);
          }
        });

        this.protected_macs = {};

        this._updateTrustedIPSet();
        setInterval(() => {
          this._updateTrustedIPSet();
          this._updateProtectedIPSet();
        }, 300000); // update trusted_ip_set and protected_ip_set once every 5 minutes
      }
      instance = this;
    }
    return instance;
  }

  async addIncomingRule(protocol, dstIp, dstPort) {
    log.info(util.format("Add incoming rule to %s:%s, protocol %s", dstIp, dstPort, protocol));
    const cmd = util.format("sudo iptables -w -C FW_SHIELD -p %s -d %s --dport %s -j RETURN || sudo iptables -w -I FW_SHIELD -p %s -d %s --dport %s -j RETURN",
      protocol, dstIp, dstPort, protocol, dstIp, dstPort);
    await exec(cmd);
  }

  async removeIncomingRule(protocol, dstIp, dstPort) {
    log.info(util.format("Remove incoming rule to %s:%s, protocol %s", dstIp, dstPort, protocol));
    const cmd = util.format("sudo iptables -w -C FW_SHIELD -p %s -d %s --dport %s -j RETURN && sudo iptables -w -D FW_SHIELD -p %s -d %s --dport %s -j RETURN",
      protocol, dstIp, dstPort, protocol, dstIp, dstPort);
    await exec(cmd);
  }

  async _updateProtectedIPSet() {
    const macs = Object.keys(this.protected_macs);
    for (let i in macs) {
      await this.activateShield(macs[i]);
    }
  }

  async _updateTrustedIPSet() {
    const macEntries = await hostTool.getAllMACEntries();
    const allIpv4Addrs = {};
    const allIpv6Addrs = {};
    for (let i in macEntries) {
      const macEntry = macEntries[i];
      const ipv4Addr = macEntry.ipv4Addr;
      if (ipv4Addr && ip.isV4Format(ipv4Addr)) {
        allIpv4Addrs[ipv4Addr] = 1;
      }
      let ipv6Addrs = [];
      if (macEntry.ipv6Addr)
        ipv6Addrs = JSON.parse(macEntry.ipv6Addr);
      if (ipv6Addrs && ipv6Addrs.length > 0) {
        for (let j in ipv6Addrs) {
          const ipv6Addr = ipv6Addrs[j];
          if (ipv6Addr && ip.isV6Format(ipv6Addr)) {
            allIpv6Addrs[ipv6Addr] = 1;
          }
        }
      }
    }
    for (let ip in allIpv4Addrs) {
      log.info("Add ip to trusted_ip_set: " + ip);
      const cmd = util.format("sudo ipset add -! trusted_ip_set %s", ip);
      await exec(cmd);
    }
    for (let ip in allIpv6Addrs) {
      log.info("Add ip to trusted_ip_set6: " + ip);
      const cmd = util.format("sudo ipset add -! trusted_ip_set6 %s", ip);
      await exec(cmd);
    }
  }

  async _updateVPNOutgoingRules(vpnSubnet) {
    if (this.vpnSubnet) {
      // remove old vpn subnet
      const cmd = util.format("sudo ipset -! del trusted_ip_set %s", this.vpnSubnet);
      await exec(cmd);
      this.vpnSubnet = null;
    }
    if (vpnSubnet) {
      // add new vpn subnet
      const cmd = util.format("sudo ipset add -! trusted_ip_set %s", vpnSubnet);
      await exec(cmd);
      this.vpnSubnet = vpnSubnet;
    }
  }

  async activateShield(mac) {
    if (!mac) {
      // enable shield globally
      let cmd = "sudo iptables -w -C FORWARD -j FW_SHIELD || sudo iptables -w -A FORWARD -j FW_SHIELD";
      await exec(cmd).catch((err) => {
        log.error("Failed to activate global shield in iptables", err);
      });

      cmd = "sudo ip6tables -w -C FORWARD -j FW_SHIELD || sudo ip6tables -w -A FORWARD -j FW_SHIELD";
      await exec(cmd).catch((err) => {
        log.error("Failed to activate global shield in ip6tables", err);
      });
    } else {
      // per-device shield
      const macEntry = await hostTool.getMACEntry(mac);
      if (!macEntry) {
        log.error("Cannot find host info of " + mac);
        return;
      }

      if (this.protected_macs[mac]) {
        const legacyMacEntry = this.protected_macs[mac];
        const legacyIpv6Addrs = (legacyMacEntry.ipv6Addrs || []).sort();
        const ipv6Addrs = (macEntry.ipv6Addrs || []).sort();
        if (macEntry.ipv4Addr !== legacyMacEntry.ipv4Addr || ipv6Addrs.length !== legacyIpv6Addrs.length || !ipv6Addrs.every((value, index) => {return value === legacyIpv6Addrs[index]})) {
          // ip addresses may be changed
          log.info("IP addresses of " + mac + " have been changed.")
          await this.deactivateShield(mac);
        } else {
          log.info("IP addresses of " + mac + " are not changed.");
        }
      }

      this.protected_macs[mac] = macEntry;
      const ipv4Addr = macEntry.ipv4Addr;
      if (ipv4Addr && ip.isV4Format(ipv4Addr)) {
        log.info("Add ip to protected_ip_set: " + ipv4Addr);
        const cmd = util.format("sudo ipset add -! protected_ip_set %s", ipv4Addr);
        await exec(cmd).catch((err) => {
          log.error("Failed to add " + ipv4Addr + " to protected_ip_set", err);
        });
      }
      let ipv6Addrs = [];
      if (macEntry.ipv6Addr)
        ipv6Addrs = JSON.parse(macEntry.ipv6Addr);
      if (ipv6Addrs && ipv6Addrs.length > 0) {
        for (let j in ipv6Addrs) {
          const ipv6Addr = ipv6Addrs[j];
          if (ipv6Addr && ip.isV6Format(ipv6Addr)) {
            log.info("Add ip to protected_ip_set6: " + ipv6Addr);
            const cmd = util.format("sudo ipset add -! protected_ip_set6 %s", ipv6Addr);
            await exec(cmd).catch((err) => {
              log.error("Failed to add " + ipv4Addr + " to protected_ip_set6", err);
            });
          }
        }
      }
    }
  }

  async deactivateShield(mac) {
    if (!mac) {
      // disable shield globally
      let cmd = "sudo iptables -w -C FORWARD -j FW_SHIELD && sudo iptables -w -D FORWARD -j FW_SHIELD";
      await exec(cmd).catch((err) => {
        log.debug("Failed to deactivate global shield in iptables", err);
      });

      cmd = "sudo ip6tables -w -C FORWARD -j FW_SHIELD && sudo ip6tables -w -D FORWARD -j FW_SHIELD";
      await exec(cmd).catch((err) => {
        log.debug("Failed to deactivate global shield in ip6tables", err);
      });
    } else {
      if (this.protected_macs[mac]) {
        const macEntry = this.protected_macs[mac];
        if (!macEntry)
          return;
        const ipv4Addr = macEntry.ipv4Addr;
        if (ipv4Addr && ip.isV4Format(ipv4Addr)) {
          log.info("Remove ip from protected_ip_set: " + ipv4Addr);
          const cmd = util.format("sudo ipset del -! protected_ip_set %s", ipv4Addr);
          await exec(cmd).catch((err) => {
            log.error("Failed to remove " + ipv4Addr + " from protected_ip_set", err);
          });
        }
        let ipv6Addrs = [];
        if (macEntry.ipv6Addr)
          ipv6Addrs = JSON.parse(macEntry.ipv6Addr);
        if (ipv6Addrs && ipv6Addrs.length > 0) {
          for (let j in ipv6Addrs) {
            const ipv6Addr = ipv6Addrs[j];
            if (ipv6Addr && ip.isV6Format(ipv6Addr)) {
              log.info("Remove ip from protected_ip_set6: " + ipv6Addr);
              const cmd = util.format("sudo ipset add -! protected_ip_set6 %s", ipv6Addr);
              await exec(cmd).catch((err) => {
                log.error("Failed to remove " + ipv6Addr + " from protected_ip_set6", err);
              });
            }
          }
        }
        delete this.protected_macs[mac];
      } else {
        log.warn("Device " + mac + " is not protected, no need to deactivate shield.");
      }
    }
  }
}

module.exports = ShieldManager;<|endoftext|>


<commit_before>import React, {Component} from 'react'
import PropTypes from 'prop-types'
import injectSheet from 'react-jss'
import times from 'lodash/times'

import theme from '../theme'

import {
  connectFrequencyToAnalyser,
  getFrequencyData,
  castToFraction
} from '../utils/audio'

// TODO: Make changable via controls
const amount = 256

const radius = 100
const maxSoundRadius = 200

const styles = {
  player: {
    width: radius * 2,
    height: radius * 2,
    position: 'relative',
    transform: ({rotation}) => `rotate(${rotation}deg)`,
    '&::after': {
      content: '""',
      width: radius * 6,
      height: radius * 6,
      position: 'absolute',
      zIndex: 1,
      background: `radial-gradient(closest-side, ${theme.active}, transparent)`,
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',
      opacity: 0.15
    }
  },
  circle: {
    width: '100%',
    height: '100%',
    borderRadius: '50%',
    position: 'relative',
    zIndex: 3,
    background: theme.background,
    boxShadow: [{
      blur: 30,
      spread: 2,
      color: theme.active
    }, {
      inset: 'inset',
      blur: 10,
      color: theme.active
    }]
  },
  bar: {
    transformOrigin: [0, '50%'],
    maxWidth: maxSoundRadius,
    position: 'absolute',
    top: '50%',
    left: '50%',
    height: 2,
    borderRadius: 10,
    zIndex: 2
  }
}

times(amount, (i) => {
  styles[`bar${i}`] = {
    composes: '$bar',
    transform: `rotate(${(360 / amount) * i}deg)`,
    background: ({frequency}) => frequency && `rgba(${frequency[i]}, ${frequency[i]}, 0, ${castToFraction(frequency[i])})`,
    width: ({frequency}) => frequency && castToFraction(frequency[i]) * (maxSoundRadius - radius) + radius
  }
})

class Player extends Component {
  static propTypes = {
    sheet: PropTypes.object.isRequired,
    classes: PropTypes.object.isRequired,
    audio: PropTypes.object.isRequired
  }

  componentDidMount() {
    const {audio} = this.props

    let frequency = connectFrequencyToAnalyser(audio, {
      fftSize: amount
    })
    let rotation = 0

    const resultFrequency = new Uint8Array(frequency.length * 2)

    const getFrame = () => {
      frequency = getFrequencyData(frequency)

      // Make mirrored frequency for better visualization
      resultFrequency.set(frequency)
      resultFrequency.set(frequency, frequency.length)

      this.props.sheet.update({
        frequency: resultFrequency,
        rotation: ++rotation * 0.1
      })

      requestAnimationFrame(getFrame)
    }

    // TODO: Remove after debugging
    audio.currentTime = 0

    audio.play()
    getFrame()
  }

  shouldComponentUpdate = () => false

  componentWillUnmount() {
    this.props.audio.pause()
  }

  render() {
    const {classes} = this.props

    return (

          {times(amount, i => <div key={i} className={classes[`bar${i}`]} />)}

    )
  }
}

export default injectSheet(styles)(Player)
<commit_msg>More animation for player<commit_after>import React, {Component} from 'react'
import PropTypes from 'prop-types'
import injectSheet from 'react-jss'
import times from 'lodash/times'

import theme from '../theme'

import {
  connectFrequencyToAnalyser,
  getFrequencyData,
  castToFraction
} from '../utils/audio'

// TODO: Make changable via controls
const amount = 256

const radius = 100
const maxSoundRadius = 200

const styles = {
  player: {
    width: radius * 2,
    height: radius * 2,
    position: 'relative',
    transform: ({rotation}) => `rotate(${rotation}deg)`,
    '&::after': {
      content: '""',
      position: 'absolute',
      zIndex: 1,
      background: `radial-gradient(closest-side, ${theme.active}, transparent)`,
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',
      opacity: 0.15,
      width: ({averageFrequency}) => `${averageFrequency * 10 * radius}px`,
      height: ({averageFrequency}) => `${averageFrequency * 10 * radius}px`
    }
  },
  circle: {
    width: '100%',
    height: '100%',
    borderRadius: '50%',
    position: 'relative',
    zIndex: 3,
    background: theme.background,
    transform: ({averageFrequency}) => `scale(${1 + (averageFrequency / 3)})`,
    boxShadow: ({averageFrequency}) => {
      if (averageFrequency <= 0.5) return `0 0 5px 1px ${theme.active}, inset 0 0 5px 1px ${theme.active}`
      return `0 0 ${averageFrequency * 30}px 2px ${theme.active}, inset 0 0 ${averageFrequency * 20}px 1px ${theme.active}`
    }
  },
  bar: {
    transformOrigin: [0, '50%'],
    maxWidth: maxSoundRadius,
    position: 'absolute',
    top: '50%',
    left: '50%',
    height: 2,
    borderRadius: 10,
    zIndex: 2
  }
}

times(amount, (i) => {
  styles[`bar${i}`] = {
    composes: '$bar',
    transform: `rotate(${(360 / amount) * i}deg)`,
    background: ({frequency}) => frequency && `rgba(${frequency[i]}, ${frequency[i]}, 0, ${castToFraction(frequency[i])})`,
    width: ({frequency}) => frequency && castToFraction(frequency[i]) * (maxSoundRadius - radius) + radius
  }
})

class Player extends Component {
  static propTypes = {
    sheet: PropTypes.object.isRequired,
    classes: PropTypes.object.isRequired,
    audio: PropTypes.object.isRequired
  }

  componentDidMount() {
    const {audio} = this.props

    let frequency = connectFrequencyToAnalyser(audio, {
      fftSize: amount
    })
    let rotation = 0

    const resultFrequency = new Uint8Array(frequency.length * 2)

    const getFrame = () => {
      frequency = getFrequencyData(frequency)

      // Make mirrored frequency for better visualization
      resultFrequency.set(frequency)
      resultFrequency.set(frequency, frequency.length)

      this.props.sheet.update({
        frequency: resultFrequency,
        averageFrequency: castToFraction(frequency[frequency.length / 2]),
        rotation: ++rotation * 0.1
      })

      requestAnimationFrame(getFrame)
    }

    // TODO: Remove after debugging
    audio.currentTime = 90

    audio.play()
    getFrame()
  }

  shouldComponentUpdate = () => false

  componentWillUnmount() {
    this.props.audio.pause()
  }

  render() {
    const {classes} = this.props

    return (

          {times(amount, i => <div key={i} className={classes[`bar${i}`]} />)}

    )
  }
}

export default injectSheet(styles)(Player)
<|endoftext|>


<commit_before>/*!
 * Copyright(c) 2014 Jan Blaha
 *
 * http server cluster listening on dedicated work and executing specified tasks
 */

var cluster = require('cluster')
// eslint-disable-next-line
var domain = require('domain')
var messageHandler = require('./messageHandler')

var workers = []
var currentRequests = {}
var port
var host
var inputRequestLimit
var callbackRequests = {}

if (cluster.isMaster) {
  var isRunning = false

  cluster.on('fork', function (worker) {
    worker.pid = worker.process.pid
    worker.isRunning = false
    workers.push(worker)

    worker.process.on('message', function (rawM) {
      var m = messageHandler.parse(rawM)

      if (m.action === 'register') {
        var worker = workers.find(w => w.pid === m.pid)

        // maybe worker was recycled before it started? unlikely, but to be sure we don't crash the master
        if (worker) {
          currentRequests[m.rid] = worker

          process.send(messageHandler.serialize({
            action: 'register',
            rid: m.rid
          }))
        }
      }

      if (m.action === 'completed') {
        delete currentRequests[m.rid]
      }

      if (m.action === 'callback') {
        process.send(messageHandler.serialize(m))
      }
    })

    worker.on('exit', function (w, code, signal) {
      workers = workers.filter(w => w.pid !== worker.pid)

      var keysToDelete = []

      for (var key in currentRequests) {
        if (currentRequests[key].pid === worker.pid) {
          keysToDelete.push(key)
        }
      }

      keysToDelete.forEach(function (k) {
        delete currentRequests[k]
      })

      cluster.fork()
    })

    worker.send(messageHandler.serialize({
      action: 'start',
      port: port,
      host: host,
      inputRequestLimit: inputRequestLimit
    }))
  })

  cluster.on('listening', function (worker) {
    if (isRunning) {
      return
    }

    worker.isRunning = true

    if (!workers.find(w => w.isRunning === false)) {
      isRunning = true

      process.send(messageHandler.serialize({
        action: 'running'
      }))
    }
  })

  process.on('message', function (rawM) {
    var m = messageHandler.parse(rawM)
    var worker

    if (m.action === 'kill') {
      worker = currentRequests[m.rid]

      if (worker) {
        worker.process.kill('SIGKILL')
      }
    }

    if (m.action === 'start') {
      port = m.port
      host = m.host
      inputRequestLimit = m.inputRequestLimit

      for (var i = 0; i < m.numberOfWorkers; i++) {
        cluster.fork()
      }
    }

    if (m.action === 'callback-response') {
      worker = currentRequests[m.rid]

      // worker could be recycled in the meantime
      if (worker) {
        worker.send(messageHandler.serialize(m))
      }
    }
  })
}

if (!cluster.isMaster) {
  var startListening = function (port, host) {
    var server = require('http').createServer(function (req, res) {
      // NOTE: we're still using domains here intentionally,
      // we have tried to avoid its usage but unfortunately there is no other way to
      // ensure that we are handling all kind of errors that can occur in an external script,
      // but everything is ok because node.js will only remove domains when they found an alternative
      // and when that time comes, we just need to migrate to that alternative.
      var d = domain.create()

      d.on('error', function (er) {
        try {
          // make sure we close down within 30 seconds
          var killtimer = setTimeout(function () {
            process.exit(1)
          }, 30000)

          // But don't keep the process open just for that!
          killtimer.unref()

          // stop taking new requests.
          server.close()

          // Let the master know we're dead.  This will trigger a
          // 'disconnect' in the cluster master, and then it will fork
          // a new worker.
          if (cluster) {
            cluster.worker.disconnect()
          }

          error(res, er)
        } catch (er2) {
          // oh well, not much we can do at this point.
          console.error('Error sending 500!', er2.stack)
        }
      })

      d.add(req)
      d.add(res)
      d.req = req

      d.run(function () {
        processRequest(req, res)
      })
    })

    server.listen(port, host)
  }

  process.on('message', function (rawM) {
    var m = messageHandler.parse(rawM)
    inputRequestLimit = m.inputRequestLimit

    if (m.action === 'start') {
      startListening(m.port, m.host)
    }

    if (m.action === 'callback-response') {
      callbackRequests[m.rid](m)
    }
  })
}

function error (res, err) {
  res.writeHead(500)

  res.end(messageHandler.serialize({
    error: {
      message: err.message,
      stack: err.stack
    }
  }))
}

function processRequest (req, res) {
  var body = []
  var length = 0

  req.on('data', function (data) {
    body.push(data)
    length += data.length

    if (length > inputRequestLimit) {
      error(res, new Error('Input request exceeded inputRequestLimit'))
      res.destroy()
    }
  })

  req.on('end', function () {
    req.body = messageHandler.parse(Buffer.concat(body).toString())

    process.send(messageHandler.serialize({
      action: 'register',
      rid: req.body.options.rid,
      pid: process.pid
    }))

    try {
      var callback = function () {
        var cb = arguments[arguments.length - 1]

        callbackRequests[req.body.options.rid] = function (m) {
          if (m.params.length) {
            if (m.params[0]) {
              m.params[0] = new Error(m.params[0])
            }
          }

          cb.apply(this, m.params)

          delete callbackRequests[req.body.options.rid]
        }

        var args = Array.prototype.slice.call(arguments)

        args.pop()

        process.send(messageHandler.serialize({
          action: 'callback',
          rid: req.body.options.rid,
          pid: process.pid,
          params: args.sort()
        }))
      }

      require(req.body.options.execModulePath)(req.body.inputs, callback, function (err, val) {
        if (err) {
          return error(res, err)
        }

        res.end(messageHandler.serialize(val))
      })
    } catch (e) {
      error(res, e)
    }
  })
}
<commit_msg>Remove timeout from http-server workers for long-running scripts<commit_after>/*!
 * Copyright(c) 2014 Jan Blaha
 *
 * http server cluster listening on dedicated work and executing specified tasks
 */

var cluster = require('cluster')
// eslint-disable-next-line
var domain = require('domain')
var messageHandler = require('./messageHandler')

var workers = []
var currentRequests = {}
var port
var host
var inputRequestLimit
var callbackRequests = {}

if (cluster.isMaster) {
  var isRunning = false

  cluster.on('fork', function (worker) {
    worker.pid = worker.process.pid
    worker.isRunning = false
    workers.push(worker)

    worker.process.on('message', function (rawM) {
      var m = messageHandler.parse(rawM)

      if (m.action === 'register') {
        var worker = workers.find(w => w.pid === m.pid)

        // maybe worker was recycled before it started? unlikely, but to be sure we don't crash the master
        if (worker) {
          currentRequests[m.rid] = worker

          process.send(messageHandler.serialize({
            action: 'register',
            rid: m.rid
          }))
        }
      }

      if (m.action === 'completed') {
        delete currentRequests[m.rid]
      }

      if (m.action === 'callback') {
        process.send(messageHandler.serialize(m))
      }
    })

    worker.on('exit', function (w, code, signal) {
      workers = workers.filter(w => w.pid !== worker.pid)

      var keysToDelete = []

      for (var key in currentRequests) {
        if (currentRequests[key].pid === worker.pid) {
          keysToDelete.push(key)
        }
      }

      keysToDelete.forEach(function (k) {
        delete currentRequests[k]
      })

      cluster.fork()
    })

    worker.send(messageHandler.serialize({
      action: 'start',
      port: port,
      host: host,
      inputRequestLimit: inputRequestLimit
    }))
  })

  cluster.on('listening', function (worker) {
    if (isRunning) {
      return
    }

    worker.isRunning = true

    if (!workers.find(w => w.isRunning === false)) {
      isRunning = true

      process.send(messageHandler.serialize({
        action: 'running'
      }))
    }
  })

  process.on('message', function (rawM) {
    var m = messageHandler.parse(rawM)
    var worker

    if (m.action === 'kill') {
      worker = currentRequests[m.rid]

      if (worker) {
        worker.process.kill('SIGKILL')
      }
    }

    if (m.action === 'start') {
      port = m.port
      host = m.host
      inputRequestLimit = m.inputRequestLimit

      for (var i = 0; i < m.numberOfWorkers; i++) {
        cluster.fork()
      }
    }

    if (m.action === 'callback-response') {
      worker = currentRequests[m.rid]

      // worker could be recycled in the meantime
      if (worker) {
        worker.send(messageHandler.serialize(m))
      }
    }
  })
}

if (!cluster.isMaster) {
  var startListening = function (port, host) {
    var server = require('http').createServer(function (req, res) {
      // NOTE: we're still using domains here intentionally,
      // we have tried to avoid its usage but unfortunately there is no other way to
      // ensure that we are handling all kind of errors that can occur in an external script,
      // but everything is ok because node.js will only remove domains when they found an alternative
      // and when that time comes, we just need to migrate to that alternative.
      var d = domain.create()

      d.on('error', function (er) {
        try {
          // make sure we close down within 30 seconds
          var killtimer = setTimeout(function () {
            process.exit(1)
          }, 30000)

          // But don't keep the process open just for that!
          killtimer.unref()

          // stop taking new requests.
          server.close()

          // Let the master know we're dead.  This will trigger a
          // 'disconnect' in the cluster master, and then it will fork
          // a new worker.
          if (cluster) {
            cluster.worker.disconnect()
          }

          error(res, er)
        } catch (er2) {
          // oh well, not much we can do at this point.
          console.error('Error sending 500!', er2.stack)
        }
      })

      d.add(req)
      d.add(res)
      d.req = req

      d.run(function () {
        processRequest(req, res)
      })
    })

    server.timeout = 0
    server.listen(port, host)
  }

  process.on('message', function (rawM) {
    var m = messageHandler.parse(rawM)
    inputRequestLimit = m.inputRequestLimit

    if (m.action === 'start') {
      startListening(m.port, m.host)
    }

    if (m.action === 'callback-response') {
      callbackRequests[m.rid](m)
    }
  })
}

function error (res, err) {
  res.writeHead(500)

  res.end(messageHandler.serialize({
    error: {
      message: err.message,
      stack: err.stack
    }
  }))
}

function processRequest (req, res) {
  var body = []
  var length = 0

  req.on('data', function (data) {
    body.push(data)
    length += data.length

    if (length > inputRequestLimit) {
      error(res, new Error('Input request exceeded inputRequestLimit'))
      res.destroy()
    }
  })

  req.on('end', function () {
    req.body = messageHandler.parse(Buffer.concat(body).toString())

    process.send(messageHandler.serialize({
      action: 'register',
      rid: req.body.options.rid,
      pid: process.pid
    }))

    try {
      var callback = function () {
        var cb = arguments[arguments.length - 1]

        callbackRequests[req.body.options.rid] = function (m) {
          if (m.params.length) {
            if (m.params[0]) {
              m.params[0] = new Error(m.params[0])
            }
          }

          cb.apply(this, m.params)

          delete callbackRequests[req.body.options.rid]
        }

        var args = Array.prototype.slice.call(arguments)

        args.pop()

        process.send(messageHandler.serialize({
          action: 'callback',
          rid: req.body.options.rid,
          pid: process.pid,
          params: args.sort()
        }))
      }

      require(req.body.options.execModulePath)(req.body.inputs, callback, function (err, val) {
        if (err) {
          return error(res, err)
        }

        res.end(messageHandler.serialize(val))
      })
    } catch (e) {
      error(res, e)
    }
  })
}
<|endoftext|>


<commit_before><commit_msg>Reverted more HMR code<commit_after><|endoftext|>


<commit_before>/* eslint-disable no-console */
import React, { PropTypes } from 'react';

// @TODO: check for an alternative to remove global dependency
function getWidgets(name) {
  return window.app.getWidgets(name);
}

function getObservable(name) {
  return window.app.observeWidgets(name);
}

function isRootAppAvailable() {
  return window.app;
}

export default React.createClass({
  propTypes: {
    name: PropTypes.string.isRequired
  },

  componentDidMount() {
    const observable = getObservable();

    this.subscription = observable.subscribe({
      // @TODO: this can be optimized further
      next: () => {
        this.setState({
          list: getWidgets(this.props.name)
        });

        this.state.list.forEach((widget) => {
          if (!isRootAppAvailable()) {
            return;
          }

          const widgetName = widget.getOption('name');

          // @TODO: later re-implement this check with observables
          const rootApp = widget.getRootApp();
          const areDependenciesLoaded = widget.readableApps.length > 0
            ? widget.readableApps.every((readableApp) => rootApp.getStore(readableApp))
            : true;

          if (!areDependenciesLoaded) {
            return;
          }

          const existsInState = this.state.listForRendering.some((item) => {
            return item.name === widgetName;
          });

          if (existsInState) {
            return;
          }

          const WidgetComponent = widget.render();
          const WrapperComponent = React.createClass({
            componentWillMount() {
              widget.beforeMount();
            },

            componentDidMount() {
              widget.afterMount();
            },

            componentWillUnmount() {
              widget.beforeUnmount();
            },

            render() {
              return <WidgetComponent />;
            }
          });

          const { listForRendering } = this.state;
          listForRendering.push({
            name: widgetName,
            Component: WrapperComponent
          });

          this.setState({ listForRendering });
        });
      },
      error: (err) => {
        console.warn(`Subscription error for <Region name="${this.props.name}" />:`, err);
      }
    });
  },

  componentWillUnmount() {
    this.subscription.unsubscribe();
  },

  getInitialState() {
    return {
      list: [], // array of widgetApps
      listForRendering: [] // array of {name, component} objects
    };
  },

  render() {
    const { listForRendering } = this.state;

    if (listForRendering.length === 0) {
      return null;
    }

    return (

        {listForRendering.map((item) => {
          const { Component, name } = item;

          return (
            <Component key={name} />
          );
        })}

    );
  }
});
<commit_msg>Fix rendering twice issue (#2)<commit_after>/* eslint-disable no-console */
import React, { PropTypes } from 'react';

// @TODO: check for an alternative to remove global dependency
function getWidgets(name) {
  return window.app.getWidgets(name);
}

function getObservable(name) {
  return window.app.observeWidgets(name);
}

function isRootAppAvailable() {
  return window.app;
}

export default React.createClass({
  propTypes: {
    name: PropTypes.string.isRequired
  },

  componentWillMount() {
    const observable = getObservable();

    this.subscription = observable.subscribe({
      // @TODO: this can be optimized further
      next: () => {
        this.setState({
          list: getWidgets(this.props.name)
        });

        this.state.list.forEach((widget) => {
          if (!isRootAppAvailable()) {
            return;
          }

          const widgetName = widget.getOption('name');

          // @TODO: later re-implement this check with observables
          const rootApp = widget.getRootApp();
          const areDependenciesLoaded = widget.readableApps.length > 0
            ? widget.readableApps.every((readableApp) => rootApp.getStore(readableApp))
            : true;

          if (!areDependenciesLoaded) {
            return;
          }

          const existsInState = this.state.listForRendering.some((item) => {
            return item.name === widgetName;
          });

          if (existsInState) {
            return;
          }

          const WidgetComponent = widget.render();
          const WrapperComponent = React.createClass({
            componentWillMount() {
              widget.beforeMount();
            },

            componentDidMount() {
              widget.afterMount();
            },

            componentWillUnmount() {
              widget.beforeUnmount();
            },

            render() {
              return <WidgetComponent />;
            }
          });

          const { listForRendering } = this.state;
          listForRendering.push({
            name: widgetName,
            Component: WrapperComponent
          });

          this.setState({ listForRendering });
        });
      },
      error: (err) => {
        console.warn(`Subscription error for <Region name="${this.props.name}" />:`, err);
      }
    });
  },

  componentWillUnmount() {
    this.subscription.unsubscribe();
  },

  getInitialState() {
    return {
      list: [], // array of widgetApps
      listForRendering: [] // array of {name, component} objects
    };
  },

  render() {
    const { listForRendering } = this.state;

    if (listForRendering.length === 0) {
      return null;
    }

    return (

        {listForRendering.map((item) => {
          const { Component, name } = item;

          return (
            <Component key={name} />
          );
        })}

    );
  }
});
<|endoftext|>


<commit_before><commit_msg>Readd webpack publicPath<commit_after><|endoftext|>


<commit_before>var chai        = require('chai')
  , expect      = chai.expect
  , Support     = require(__dirname + '/support')
  , dialect     = Support.getTestDialect()
  , Transaction = require(__dirname + '/../lib/transaction')
  , sinon       = require('sinon')

describe(Support.getTestDialectTeaser("Transaction"), function () {
  this.timeout(4000);
  describe('constructor', function() {
    it('stores options', function() {
      var transaction = new Transaction(this.sequelize)
      expect(transaction.options).to.be.an.instanceOf(Object)
    })

    it('generates an identifier', function() {
      var transaction = new Transaction(this.sequelize)
      expect(transaction.id).to.exist
    })
  })

  describe('commit', function() {
    it('is a commit method available', function() {
      expect(Transaction).to.respondTo('commit')
    })
  })

  describe('rollback', function() {
    it('is a rollback method available', function() {
      expect(Transaction).to.respondTo('rollback')
    })
  })

  if (dialect !== 'sqlite') {
    describe('row locking', function () {
      this.timeout(10000);
      it('supports for update', function (done) {
        var User = this.sequelize.define('user', {
              username: Support.Sequelize.STRING,
              awesome: Support.Sequelize.BOOLEAN
            })
          , self = this
          , t1Spy = sinon.spy()
          , t2Spy = sinon.spy()

        this.sequelize.sync({ force: true }).then(function () {
          return User.create({ username: 'jan'})
        }).then(function () {
          self.sequelize.transaction().then(function (t1) {
            return User.find({
              where: {
                username: 'jan'
              }
            }, {
              lock: t1.LOCK.UPDATE,
              transaction: t1
            }).then(function (t1Jan) {
              self.sequelize.transaction({
                isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
              }).then(function (t2) {
                User.find({
                  where: {
                    username: 'jan'
                  },
                }, {
                  lock: t2.LOCK.UPDATE,
                  transaction: t2
                }).then(function () {
                  t2Spy()
                  t2.commit().then(function () {
                    expect(t2Spy).to.have.been.calledAfter(t1Spy) // Find should not succeed before t1 has comitted
                    done()
                  })
                })

                t1Jan.updateAttributes({
                  awesome: true
                }, { transaction: t1}).then(function () {
                  t1Spy()
                  setTimeout(t1.commit.bind(t1), 2000)
                })
              })
            })
          })
        })
      })

      it('supports for share', function (done) {
        var User = this.sequelize.define('user', {
              username: Support.Sequelize.STRING,
              awesome: Support.Sequelize.BOOLEAN
            })
          , self = this
          , t1Spy = sinon.spy()
          , t2FindSpy = sinon.spy()
          , t2UpdateSpy = sinon.spy()

        this.sequelize.sync({ force: true }).then(function () {
          return User.create({ username: 'jan'})
        }).then(function () {
          self.sequelize.transaction().then(function (t1) {
            return User.find({
              where: {
                username: 'jan'
              }
            }, {
              lock: t1.LOCK.SHARE,
              transaction: t1
            }).then(function (t1Jan) {
              self.sequelize.transaction({
                isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
              }).then(function (t2) {
                User.find({
                  where: {
                    username: 'jan'
                  }
                }, { transaction: t2}).then(function (t2Jan) {
                  t2FindSpy()

                  t2Jan.updateAttributes({
                    awesome: false
                  }, {
                    transaction: t2
                  }).then(function () {
                    t2UpdateSpy()
                    t2.commit().then(function () {
                      expect(t2FindSpy).to.have.been.calledBefore(t1Spy) // The find call should have returned
                      expect(t2UpdateSpy).to.have.been.calledAfter(t1Spy) // But the update call should not happen before the first transaction has committed
                      done()
                    })
                  })
                })

                t1Jan.updateAttributes({
                  awesome: true
                }, {
                  transaction: t1
                }).then(function () {
                  setTimeout(function () {
                    t1Spy()
                    t1.commit()
                  }, 2000)
                })
              })
            })
          })
        })
      })
    })
  }
})
<commit_msg>chore: semicolons<commit_after>var chai        = require('chai')
  , expect      = chai.expect
  , Support     = require(__dirname + '/support')
  , dialect     = Support.getTestDialect()
  , Transaction = require(__dirname + '/../lib/transaction')
  , sinon       = require('sinon');

describe(Support.getTestDialectTeaser("Transaction"), function () {
  this.timeout(4000);
  describe('constructor', function() {
    it('stores options', function() {
      var transaction = new Transaction(this.sequelize);
      expect(transaction.options).to.be.an.instanceOf(Object);
    });

    it('generates an identifier', function() {
      var transaction = new Transaction(this.sequelize);
      expect(transaction.id).to.exist;
    });
  });

  describe('commit', function() {
    it('is a commit method available', function() {
      expect(Transaction).to.respondTo('commit');
    });
  });

  describe('rollback', function() {
    it('is a rollback method available', function() {
      expect(Transaction).to.respondTo('rollback');
    });
  });

  if (dialect !== 'sqlite') {
    describe('row locking', function () {
      this.timeout(10000);
      it('supports for update', function (done) {
        var User = this.sequelize.define('user', {
            username: Support.Sequelize.STRING,
            awesome: Support.Sequelize.BOOLEAN
          })
          , self = this
          , t1Spy = sinon.spy()
          , t2Spy = sinon.spy();

        this.sequelize.sync({ force: true }).then(function () {
          return User.create({ username: 'jan'});
        }).then(function () {
          self.sequelize.transaction().then(function (t1) {
            return User.find({
              where: {
                username: 'jan'
              }
            }, {
              lock: t1.LOCK.UPDATE,
              transaction: t1
            }).then(function (t1Jan) {
              self.sequelize.transaction({
                isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
              }).then(function (t2) {
                User.find({
                  where: {
                    username: 'jan'
                  },
                }, {
                  lock: t2.LOCK.UPDATE,
                  transaction: t2
                }).then(function () {
                  t2Spy()
                  t2.commit().then(function () {
                    expect(t2Spy).to.have.been.calledAfter(t1Spy); // Find should not succeed before t1 has comitted
                    done();
                  });
                });

                t1Jan.updateAttributes({
                  awesome: true
                }, { transaction: t1}).then(function () {
                  t1Spy()
                  setTimeout(t1.commit.bind(t1), 2000);
                });
              });
            });
          });
        });
      });

      it('supports for share', function (done) {
        var User = this.sequelize.define('user', {
            username: Support.Sequelize.STRING,
            awesome: Support.Sequelize.BOOLEAN
          })
          , self = this
          , t1Spy = sinon.spy()
          , t2FindSpy = sinon.spy()
          , t2UpdateSpy = sinon.spy();

        this.sequelize.sync({ force: true }).then(function () {
          return User.create({ username: 'jan'});
        }).then(function () {
          self.sequelize.transaction().then(function (t1) {
            return User.find({
              where: {
                username: 'jan'
              }
            }, {
              lock: t1.LOCK.SHARE,
              transaction: t1
            }).then(function (t1Jan) {
              self.sequelize.transaction({
                isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
              }).then(function (t2) {
                User.find({
                  where: {
                    username: 'jan'
                  }
                }, { transaction: t2}).then(function (t2Jan) {
                  t2FindSpy();

                  t2Jan.updateAttributes({
                    awesome: false
                  }, {
                    transaction: t2
                  }).then(function () {
                    t2UpdateSpy();
                    t2.commit().then(function () {
                      expect(t2FindSpy).to.have.been.calledBefore(t1Spy); // The find call should have returned
                      expect(t2UpdateSpy).to.have.been.calledAfter(t1Spy); // But the update call should not happen before the first transaction has committed
                      done();
                    });
                  });
                });

                t1Jan.updateAttributes({
                  awesome: true
                }, {
                  transaction: t1
                }).then(function () {
                  setTimeout(function () {
                    t1Spy();
                    t1.commit();
                  }, 2000);
                });
              });
            });
          });
        });
      });
    });
  }
});
<|endoftext|>


<commit_before>import React, {
  Component,
  PropTypes,
  StyleSheet,
  Text,
  TextInput,
  View,
  ScrollView,
  TouchableHighlight,
  PickerIOS,
  Slider,
  StatusBar
} from 'react-native';
import globalVariables from '../styles/globalVariables.js'
import PricePickerContainer from './PricePickerContainer.js'
import YearPickerContainer from './YearPickerContainer.js'
import CarConditionPicker from './CarConditionPicker.js';
import CarMakePickerContainer from './CarMakePickerContainer.js';
import ZipCodeContainer from './ZipCodeContainer.js';
import setQueryAction from '../actions/setQueryAction.js';
import searchActions from '../actions/searchActions.js';
import MultiSlider from 'react-native-multi-slider';
import Immutable from 'immutable';
import { connect } from 'react-redux';
import HeaderContainer from './common/HeaderContainer.js';
import Icon from 'react-native-vector-icons/Ionicons';
import ListViewer from './common/ListViewer.js';
import { Actions } from 'react-native-router-flux';

let PickerItemIOS = PickerIOS.Item;

@connect(state => ({
  query: state.search,
  CAR_MAKES_AND_MODELS: state.search.allCars
}))
export default class Search extends Component {
  static propTypes = {
    dispatch: React.PropTypes.func.isRequired,
    query: React.PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);
  }

  goToResults() {
    console.log('going');
    console.log(this.props.query);
    this.props.dispatch(searchActions(this.props.query));
  }

  handleLogout() {
    Actions.Login();
  }

  render() {
    var action = Actions
    const rightItem = {
      title: 'ios-heart',
      icon: 'ios-heart',
      onPress: 'Actions.Favorites.bind(this)'
    };
    const leftItem = {
      title: 'ios-car',
      icon: 'ios-car',
      onPress: 'Actions.Results.bind(this)'
    }
    return (
      <HeaderContainer
        title="Search"
        // parallaxContent={profilePicture}
        backgroundImage={require('../assets/images/main-background.png')}
        backgroundColor={'#A8D769'}
        // onSegmentChange={this.handleSegmentChanged}
        leftItem={leftItem}
        rightItem={rightItem}>
        <ListViewer
        renderEmptyList={this.renderScrollView.bind(this)}

        >
        </ListViewer>

      </HeaderContainer>

  )
  }
  renderScrollView(){
    return (
        <View style={styles.container} >
          <View style={styles.page}>
          <CarMakePickerContainer />
          <PricePickerContainer />
          <YearPickerContainer />
          <ZipCodeContainer />
          <CarConditionPicker />

        <TouchableHighlight
          underlayColor="#88D4F5"
          onPress={this.goToResults.bind(this)}
        >
        <Text>Search </Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={this.handleLogout.bind(this)}>
        <Text style={styles.loginText}>Logout</Text></TouchableHighlight>
        </View>
        </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 15,
    backgroundColor: globalVariables.background
  },

  page: {
    paddingBottom: 50
  },

  searchButton: {
    padding: 14,
    backgroundColor: globalVariables.green
  },

  searchButtonText: {
    fontSize: 16,
    color: 'white',
    textAlign: 'center'
  },

  loginText: {
    textAlign: 'center',
    color: 'black',
    marginBottom: 5,
    textDecorationLine: 'underline'
  }
});
<commit_msg>Added styling to search page button<commit_after>import React, {
  Component,
  PropTypes,
  StyleSheet,
  Text,
  TextInput,
  View,
  ScrollView,
  TouchableHighlight,
  PickerIOS,
  Slider,
  StatusBar
} from 'react-native';
import globalVariables from '../styles/globalVariables.js'
import PricePickerContainer from './PricePickerContainer.js'
import YearPickerContainer from './YearPickerContainer.js'
import CarConditionPicker from './CarConditionPicker.js';
import CarMakePickerContainer from './CarMakePickerContainer.js';
import ZipCodeContainer from './ZipCodeContainer.js';
import setQueryAction from '../actions/setQueryAction.js';
import searchActions from '../actions/searchActions.js';
import MultiSlider from 'react-native-multi-slider';
import Immutable from 'immutable';
import { connect } from 'react-redux';
import HeaderContainer from './common/HeaderContainer.js';
import Icon from 'react-native-vector-icons/Ionicons';
import ListViewer from './common/ListViewer.js';
import { Actions } from 'react-native-router-flux';

let PickerItemIOS = PickerIOS.Item;

@connect(state => ({
  query: state.search,
  CAR_MAKES_AND_MODELS: state.search.allCars
}))
export default class Search extends Component {
  static propTypes = {
    dispatch: React.PropTypes.func.isRequired,
    query: React.PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);
  }

  goToResults() {
    console.log('going');
    console.log(this.props.query);
    this.props.dispatch(searchActions(this.props.query));
  }

  handleLogout() {
    Actions.Login();
  }

  render() {
    var action = Actions
    const rightItem = {
      title: 'ios-heart',
      icon: 'ios-heart',
      onPress: 'Actions.Favorites.bind(this)'
    };
    const leftItem = {
      title: 'ios-car',
      icon: 'ios-car',
      onPress: 'Actions.Results.bind(this)'
    }
    return (
      <HeaderContainer
        title="Search"
        // parallaxContent={profilePicture}
        backgroundImage={require('../assets/images/main-background.png')}
        backgroundColor={'#A8D769'}
        // onSegmentChange={this.handleSegmentChanged}
        leftItem={leftItem}
        rightItem={rightItem}>
        <ListViewer
        renderEmptyList={this.renderScrollView.bind(this)}

        >
        </ListViewer>

      </HeaderContainer>

  )
  }
  renderScrollView(){
    return (
        <View style={styles.container} >
          <View style={styles.page}>
          <CarMakePickerContainer />
          <PricePickerContainer />
          <YearPickerContainer />
          <ZipCodeContainer />
          <CarConditionPicker />

        <TouchableHighlight
          underlayColor="#88D4F5"
          onPress={this.goToResults.bind(this)}
          style={styles.searchButton}
        >
        <Text style={styles.searchButtonText}>Search</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={this.handleLogout.bind(this)}>
        <Text style={styles.loginText}>Logout</Text></TouchableHighlight>
        </View>
        </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 15,
    backgroundColor: globalVariables.background
  },

  page: {
    paddingBottom: 50
  },

  searchButton: {
    padding: 14,
    backgroundColor: globalVariables.green,
    alignSelf: 'stretch',
    justifyContent: 'center',
    borderRadius: 8,
    height: 40,
    borderColor: globalVariables.green,
  },

  searchButtonText: {
    fontSize: 16,
    color: 'white',
    textAlign: 'center'
  },

  loginText: {
    textAlign: 'center',
    color: 'black',
    marginBottom: 5,
    textDecorationLine: 'underline',
    marginTop: 10
  }
});

<|endoftext|>


<commit_before>const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const WebpackMd5Hash = require('webpack-md5-hash');

//=========================================================
//  ENVIRONMENT VARS
//---------------------------------------------------------
const NODE_ENV = process.env.NODE_ENV;

const ENV_DEVELOPMENT = NODE_ENV === 'development';
const ENV_PRODUCTION = NODE_ENV === 'production';
const ENV_TEST = NODE_ENV === 'test';

// ----------------------
const HOST = '0.0.0.0';
const PORT = 3000;

//=========================================================
//  LOADERS
//---------------------------------------------------------
const loaders = {
  js: {test: /\.js$/, exclude: /node_modules/, loader: 'babel'},
  scss: {test: /\.scss$/, loader: 'style!css!postcss!sass'}
};

//=========================================================
//  CONFIG
//---------------------------------------------------------
const config = {};
module.exports = config;

config.resolve = {
  extensions: ['', '.js'],
  modulesDirectories: ['node_modules'],
  root: path.resolve('.')
};

config.plugins = [
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(NODE_ENV)
  })
];

config.postcss = [
  autoprefixer({ browsers: ['last 3 versions'] })
];

config.sassLoader = {
  outputStyle: 'compressed',
  precision: 10,
  sourceComments: false
};

//=====================================
//  DEVELOPMENT or PRODUCTION
//-------------------------------------
if (ENV_DEVELOPMENT || ENV_PRODUCTION) {
  config.entry = {
    main: ['./src/main.js']
  };

  config.output = {
    filename: '[name].js',
    path: path.resolve('./target'),
    publicPath: '/'
  };

  config.plugins.push(
    new HtmlWebpackPlugin({
      chunkSortMode: 'dependency',
      filename: 'index.html',
      hash: false,
      inject: 'body',
      template: './src/index.html'
    })
  );
}

//=====================================
//  DEVELOPMENT
//-------------------------------------
if (ENV_DEVELOPMENT) {
  config.devtool = 'cheap-module-source-map';

  config.entry.main.unshift(
    `webpack-dev-server/client?http://${HOST}:${PORT}`,
    'webpack/hot/only-dev-server',
    'react-hot-loader/patch',
    'babel-polyfill'
  );

  config.module = {
    loaders: [
      loaders.js,
      loaders.scss
    ]
  };

  config.plugins.push(
    new webpack.HotModuleReplacementPlugin()
  );

  config.devServer = {
    contentBase: './src',
    historyApiFallback: true,
    host: HOST,
    hot: true,
    port: PORT,
    publicPath: config.output.publicPath,
    stats: {
      cached: true,
      cachedAssets: true,
      chunks: true,
      chunkModules: false,
      colors: true,
      hash: false,
      reasons: true,
      timings: true,
      version: false
    }
  };
}

//=====================================
//  PRODUCTION
//-------------------------------------
if (ENV_PRODUCTION) {
  config.devtool = 'source-map';

  config.entry.vendor = './src/vendor.js';

  config.output.filename = '[name].[chunkhash].js';

  config.module = {
    loaders: [
      loaders.js,
      {test: /\.scss$/, loader: ExtractTextPlugin.extract('css?-autoprefixer!postcss!sass')}
    ]
  };

  config.plugins.push(
    new WebpackMd5Hash(),
    new ExtractTextPlugin('styles.[contenthash].css'),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      mangle: true,
      compress: {
        dead_code: true, // eslint-disable-line camelcase
        screw_ie8: true, // eslint-disable-line camelcase
        unused: true,
        warnings: false
      }
    })
  );
}

//=====================================
//  TEST
//-------------------------------------
if (ENV_TEST) {
  config.devtool = 'inline-source-map';

  config.module = {
    loaders: [
      loaders.js,
      loaders.scss
    ]
  };
}
<commit_msg>Test ssh<commit_after>const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const WebpackMd5Hash = require('webpack-md5-hash');

//=========================================================
//  ENVIRONMENT VARS
//---------------------------------------------------------
const NODE_ENV = process.env.NODE_ENV;

const ENV_DEVELOPMENT = NODE_ENV === 'development';
const ENV_PRODUCTION = NODE_ENV === 'production';
const ENV_TEST = NODE_ENV === 'test';

const HOST = '0.0.0.0';
const PORT = 3000;

//=========================================================
//  LOADERS
//---------------------------------------------------------
const loaders = {
  js: {test: /\.js$/, exclude: /node_modules/, loader: 'babel'},
  scss: {test: /\.scss$/, loader: 'style!css!postcss!sass'}
};

//=========================================================
//  CONFIG
//---------------------------------------------------------
const config = {};
module.exports = config;

config.resolve = {
  extensions: ['', '.js'],
  modulesDirectories: ['node_modules'],
  root: path.resolve('.')
};

config.plugins = [
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(NODE_ENV)
  })
];

config.postcss = [
  autoprefixer({ browsers: ['last 3 versions'] })
];

config.sassLoader = {
  outputStyle: 'compressed',
  precision: 10,
  sourceComments: false
};

//=====================================
//  DEVELOPMENT or PRODUCTION
//-------------------------------------
if (ENV_DEVELOPMENT || ENV_PRODUCTION) {
  config.entry = {
    main: ['./src/main.js']
  };

  config.output = {
    filename: '[name].js',
    path: path.resolve('./target'),
    publicPath: '/'
  };

  config.plugins.push(
    new HtmlWebpackPlugin({
      chunkSortMode: 'dependency',
      filename: 'index.html',
      hash: false,
      inject: 'body',
      template: './src/index.html'
    })
  );
}

//=====================================
//  DEVELOPMENT
//-------------------------------------
if (ENV_DEVELOPMENT) {
  config.devtool = 'cheap-module-source-map';

  config.entry.main.unshift(
    `webpack-dev-server/client?http://${HOST}:${PORT}`,
    'webpack/hot/only-dev-server',
    'react-hot-loader/patch',
    'babel-polyfill'
  );

  config.module = {
    loaders: [
      loaders.js,
      loaders.scss
    ]
  };

  config.plugins.push(
    new webpack.HotModuleReplacementPlugin()
  );

  config.devServer = {
    contentBase: './src',
    historyApiFallback: true,
    host: HOST,
    hot: true,
    port: PORT,
    publicPath: config.output.publicPath,
    stats: {
      cached: true,
      cachedAssets: true,
      chunks: true,
      chunkModules: false,
      colors: true,
      hash: false,
      reasons: true,
      timings: true,
      version: false
    }
  };
}

//=====================================
//  PRODUCTION
//-------------------------------------
if (ENV_PRODUCTION) {
  config.devtool = 'source-map';

  config.entry.vendor = './src/vendor.js';

  config.output.filename = '[name].[chunkhash].js';

  config.module = {
    loaders: [
      loaders.js,
      {test: /\.scss$/, loader: ExtractTextPlugin.extract('css?-autoprefixer!postcss!sass')}
    ]
  };

  config.plugins.push(
    new WebpackMd5Hash(),
    new ExtractTextPlugin('styles.[contenthash].css'),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      mangle: true,
      compress: {
        dead_code: true, // eslint-disable-line camelcase
        screw_ie8: true, // eslint-disable-line camelcase
        unused: true,
        warnings: false
      }
    })
  );
}

//=====================================
//  TEST
//-------------------------------------
if (ENV_TEST) {
  config.devtool = 'inline-source-map';

  config.module = {
    loaders: [
      loaders.js,
      loaders.scss
    ]
  };
}
<|endoftext|>


<commit_before>import React from 'react'
import { Router } from 'dva/router'
import App from './routes/app'

const cached = {}
const registerModel = (app, model) => {
  if (!cached[model.namespace]) {
    app.model(model)
    cached[model.namespace] = 1
  }
}

export default function ({ history, app }) {
  const routes = [
    {
      path: '/',
      component: App,
      getIndexRoute (nextState, cb) {
        require.ensure([], require => {
          registerModel(app, require('./models/dashboard'))
          cb(null, { component: require('./routes/dashboard') })
        }, 'dashboard')
      },
      childRoutes: [
        {
          path: 'dashboard',
          name: 'dashboard',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              registerModel(app, require('./models/dashboard'))
              cb(null, require('./routes/dashboard'))
            }, 'dashboard')
          },
        }, {
          path: 'users',
          name: 'users',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              registerModel(app, require('./models/users'))
              cb(null, require('./routes/users'))
            }, 'users')
          },
        }, {
          path: 'ui/ico',
          name: 'ui/ico',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/ui/ico'))
            }, 'ui-ico')
          },
        }, {
          path: 'ui/search',
          name: 'ui/search',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/ui/search'))
            }, 'ui-search')
          },
        }, {
          path: 'ui/dropOption',
          name: 'ui/dropOption',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/ui/dropOption'))
            }, 'ui-dropOption')
          },
        }, {
          path: 'ui/layer',
          name: 'ui/layer',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/ui/layer'))
            }, 'ui-layer')
          },
        }, {
          path: '*',
          name: 'error',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/error'))
            }, 'error')
          },
        },
      ],
    },
  ]

  return <Router history={history} routes={routes} />
}
<commit_msg>Ajust router.js<commit_after>import React, { PropTypes } from 'react'
import { Router } from 'dva/router'
import App from './routes/app'

const cached = {}
const registerModel = (app, model) => {
  if (!cached[model.namespace]) {
    app.model(model)
    cached[model.namespace] = 1
  }
}

const Routers = function ({ history, app }) {
  const routes = [
    {
      path: '/',
      component: App,
      getIndexRoute (nextState, cb) {
        require.ensure([], require => {
          registerModel(app, require('./models/dashboard'))
          cb(null, { component: require('./routes/dashboard') })
        }, 'dashboard')
      },
      childRoutes: [
        {
          path: 'dashboard',
          name: 'dashboard',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              registerModel(app, require('./models/dashboard'))
              cb(null, require('./routes/dashboard'))
            }, 'dashboard')
          },
        }, {
          path: 'users',
          name: 'users',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              registerModel(app, require('./models/users'))
              cb(null, require('./routes/users'))
            }, 'users')
          },
        }, {
          path: 'ui/ico',
          name: 'ui/ico',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/ui/ico'))
            }, 'ui-ico')
          },
        }, {
          path: 'ui/search',
          name: 'ui/search',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/ui/search'))
            }, 'ui-search')
          },
        }, {
          path: 'ui/dropOption',
          name: 'ui/dropOption',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/ui/dropOption'))
            }, 'ui-dropOption')
          },
        }, {
          path: 'ui/layer',
          name: 'ui/layer',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/ui/layer'))
            }, 'ui-layer')
          },
        }, {
          path: '*',
          name: 'error',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/error'))
            }, 'error')
          },
        },
      ],
    },
  ]

  return <Router history={history} routes={routes} />
}

Routers.propTypes = {
  history: PropTypes.object,
  app: PropTypes.object,
}

export default Routers
<|endoftext|>


<commit_before>import React, {
  Component,
  PropTypes,
  StyleSheet,
  Text,
  TextInput,
  View,
  ScrollView,
  TouchableHighlight,
  PickerIOS,
  Slider,
  StatusBar
} from 'react-native';
import globalVariables from '../styles/globalVariables.js'
import PricePickerContainer from './PricePickerContainer.js'
import YearPickerContainer from './YearPickerContainer.js'
import CarConditionPicker from './CarConditionPicker.js';
import CarMakePickerContainer from './CarMakePickerContainer.js';
import ZipCodeContainer from './ZipCodeContainer.js';
import setQueryAction from '../actions/setQueryAction.js';
import searchActions from '../actions/searchActions.js';
import MultiSlider from 'react-native-multi-slider';
import Immutable from 'immutable';
import { connect } from 'react-redux';

let PickerItemIOS = PickerIOS.Item;

@connect(state => ({
  query: state.search,
  CAR_MAKES_AND_MODELS: state.search.allCars
}))
export default class Counter extends Component {
  static propTypes = {
    dispatch: React.PropTypes.func.isRequired,
    query: React.PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);
  }

  goToResults() {
    console.log('going');
    console.log(this.props.query);
    this.props.dispatch(searchActions(this.props.query));
  }

  render() {
    const { query, dispatch, CAR_MAKES_AND_MODELS } = this.props;
    return (
  <ScrollView style={styles.container}>
    <View style={styles.page}>
      <StatusBar hidden={false} backgroundColor='blue'/>
      <CarConditionPicker />
      <CarMakePickerContainer />
      <PricePickerContainer />
      <YearPickerContainer />
      <ZipCodeContainer />

    <TouchableHighlight
      underlayColor="#88D4F5"
      onPress={this.goToResults.bind(this)}
    >
    <Text>Search </Text>
    </TouchableHighlight>

    </View>
   </ScrollView>
)
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 15,
    backgroundColor: globalVariables.background
  },

  page: {
    paddingBottom: 50
  },

  searchButton: {
    padding: 14,
    backgroundColor: globalVariables.green
  },

  searchButtonText: {
    fontSize: 16,
    color: 'white',
    textAlign: 'center'
  }
});
<commit_msg>onPress Search routes to Results<commit_after>import React, {
  Component,
  PropTypes,
  StyleSheet,
  Text,
  TextInput,
  View,
  ScrollView,
  TouchableHighlight,
  PickerIOS,
  Slider,
  StatusBar
} from 'react-native';
import globalVariables from '../styles/globalVariables.js'
import PricePickerContainer from './PricePickerContainer.js'
import YearPickerContainer from './YearPickerContainer.js'
import CarConditionPicker from './CarConditionPicker.js';
import CarMakePickerContainer from './CarMakePickerContainer.js';
import ZipCodeContainer from './ZipCodeContainer.js';
import setQueryAction from '../actions/setQueryAction.js';
import searchActions from '../actions/searchActions.js';
import MultiSlider from 'react-native-multi-slider';
import Immutable from 'immutable';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';

let PickerItemIOS = PickerIOS.Item;

@connect(state => ({
  query: state.search,
  CAR_MAKES_AND_MODELS: state.search.allCars
}))
export default class Counter extends Component {
  static propTypes = {
    dispatch: React.PropTypes.func.isRequired,
    query: React.PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);
  }

  goToResults() {
    console.log('going');
    console.log(this.props.query);
    this.props.dispatch(searchActions(this.props.query));
    Actions.Results();
  }

  render() {
    const { query, dispatch, CAR_MAKES_AND_MODELS } = this.props;
    return (
  <ScrollView style={styles.container}>
    <View style={styles.page}>
      <StatusBar hidden={false} backgroundColor='blue'/>
      <CarConditionPicker />
      <CarMakePickerContainer />
      <PricePickerContainer />
      <YearPickerContainer />
      <ZipCodeContainer />

    <TouchableHighlight
      underlayColor="#88D4F5"
      onPress={this.goToResults.bind(this)}
    >
    <Text>Search </Text>
    </TouchableHighlight>

    </View>
   </ScrollView>
)
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 15,
    backgroundColor: globalVariables.background
  },

  page: {
    paddingBottom: 50
  },

  searchButton: {
    padding: 14,
    backgroundColor: globalVariables.green
  },

  searchButtonText: {
    fontSize: 16,
    color: 'white',
    textAlign: 'center'
  }
});
<|endoftext|>


<commit_before><commit_msg>Only use .js files as fng resources<commit_after><|endoftext|>


<commit_before>import React        from 'react'
import { merge }    from 'lodash'
import {
  Router as ReactRouter,
  RouterContext,
  browserHistory,
  createMemoryHistory,
  match
} from 'react-router'

import {
  syncHistoryWithStore,
  routerReducer
} from 'react-router-redux'

export {
  Route,
  IndexRoute,
  Redirect,
  IndexRedirect,
  Link,
  IndexLink,
} from 'react-router'

export renderer from './renderer'

export default Router

export class Router {

  static defaults = {
    routes: []
  };

  constructor(opts) {
    this.options = merge({}, Router.defaults, opts)
    this.routes = this.options.routes
  }

  registerStore(store) {
    syncHistoryWithStore(this.history, store)
  }

  getReducer() {
    return routerReducer
  }

  getComponent(renderProps, client = false) {
    return client
      ? <ReactRouter {...renderProps} />
      : <RouterContext {...renderProps} />
  }

  match(req, callback) {
    if (arguments.length === 1 && typeof req === 'function') {
      callback = req
      req = null
    }
    return match(this.createMatchOptions(req), callback)
  }

  createMatchOptions(req) {
    const opts = { routes: this.routes }
    if (req) {
      opts.history = createMemoryHistory()
      opts.location = req.url
    } else {
      opts.history = browserHistory
    }
    this.history = opts.history
    return opts
  }

}<commit_msg>Fix issue with not using upgraded history object<commit_after>import React        from 'react'
import { merge }    from 'lodash'
import {
  Router as ReactRouter,
  RouterContext,
  browserHistory,
  createMemoryHistory,
  match
} from 'react-router'

import {
  syncHistoryWithStore,
  routerReducer
} from 'react-router-redux'

export {
  Route,
  IndexRoute,
  Redirect,
  IndexRedirect,
  Link,
  IndexLink,
} from 'react-router'

export renderer from './renderer'

export default Router

export class Router {

  static defaults = {
    routes: []
  };

  constructor(opts) {
    this.options = merge({}, Router.defaults, opts)
    this.routes = this.options.routes
  }

  registerStore(store) {
    this.history = syncHistoryWithStore(this.history, store)
  }

  getReducer() {
    return routerReducer
  }

  getComponent(renderProps, client = false) {
    return client
      ? <ReactRouter {...renderProps} />
      : <RouterContext {...renderProps} />
  }

  match(req, callback) {
    if (arguments.length === 1 && typeof req === 'function') {
      callback = req
      req = null
    }
    return match(this.createMatchOptions(req), callback)
  }

  createMatchOptions(req) {
    const opts = { routes: this.routes }
    if (req) {
      opts.history = createMemoryHistory()
      opts.location = req.url
    } else {
      opts.history = browserHistory
    }
    this.history = opts.history
    return opts
  }

}<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { List } from 'immutable';
import { stringToColor, convertScales, getUUID } from 'lib';
import _zip from 'lodash/zip';

class Series extends React.Component {
  /* This class displays a line corresponding to a series.*/

  shouldComponentUpdate(nextProps) {
    const props = this.props;
    return ((nextProps.indices !== props.indices) ||
            (nextProps.values !== props.values) ||
            (nextProps.minX !== props.minX) ||
            (nextProps.minY !== props.minY) ||
            (nextProps.maxX !== props.maxX) ||
            (nextProps.maxY !== props.maxY) ||
            (nextProps.width !== props.width) ||
            (nextProps.height !== props.height));
  }

  render() {
    const props = this.props;
    const uuid = getUUID(props.modelName, props.seriesName);
    const color = stringToColor(uuid);
    const scale = props.scale;
    const maxX = scale.get('maxX');
    const minX = scale.get('minX');
    const maxY = scale.get('maxY');
    const minY = scale.get('minY');
    const width = props.width;
    const height = props.height;

    const indices = convertScales(props.indices.toJS(),
      minX, maxX, 0, width);
    const values = convertScales(props.values.toJS(),
      minY, maxY, 0, height, { invert: true });
    const pairs = _zip(indices, values);
    return (<svg className="series max absolute top-0 left-0">
      {pairs.map((pair) => (
        <circle r="0" fill={color} stroke="0" cx={pair[0]}
          cy={pair[1]} key={pair[0]}
        />
      ))}
      <polyline style={{ strokeWidth: 1, stroke: color, fill: 'none' }}
        points={pairs.map((v) => v.join(',')).join(' ')}
      />
    </svg>);
  }
}

Series.propTypes = {
  indices: PropTypes.instanceOf(List),
  values: PropTypes.instanceOf(List),
  seriesName: PropTypes.string,
  modelName: PropTypes.string,
  width: PropTypes.number,
  height: PropTypes.number,
  scale: PropTypes.object,
};

export default Series;
<commit_msg>Fix bug with shouldcompoenntupdate in series<commit_after>import React, { PropTypes } from 'react';
import { List } from 'immutable';
import { stringToColor, convertScales, getUUID } from 'lib';
import _zip from 'lodash/zip';

class Series extends React.Component {
  /* This class displays a line corresponding to a series.*/

  shouldComponentUpdate(nextProps) {
    const props = this.props;
    return ((nextProps.indices !== props.indices) ||
            (nextProps.values !== props.values) ||
            (nextProps.scale !== props.scale) ||
            (nextProps.width !== props.width) ||
            (nextProps.height !== props.height));
  }

  render() {
    const props = this.props;
    const uuid = getUUID(props.modelName, props.seriesName);
    const color = stringToColor(uuid);
    const scale = props.scale;
    const maxX = scale.get('maxX');
    const minX = scale.get('minX');
    const maxY = scale.get('maxY');
    const minY = scale.get('minY');
    const width = props.width;
    const height = props.height;

    const indices = convertScales(props.indices.toJS(),
      minX, maxX, 0, width);
    const values = convertScales(props.values.toJS(),
      minY, maxY, 0, height, { invert: true });
    const pairs = _zip(indices, values);
    return (<svg className="series max absolute top-0 left-0">
      {pairs.map((pair) => (
        <circle r="0" fill={color} stroke="0" cx={pair[0]}
          cy={pair[1]} key={pair[0]}
        />
      ))}
      <polyline style={{ strokeWidth: 1, stroke: color, fill: 'none' }}
        points={pairs.map((v) => v.join(',')).join(' ')}
      />
    </svg>);
  }
}

Series.propTypes = {
  indices: PropTypes.instanceOf(List),
  values: PropTypes.instanceOf(List),
  seriesName: PropTypes.string,
  modelName: PropTypes.string,
  width: PropTypes.number,
  height: PropTypes.number,
  scale: PropTypes.object,
};

export default Series;
<|endoftext|>


<commit_before>CubeGame.Credits = function() {};
CubeGame.Credits.prototype = {
    create: function() {
        this.credits = "Avoid the obstacles with the Cube!\nCreated with the Phaser Game Engine\n\nImages created in Inkscape\nSounds created in Audacity";
        this.creditsText = CubeGame.factory.addText(100, 50, this.credits, 30, "#5f5f5f");

        this.menuButton = this.game.add.button(100, 400, "Textures", this.menuState, this);
        this.menuButton.frameName = "MenuButton";

        this.creditsThingsGroup = this.game.add.group();
        this.creditsThingsGroup.add(this.menuButton);
        this.creditsThingsGroup.add(this.creditsText);
        this.creditsThingsSlideIn = this.game.add.tween(this.creditsThingsGroup)
            .from({x:1500}, 500, Phaser.Easing.Sinusoidal.Out).start();
    },
    menuState: function() {
        this.game.state.start("Menu");
    }
};<commit_msg>Add note in credits about Javascript/HTML5<commit_after>CubeGame.Credits = function() {};
CubeGame.Credits.prototype = {
    create: function() {
        this.credits = "Avoid the obstacles with the Cube!\nA Javascript/HTML5 Game\nCreated with the Phaser Game Engine\n\nImages created in Inkscape\nSounds created in Audacity";
        this.creditsText = CubeGame.factory.addText(100, 50, this.credits, 30, "#5f5f5f");

        this.menuButton = this.game.add.button(100, 400, "Textures", this.menuState, this);
        this.menuButton.frameName = "MenuButton";

        this.creditsThingsGroup = this.game.add.group();
        this.creditsThingsGroup.add(this.menuButton);
        this.creditsThingsGroup.add(this.creditsText);
        this.creditsThingsSlideIn = this.game.add.tween(this.creditsThingsGroup)
            .from({x:1500}, 500, Phaser.Easing.Sinusoidal.Out).start();
    },
    menuState: function() {
        this.game.state.start("Menu");
    }
};<|endoftext|>


<commit_before><commit_msg>Update androidbsc.js<commit_after><|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';

import Box from './Box';

const HEIGHT = 16;
const WIDTH = 27;
const OFFSET = 1;
const LENGTH = HEIGHT - OFFSET * 2;

const Inner = styled(Box)`
  transition: left 0.5s ease;
`;

const Switch = ({ checked, ...props }) => (
  <Box
    as="button"
    type="button"
    role="switch"
    {...props}
    aria-checked={checked}
    position="relative"
    bg={checked ? 'tertiary' : 'primary'}
    height={HEIGHT}
    width={WIDTH}
    borderRadius={18}
  >
    <Inner
      position="absolute"
      top="1px"
      left={checked ? `calc(100% - ${LENGTH}px - ${OFFSET}px)` : `${OFFSET}px`}
      height={LENGTH}
      width={LENGTH}
      borderRadius="50%"
      bg="white"
    />
  </Box>
);

Switch.propTypes = {
  checked: PropTypes.bool.isRequired,
};

export default Switch;
<commit_msg>fix: reduce Switch animation speed<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';

import Box from './Box';

const HEIGHT = 16;
const WIDTH = 27;
const OFFSET = 1;
const LENGTH = HEIGHT - OFFSET * 2;

const Inner = styled(Box)`
  transition: left 0.2s ease;
`;

const Switch = ({ checked, ...props }) => (
  <Box
    as="button"
    type="button"
    role="switch"
    {...props}
    aria-checked={checked}
    position="relative"
    bg={checked ? 'tertiary' : 'primary'}
    height={HEIGHT}
    width={WIDTH}
    borderRadius={18}
  >
    <Inner
      position="absolute"
      top="1px"
      left={checked ? `calc(100% - ${LENGTH}px - ${OFFSET}px)` : `${OFFSET}px`}
      height={LENGTH}
      width={LENGTH}
      borderRadius="50%"
      bg="white"
    />
  </Box>
);

Switch.propTypes = {
  checked: PropTypes.bool.isRequired,
};

export default Switch;
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

const electron             = require('electron');
const path                 = require('path');
const {app, BrowserWindow} = electron;
const dirname              = __dirname || path.resolve(path.dirname());
const emberAppLocation     = `file://${dirname}/dist/index.html`;

let mainWindow = null;

// Uncomment the lines below to enable Electron's crash reporter
// For more information, see http://electron.atom.io/docs/api/crash-reporter/

// electron.crashReporter.start({
//     productName: 'YourName',
//     companyName: 'YourCompany',
//     submitURL: 'https://your-domain.com/url-to-submit',
//     autoSubmit: true
// });

app.on('window-all-closed', function onWindowAllClosed() {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('ready', function onReady() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600
    });

    delete mainWindow.module;

    // If you want to open up dev tools programmatically, call
    // mainWindow.openDevTools();

    // By default, we'll open the Ember App by directly going to the
    // file system.
    //
    // Please ensure that you have set the locationType option in the
    // config/environment.js file to 'hash'. For more information,
    // please consult the ember-electron readme.
    mainWindow.loadURL(emberAppLocation);

    // If a loading operation goes wrong, we'll send Electron back to
    // Ember App entry point
    mainWindow.webContents.on('did-fail-load', () => {
        mainWindow.loadURL(emberAppLocation);
    });

    mainWindow.webContents.on('crashed', () => {
        console.log('Your Ember app (or other code) in the main window has crashed.');
        console.log('This is a serious issue that needs to be handled and/or debugged.');
    });

    mainWindow.on('unresponsive', () => {
        console.log('Your Ember app (or other code) has made the window unresponsive.');
    });

    mainWindow.on('responsive', () => {
        console.log('The main window has become responsive again.');
    });

    mainWindow.on('closed', () => {
        mainWindow = null;
    });

    // Handle an unhandled error in the main thread
    //
    // Note that 'uncaughtException' is a crude mechanism for exception handling intended to
    // be used only as a last resort. The event should not be used as an equivalent to
    // "On Error Resume Next". Unhandled exceptions inherently mean that an application is in
    // an undefined state. Attempting to resume application code without properly recovering
    // from the exception can cause additional unforeseen and unpredictable issues.
    //
    // Attempting to resume normally after an uncaught exception can be similar to pulling out
    // of the power cord when upgrading a computer -- nine out of ten times nothing happens -
    // but the 10th time, the system becomes corrupted.
    //
    // The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated
    // resources (e.g. file descriptors, handles, etc) before shutting down the process. It is
    // not safe to resume normal operation after 'uncaughtException'.
    process.on('uncaughtException', (err) => {
        console.log('An exception in the main thread was not handled.');
        console.log('This is a serious issue that needs to be handled and/or debugged.');
        console.log(`Exception: ${err}`);
    });
});
<commit_msg>maximize window<commit_after>/* jshint node: true */
'use strict';

const electron             = require('electron');
const path                 = require('path');
const {app, BrowserWindow} = electron;
const dirname              = __dirname || path.resolve(path.dirname());
const emberAppLocation     = `file://${dirname}/dist/index.html`;

let mainWindow = null;

// Uncomment the lines below to enable Electron's crash reporter
// For more information, see http://electron.atom.io/docs/api/crash-reporter/

// electron.crashReporter.start({
//     productName: 'YourName',
//     companyName: 'YourCompany',
//     submitURL: 'https://your-domain.com/url-to-submit',
//     autoSubmit: true
// });

app.on('window-all-closed', function onWindowAllClosed() {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('ready', function onReady() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600
    });
    mainWindow.maximize();

    delete mainWindow.module;

    // If you want to open up dev tools programmatically, call
    // mainWindow.openDevTools();

    // By default, we'll open the Ember App by directly going to the
    // file system.
    //
    // Please ensure that you have set the locationType option in the
    // config/environment.js file to 'hash'. For more information,
    // please consult the ember-electron readme.
    mainWindow.loadURL(emberAppLocation);

    // If a loading operation goes wrong, we'll send Electron back to
    // Ember App entry point
    mainWindow.webContents.on('did-fail-load', () => {
        mainWindow.loadURL(emberAppLocation);
    });

    mainWindow.webContents.on('crashed', () => {
        console.log('Your Ember app (or other code) in the main window has crashed.');
        console.log('This is a serious issue that needs to be handled and/or debugged.');
    });

    mainWindow.on('unresponsive', () => {
        console.log('Your Ember app (or other code) has made the window unresponsive.');
    });

    mainWindow.on('responsive', () => {
        console.log('The main window has become responsive again.');
    });

    mainWindow.on('closed', () => {
        mainWindow = null;
    });

    // Handle an unhandled error in the main thread
    //
    // Note that 'uncaughtException' is a crude mechanism for exception handling intended to
    // be used only as a last resort. The event should not be used as an equivalent to
    // "On Error Resume Next". Unhandled exceptions inherently mean that an application is in
    // an undefined state. Attempting to resume application code without properly recovering
    // from the exception can cause additional unforeseen and unpredictable issues.
    //
    // Attempting to resume normally after an uncaught exception can be similar to pulling out
    // of the power cord when upgrading a computer -- nine out of ten times nothing happens -
    // but the 10th time, the system becomes corrupted.
    //
    // The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated
    // resources (e.g. file descriptors, handles, etc) before shutting down the process. It is
    // not safe to resume normal operation after 'uncaughtException'.
    process.on('uncaughtException', (err) => {
        console.log('An exception in the main thread was not handled.');
        console.log('This is a serious issue that needs to be handled and/or debugged.');
        console.log(`Exception: ${err}`);
    });
});
<|endoftext|>