<commit_before>/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of perseo-fe
 *
 * perseo-fe is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * perseo-fe 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 perseo-fe.
 * If not, see http://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */

'use strict';

var domain = require('domain'),
    express = require('express'),
    bodyParser = require('body-parser'),
    async = require('async'),
    constants = require('./constants'),
    appContext = require('./appContext'),
    config = require('../config'),
    db = require('./db'),
    actionsRoutes = require('./routes/actionsController'),
    rulesRoutes = require('./routes/rulesController'),
    noticesRoutes = require('./routes/noticesController'),
    visualRulesRoutes = require('./routes/visualRulesController'),
    checkRoutes = require('./routes/checkController'),
    versionRoutes = require('./routes/versionController'),
    metricsRoutes = require('./routes/metricsController'),
    rules = require('./models/rules'),
    metrics = require('./models/metrics'),
    app = express(),
    server,
    logger = require('logops'),
    domainMiddleware = require('./middleware/domain').requestDomain(),
    logRequestMiddleware = require('./middleware/logRequest'),
    serviceMiddleware = require('./middleware/service'),
    errorMiddleware = require('./middleware/error'),
    myutils = require('./myutils'),
    d = domain.create();

function start(callbackStart) {
    var context = { op: 'start', comp: constants.COMPONENT_NAME };

    logger.info(context, 'starting perseo');
    logger.setLevel(config.logLevel);

    logger.getContext = function getDomainContext() {
        if (process.domain) {
            return process.domain.context;
        }
    };

    d.run(function() {
        app.disable('etag');
        app.use(serviceMiddleware.middleware());
        app.use(domainMiddleware);
        app.use(
            bodyParser.json({
                verify: function(req, res, buf) {
                    // actions are internal, not to be included
                    if (
                        req.url !== config.endpoint.actionsPath &&
                        req.url !== config.endpoint.checkPath &&
                        req.url !== config.endpoint.versionPath &&
                        req.url !== config.endpoint.logPath &&
                        req.url !== config.endpoint.metricsPath
                    ) {
                        metrics.IncMetrics(
                            req.service,
                            req.subservice,
                            metrics.incomingTransactionsRequestSize,
                            buf.length
                        );
                    }
                }
            })
        );
        app.use(logRequestMiddleware.middleware());
        app.use(errorMiddleware.middleware());

        actionsRoutes.AddTo(app);
        rulesRoutes.AddTo(app);
        noticesRoutes.AddTo(app);
        visualRulesRoutes.AddTo(app);
        checkRoutes.AddTo(app);
        versionRoutes.AddTo(app);
        metricsRoutes.AddTo(app);

        async.series(
            [
                function(callback) {
                    async.waterfall(
                        [
                            db.getDb,
                            function(db0, cbwf) {
                                appContext.SetDB(db0);
                                cbwf(null);
                            }
                        ],
                        callback
                    );
                },
                db.ping,
                db.setUp,
                function(callback) {
                    async.waterfall(
                        [
                            db.getOrionDb,
                            function(dbO, cbwf) {
                                appContext.SetOrionDB(dbO);
                                cbwf(null);
                            }
                        ],
                        callback
                    );
                },
                db.orionPing,
                function(callback) {
                    var domain = require('domain').create();
                    domain.context = {};
                    domain.context.op = 'initialRefresh';
                    domain.context.comp = constants.COMPONENT_NAME;
                    domain.context.trans = 'n/a';
                    domain.context.corr = domain.context.trans;
                    domain.context.srv = 'n/a';
                    domain.context.subsrv = 'n/a';
                    domain.run(function() {
                        rules.Refresh(callback);
                    });
                },
                function(callback) {
                    server = app.listen(config.endpoint.port, function() {
                        logger.info(context, 'listening on port %d', server.address().port);
                        return callback(null, server);
                    });
                }
            ],
            function(err) {
                myutils.logErrorIf(err, context);
                require('./refreshCore'); // Start periodical update of rules at core
                return callbackStart(err);
            }
        );
    });
}

function stop(callback) {
    var context = { op: 'stop', comp: constants.COMPONENT_NAME };
    logger.info(context, 'stopping perseo');
    async.series([server.close.bind(server), db.close, db.orionClose], function(err) {
        myutils.logErrorIf(err);
        return callback(err);
    });
}

/**
 * start starts perseo server.
 *
 *  @param {function}       callback function(error)
 */
module.exports.start = start;
/**
 * stop stops perseo server.
 *
 *  @param {function}       callback function(error)
 */
module.exports.stop = stop;
<commit_msg>Update perseo.js<commit_after>/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of perseo-fe
 *
 * perseo-fe is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * perseo-fe 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 perseo-fe.
 * If not, see http://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */

'use strict';

var domain = require('domain'),
    express = require('express'),
    bodyParser = require('body-parser'),
    async = require('async'),
    constants = require('./constants'),
    appContext = require('./appContext'),
    config = require('../config'),
    db = require('./db'),
    actionsRoutes = require('./routes/actionsController'),
    rulesRoutes = require('./routes/rulesController'),
    noticesRoutes = require('./routes/noticesController'),
    visualRulesRoutes = require('./routes/visualRulesController'),
    checkRoutes = require('./routes/checkController'),
    versionRoutes = require('./routes/versionController'),
    metricsRoutes = require('./routes/metricsController'),
    rules = require('./models/rules'),
    metrics = require('./models/metrics'),
    app = express(),
    server,
    logger = require('logops'),
    domainMiddleware = require('./middleware/domain').requestDomain(),
    logRequestMiddleware = require('./middleware/logRequest'),
    serviceMiddleware = require('./middleware/service'),
    errorMiddleware = require('./middleware/error'),
    myutils = require('./myutils'),
    d = domain.create();

function start(callbackStart) {
    var context = { op: 'start', comp: constants.COMPONENT_NAME };

    logger.info(context, 'starting perseo');
    logger.setLevel(config.logLevel);
    logger.debug(context, 'Using config:\n\n%s\n', JSON.stringify(config, null, 4));
    logger.getContext = function getDomainContext() {
        if (process.domain) {
            return process.domain.context;
        }
    };

    d.run(function() {
        app.disable('etag');
        app.use(serviceMiddleware.middleware());
        app.use(domainMiddleware);
        app.use(
            bodyParser.json({
                verify: function(req, res, buf) {
                    // actions are internal, not to be included
                    if (
                        req.url !== config.endpoint.actionsPath &&
                        req.url !== config.endpoint.checkPath &&
                        req.url !== config.endpoint.versionPath &&
                        req.url !== config.endpoint.logPath &&
                        req.url !== config.endpoint.metricsPath
                    ) {
                        metrics.IncMetrics(
                            req.service,
                            req.subservice,
                            metrics.incomingTransactionsRequestSize,
                            buf.length
                        );
                    }
                }
            })
        );
        app.use(logRequestMiddleware.middleware());
        app.use(errorMiddleware.middleware());

        actionsRoutes.AddTo(app);
        rulesRoutes.AddTo(app);
        noticesRoutes.AddTo(app);
        visualRulesRoutes.AddTo(app);
        checkRoutes.AddTo(app);
        versionRoutes.AddTo(app);
        metricsRoutes.AddTo(app);

        async.series(
            [
                function(callback) {
                    async.waterfall(
                        [
                            db.getDb,
                            function(db0, cbwf) {
                                appContext.SetDB(db0);
                                cbwf(null);
                            }
                        ],
                        callback
                    );
                },
                db.ping,
                db.setUp,
                function(callback) {
                    async.waterfall(
                        [
                            db.getOrionDb,
                            function(dbO, cbwf) {
                                appContext.SetOrionDB(dbO);
                                cbwf(null);
                            }
                        ],
                        callback
                    );
                },
                db.orionPing,
                function(callback) {
                    var domain = require('domain').create();
                    domain.context = {};
                    domain.context.op = 'initialRefresh';
                    domain.context.comp = constants.COMPONENT_NAME;
                    domain.context.trans = 'n/a';
                    domain.context.corr = domain.context.trans;
                    domain.context.srv = 'n/a';
                    domain.context.subsrv = 'n/a';
                    domain.run(function() {
                        rules.Refresh(callback);
                    });
                },
                function(callback) {
                    server = app.listen(config.endpoint.port, function() {
                        logger.info(context, 'listening on port %d', server.address().port);
                        return callback(null, server);
                    });
                }
            ],
            function(err) {
                myutils.logErrorIf(err, context);
                require('./refreshCore'); // Start periodical update of rules at core
                return callbackStart(err);
            }
        );
    });
}

function stop(callback) {
    var context = { op: 'stop', comp: constants.COMPONENT_NAME };
    logger.info(context, 'stopping perseo');
    async.series([server.close.bind(server), db.close, db.orionClose], function(err) {
        myutils.logErrorIf(err);
        return callback(err);
    });
}

/**
 * start starts perseo server.
 *
 *  @param {function}       callback function(error)
 */
module.exports.start = start;
/**
 * stop stops perseo server.
 *
 *  @param {function}       callback function(error)
 */
module.exports.stop = stop;
<|endoftext|>


<commit_before>import React, {
  Component,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Modal,
  Picker,
  Dimensions,
  PropTypes,
} from 'react-native';
import countries from 'world-countries';

const PickerItem = Picker.Item;

const SCREEN_WIDTH = Dimensions.get('window').width;

const styles = StyleSheet.create({
  basicContainer: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },

  modalContainer: {
    width: SCREEN_WIDTH,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 0,
    backgroundColor: '#F5FCFF',
  },

  buttonView: {
    width: SCREEN_WIDTH,
    padding: 8,
    borderTopWidth: 0.5,
    borderTopColor: 'lightgrey',
    justifyContent: 'space-between',
    flexDirection: 'row',
  },

  bottomPicker: {
    width: SCREEN_WIDTH,
  },
});

class CustomPicker extends Component {

  constructor(props) {
    super(props);

    const prefix = this.getCountries();
    const selected = this.findCountriesCca2(this.props.selectedValue);

    this.state = {
      buttonColor: this.props.buttonColor || '#007AFF',
      modalVisible: false,
      selectedOption: selected,
      options: prefix,
    };

    this.onPressCancel = this.onPressCancel.bind(this);
    this.onPressSubmit = this.onPressSubmit.bind(this);
    this.onValueChange = this.onValueChange.bind(this);
  }

  componentDidMount() {
    this.onCreate();
  }

  onPressCancel() {
    this.setState({
      modalVisible: false,
    });
  }

  onPressSubmit() {
    this.onCreate();

    this.setState({
      modalVisible: false,
    });
  }

  onValueChange(option) {
    this.setState({
      selectedOption: option,
    });
  }

  onCreate() {
    if (this.props.onSubmit) {
      this.props.onSubmit(this.state.selectedOption);
    }
  }

  getCountries() {
    const array = [];
    for (let i = 0; i < countries.length; i++) {
      if (countries[i].callingCode.length > 1) {
        for (let j = 0; j < countries[i].callingCode.length; j++) {
          array.push({
            cca2: countries[i].cca2 + '( ' + countries[i].callingCode[j] + ' )',
            callingCode: countries[i].callingCode[j],
          });
        }
      }
      else {
        array.push({
          cca2: countries[i].cca2,
          callingCode: countries[i].callingCode[0],
        });
      }
    }
    return array;
  }

  findCountriesCca2(cca2) {
    const prefix = this.getCountries();

    for (let i = 0; i < prefix.length; i++) {
      if (prefix[i].cca2 === cca2) {
        return prefix[i].callingCode;
      }
    }
    return prefix[0].callingCode;
  }

  show() {
    this.setState({
      modalVisible: true,
    });
  }

  renderItem(option) {
    let value = option.callingCode;
    let label = option.cca2;
    return (
      <PickerItem
        key={label}
        value={value}
        label={label}
      />
    );
  }

  render() {
    const { buttonColor } = this.state;
    const itemStyle = this.props.itemStyle || {};

    return (
      <Modal
        animated
        transparent
        visible={this.state.modalVisible}
        onRequestClose={() => {this.onPressCancel()}}
        translucentStatusBar={true}
      >
        <View style={styles.basicContainer}>
          <View style={styles.modalContainer}>
            <View style={styles.buttonView}>
              <TouchableOpacity onPress={this.onPressCancel}>
                <Text style={{ color: buttonColor }}>
                  Cancel
                </Text>
              </TouchableOpacity>

              <TouchableOpacity onPress={this.onPressSubmit}>
                <Text style={{ color: buttonColor }}>
                  Done
                </Text>
              </TouchableOpacity>
            </View>

            <View style={styles.mainBox}>
              <Picker
                ref={'picker'}
                style={styles.bottomPicker}
                selectedValue={this.state.selectedOption}
                onValueChange={(option) => this.onValueChange(option)}
                itemStyle={itemStyle}
              >
                {this.state.options.map((option) => { return this.renderItem(option); })}
              </Picker>
            </View>

          </View>
        </View>
      </Modal>
    );
  }
}

CustomPicker.propTypes = {
  buttonColor: PropTypes.string,
  itemStyle: PropTypes.object,
  onSubmit: PropTypes.func.isRequired,
  selectedValue: PropTypes.string,
};

export default CustomPicker;
<commit_msg>FIX ESlint error<commit_after>import React, {
  Component,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Modal,
  Picker,
  Dimensions,
  PropTypes,
} from 'react-native';
import countries from 'world-countries';

const PickerItem = Picker.Item;

const SCREEN_WIDTH = Dimensions.get('window').width;

const styles = StyleSheet.create({
  basicContainer: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },

  modalContainer: {
    width: SCREEN_WIDTH,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 0,
    backgroundColor: '#F5FCFF',
  },

  buttonView: {
    width: SCREEN_WIDTH,
    padding: 8,
    borderTopWidth: 0.5,
    borderTopColor: 'lightgrey',
    justifyContent: 'space-between',
    flexDirection: 'row',
  },

  bottomPicker: {
    width: SCREEN_WIDTH,
  },
});

class CustomPicker extends Component {

  constructor(props) {
    super(props);

    const prefix = this.getCountries();
    const selected = this.findCountriesCca2(this.props.selectedValue);

    this.state = {
      buttonColor: this.props.buttonColor || '#007AFF',
      modalVisible: false,
      selectedOption: selected,
      options: prefix,
    };

    this.onPressCancel = this.onPressCancel.bind(this);
    this.onPressSubmit = this.onPressSubmit.bind(this);
    this.onValueChange = this.onValueChange.bind(this);
  }

  componentDidMount() {
    this.onCreate();
  }

  onPressCancel() {
    this.setState({
      modalVisible: false,
    });
  }

  onPressSubmit() {
    this.onCreate();

    this.setState({
      modalVisible: false,
    });
  }

  onValueChange(option) {
    this.setState({
      selectedOption: option,
    });
  }

  onCreate() {
    if (this.props.onSubmit) {
      this.props.onSubmit(this.state.selectedOption);
    }
  }

  getCountries() {
    const array = [];
    for (let i = 0; i < countries.length; i++) {
      if (countries[i].callingCode.length > 1) {
        for (let j = 0; j < countries[i].callingCode.length; j++) {
          array.push({
            cca2: countries[i].cca2 + '( ' + countries[i].callingCode[j] + ' )',
            callingCode: countries[i].callingCode[j],
          });
        }
      }
      else {
        array.push({
          cca2: countries[i].cca2,
          callingCode: countries[i].callingCode[0],
        });
      }
    }
    return array;
  }

  findCountriesCca2(cca2) {
    const prefix = this.getCountries();

    for (let i = 0; i < prefix.length; i++) {
      if (prefix[i].cca2 === cca2) {
        return prefix[i].callingCode;
      }
    }
    return prefix[0].callingCode;
  }

  show() {
    this.setState({
      modalVisible: true,
    });
  }

  renderItem(option) {
    let value = option.callingCode;
    let label = option.cca2;
    return (
      <PickerItem
        key={label}
        value={value}
        label={label}
      />
    );
  }

  render() {
    const { buttonColor } = this.state;
    const itemStyle = this.props.itemStyle || {};

    return (
      <Modal
        animated
        transparent
        visible={this.state.modalVisible}
        onRequestClose={() => { this.onPressCancel(); }}
        translucentStatusBar
      >
        <View style={styles.basicContainer}>
          <View style={styles.modalContainer}>
            <View style={styles.buttonView}>
              <TouchableOpacity onPress={this.onPressCancel}>
                <Text style={{ color: buttonColor }}>
                  Cancel
                </Text>
              </TouchableOpacity>

              <TouchableOpacity onPress={this.onPressSubmit}>
                <Text style={{ color: buttonColor }}>
                  Done
                </Text>
              </TouchableOpacity>
            </View>

            <View style={styles.mainBox}>
              <Picker
                ref={'picker'}
                style={styles.bottomPicker}
                selectedValue={this.state.selectedOption}
                onValueChange={(option) => this.onValueChange(option)}
                itemStyle={itemStyle}
              >
                {this.state.options.map((option) => { return this.renderItem(option); })}
              </Picker>
            </View>

          </View>
        </View>
      </Modal>
    );
  }
}

CustomPicker.propTypes = {
  buttonColor: PropTypes.string,
  itemStyle: PropTypes.object,
  onSubmit: PropTypes.func.isRequired,
  selectedValue: PropTypes.string,
};

export default CustomPicker;
<|endoftext|>


<commit_before>const CollisionEngine = require('./helpers/collisionEngine')
const Bomb = require('./bomb')

class Player {
  constructor(x, y, game) {
    this.x = x
    this.y = y
    this.height = 35
    this.width = 35
    this.speed = 3
    this.game = game
    this.collisions = new CollisionEngine()
    // this.bindControls()
  }

  get centerX() {
    return this.x + (this.width / 2)
  }

  get centerY() {
    return this.y + (this.height / 2)
  }

  bindControls() {
    document.addEventListener('keydown', e => {
      this.game.keys[e.keyCode] = true
    })

    document.addEventListener('keyup', e => {
      this.game.keys[e.keyCode] = false
    })
  }

  draw() {
    this.game.context.fillRect(this.x, this.y, this.width, this.height)
  }

  move() {
    this.game.context.fillRect(this.x, this.y, this.width, this.height)
  }

  clear() {
    this.game.context.clearRect(this.x, this.y, this.width, this.height)
  }

  plantBomb() {
    const bombY = this.centerY + (this.height / 2)
    const bomb = new Bomb(this.centerX, bombY, this.game)
    this.game.bombs.push(bomb)
    bomb.draw()
  }

  moveRight() {
    if (this.x < this.game.canvas.width - this.width) {
      const collidingBlocks = this.game.blocks.filter(this.collisions.rightCollide.bind(this))
      const collidingBombs = this.game.bombs.filter(this.collisions.bombRight.bind(this))
      const collidingBreakables = this.game.breakableBlocks.filter(this.collisions.rightCollide.bind(this))
      const possibleCollisions = collidingBlocks.length + collidingBombs.length + collidingBreakables.length
      if (possibleCollisions === 0) {
        this.clear()
        this.x += this.speed
        this.drawRight()
      }
    }
    return this
  }

  moveLeft() {
    if (this.x > 0) {
      const collidingBlocks = this.game.blocks.filter(this.collisions.leftCollide.bind(this))
      const collidingBombs = this.game.bombs.filter(this.collisions.bombLeft.bind(this))
      const collidingBreakables = this.game.breakableBlocks.filter(this.collisions.leftCollide.bind(this))
      const possibleCollisions = collidingBlocks.length + collidingBombs.length + collidingBreakables.length
      if (possibleCollisions === 0) {
        this.clear()
        this.x -= this.speed
        this.drawLeft()
      }
    }
    return this
  }

  moveUp() {
    if (this.y > 0) {
      const collidingBlocks = this.game.blocks.filter(this.collisions.upCollide.bind(this))
      const collidingBombs = this.game.bombs.filter(this.collisions.bombAbove.bind(this))
      const collidingBreakables = this.game.breakableBlocks.filter(this.collisions.upCollide.bind(this))
      const possibleCollisions = collidingBlocks.length + collidingBombs.length + collidingBreakables.length
      if (possibleCollisions === 0) {
        this.clear()
        this.y -= this.speed
        this.drawUp()
      }
    }
    return this
  }

  moveDown() {
    if (this.y < this.game.canvas.height - this.height) {
      const collidingBlocks = this.game.blocks.filter(this.collisions.downCollide.bind(this))
      const collidingBombs = this.game.bombs.filter(this.collisions.bombBelow.bind(this))
      const collidingBreakables = this.game.breakableBlocks.filter(this.collisions.downCollide.bind(this))
      const possibleCollisions = collidingBlocks.length + collidingBombs.length + collidingBreakables.length
      if (possibleCollisions === 0) {
        this.clear()
        this.y += this.speed
        this.drawDown()
      }
    }
    return this
  }
}

module.exports = Player
<commit_msg>close #67 add verification for clean bomb deployment on player.<commit_after>const CollisionEngine = require('./helpers/collisionEngine')
const Bomb = require('./bomb')

class Player {
  constructor(x, y, game) {
    this.x = x
    this.y = y
    this.height = 35
    this.width = 35
    this.speed = 3
    this.game = game
    this.collisions = new CollisionEngine()
  }

  get centerX() {
    return this.x + (this.width / 2)
  }

  get centerY() {
    return this.y + (this.height / 2)
  }

  bindControls() {
    document.addEventListener('keydown', e => {
      this.game.keys[e.keyCode] = true
    })

    document.addEventListener('keyup', e => {
      this.game.keys[e.keyCode] = false
    })
  }

  draw() {
    this.game.context.fillRect(this.x, this.y, this.width, this.height)
  }

  move() {
    this.game.context.fillRect(this.x, this.y, this.width, this.height)
  }

  clear() {
    this.game.context.clearRect(this.x, this.y, this.width, this.height)
  }

  plantBomb() {
    const bombY = this.centerY + (this.height / 2)
    const bomb = new Bomb(this.centerX, bombY, this.game)
    this.game.bombs.push(bomb)
    this.verifyCleanBombDeployment(bomb)
  }

  verifyCleanBombDeployment(bomb) {
    this.speed = bomb.height
    const blocksBelow = this.game.blocks.filter(this.collisions.downCollide.bind(this))
    const breakablesBelow = this.game.breakableBlocks.filter(this.collisions.downCollide.bind(this))
    this.speed = 3
    const possibleCollisions = blocksBelow.length + breakablesBelow.length
    if (possibleCollisions === 0) {
      bomb.draw()
    }
    else {
      this.adjustForBombDeployment(bomb)
    }
  }

  adjustForBombDeployment(bomb) {
    this.game.context.clearRect(this.x, this.y, this.width, this.height)
    this.y -= bomb.height
    bomb.y = this.centerY + (this.height / 2)
    bomb.draw()
  }

  moveRight() {
    if (this.x < this.game.canvas.width - this.width) {
      const collidingBlocks = this.game.blocks.filter(this.collisions.rightCollide.bind(this))
      const collidingBombs = this.game.bombs.filter(this.collisions.bombRight.bind(this))
      const collidingBreakables = this.game.breakableBlocks.filter(this.collisions.rightCollide.bind(this))
      const possibleCollisions = collidingBlocks.length + collidingBombs.length + collidingBreakables.length
      if (possibleCollisions === 0) {
        this.clear()
        this.x += this.speed
        this.drawRight()
      }
    }
    return this
  }

  moveLeft() {
    if (this.x > 0) {
      const collidingBlocks = this.game.blocks.filter(this.collisions.leftCollide.bind(this))
      const collidingBombs = this.game.bombs.filter(this.collisions.bombLeft.bind(this))
      const collidingBreakables = this.game.breakableBlocks.filter(this.collisions.leftCollide.bind(this))
      const possibleCollisions = collidingBlocks.length + collidingBombs.length + collidingBreakables.length
      if (possibleCollisions === 0) {
        this.clear()
        this.x -= this.speed
        this.drawLeft()
      }
    }
    return this
  }

  moveUp() {
    if (this.y > 0) {
      const collidingBlocks = this.game.blocks.filter(this.collisions.upCollide.bind(this))
      const collidingBombs = this.game.bombs.filter(this.collisions.bombAbove.bind(this))
      const collidingBreakables = this.game.breakableBlocks.filter(this.collisions.upCollide.bind(this))
      const possibleCollisions = collidingBlocks.length + collidingBombs.length + collidingBreakables.length
      if (possibleCollisions === 0) {
        this.clear()
        this.y -= this.speed
        this.drawUp()
      }
    }
    return this
  }

  moveDown() {
    if (this.y < this.game.canvas.height - this.height) {
      const collidingBlocks = this.game.blocks.filter(this.collisions.downCollide.bind(this))
      const collidingBombs = this.game.bombs.filter(this.collisions.bombBelow.bind(this))
      const collidingBreakables = this.game.breakableBlocks.filter(this.collisions.downCollide.bind(this))
      const possibleCollisions = collidingBlocks.length + collidingBombs.length + collidingBreakables.length
      if (possibleCollisions === 0) {
        this.clear()
        this.y += this.speed
        this.drawDown()
      }
    }
    return this
  }
}

module.exports = Player
<|endoftext|>


<commit_before>'use strict';
(function() {
    angular
        .module('owh')
        .component('owhSearch', {
            templateUrl: 'app/components/owh-search/owhSearch.html',
            controller: OWHSearchController,
            controllerAs: 'ots',
            bindings: {
                filters : '=',
                showFilters : '=',
                searchResults : '&',
                onViewFilter: '&',
                tableView: '@'
            }
        });

    OWHSearchController.$inject = ['utilService', 'searchFactory', '$window', '$location', '$scope'];

    function OWHSearchController(utilService, searchFactory, $window, $location, $scope) {
        var ots = this;
        ots.groupByFiltersUpdated = groupByFiltersUpdated;
        ots.phaseTwoImpl = phaseTwoImpl;
        //Show alert to press Ctrl+D other than Firefox browser
        $scope.bookmarkAlert = function() {
            alert('Press ' + (navigator.userAgent.indexOf('Mac') != -1 ? 'Cmd' : 'Ctrl') + '+D to bookmark this page.');
        };
        var bookmarkButton =angular.element("#bookmark-button");
        //capture currne url and assign it to bookmark button href
        $(bookmarkButton).attr({
            //If we assign $location.absURL() then 'New bookmark window' not displayed, that's why
            //split URL and added as string
            href: "http://"+$location.host()+""+$location.url()
        });
        //To verify current browser is Firefox browser or not.
        $scope.isFirefoxBrowser = function () {
            return (($window.sidebar && navigator.userAgent.indexOf('Firefox') != -1));
        }
        angular.forEach(ots.showFilters, function(filter) {
            if(filter.key === ots.tableView) {
                ots.selectedShowFilter = filter;
            }
        });

        function groupByFiltersUpdated(added) {
            var selectedFilterKeys = utilService.getValuesByKey(ots.filters.selectedPrimaryFilter.value, 'key');
            angular.forEach(ots.filters.selectedPrimaryFilter.allFilters, function(eachGroupByFilter) {
                if(!eachGroupByFilter.donotshowOnSearch && selectedFilterKeys.indexOf(eachGroupByFilter.key) < 0) {
                    eachGroupByFilter.groupBy = false;
                }
            });
            if(added && utilService.isValueNotEmpty(ots.filters.selectedPrimaryFilter.value)) {
                ots.filters.selectedPrimaryFilter.value[ots.filters.selectedPrimaryFilter.value.length - 1].groupBy =
                    ots.filters.selectedPrimaryFilter.value[ots.filters.selectedPrimaryFilter.value.length - 1].defaultGroup;
            }
            if(ots.filters.selectedPrimaryFilter.initiated) {
                ots.searchResults({});
            }
        }

        /*Show phase two implementation box*/
        function phaseTwoImpl() {
            if(ots.selectedShowFilter.key !== 'number_of_deaths') {
                ots.selectedShowFilter = ots.showFilters[0];
                searchFactory.showPhaseTwoModal('label.show.impl.next');
            }
        }

    }

}());
<commit_msg>hardcoded url to test in owhqa<commit_after>'use strict';
(function() {
    angular
        .module('owh')
        .component('owhSearch', {
            templateUrl: 'app/components/owh-search/owhSearch.html',
            controller: OWHSearchController,
            controllerAs: 'ots',
            bindings: {
                filters : '=',
                showFilters : '=',
                searchResults : '&',
                onViewFilter: '&',
                tableView: '@'
            }
        });

    OWHSearchController.$inject = ['utilService', 'searchFactory', '$window', '$location', '$scope'];

    function OWHSearchController(utilService, searchFactory, $window, $location, $scope) {
        var ots = this;
        ots.groupByFiltersUpdated = groupByFiltersUpdated;
        ots.phaseTwoImpl = phaseTwoImpl;
        //Show alert to press Ctrl+D other than Firefox browser
        $scope.bookmarkAlert = function() {
            alert('Press ' + (navigator.userAgent.indexOf('Mac') != -1 ? 'Cmd' : 'Ctrl') + '+D to bookmark this page.');
        };
        var bookmarkButton =angular.element("#bookmark-button");
        //capture currne url and assign it to bookmark button href
        $(bookmarkButton).attr({
            //If we assign $location.absURL() then 'New bookmark window' not displayed, that's why
            //split URL and added as string
            href: "http://owhqa.semanticbits.com"+$location.url()
        });
        //To verify current browser is Firefox browser or not.
        $scope.isFirefoxBrowser = function () {
            return (($window.sidebar && navigator.userAgent.indexOf('Firefox') != -1));
        }
        angular.forEach(ots.showFilters, function(filter) {
            if(filter.key === ots.tableView) {
                ots.selectedShowFilter = filter;
            }
        });

        function groupByFiltersUpdated(added) {
            var selectedFilterKeys = utilService.getValuesByKey(ots.filters.selectedPrimaryFilter.value, 'key');
            angular.forEach(ots.filters.selectedPrimaryFilter.allFilters, function(eachGroupByFilter) {
                if(!eachGroupByFilter.donotshowOnSearch && selectedFilterKeys.indexOf(eachGroupByFilter.key) < 0) {
                    eachGroupByFilter.groupBy = false;
                }
            });
            if(added && utilService.isValueNotEmpty(ots.filters.selectedPrimaryFilter.value)) {
                ots.filters.selectedPrimaryFilter.value[ots.filters.selectedPrimaryFilter.value.length - 1].groupBy =
                    ots.filters.selectedPrimaryFilter.value[ots.filters.selectedPrimaryFilter.value.length - 1].defaultGroup;
            }
            if(ots.filters.selectedPrimaryFilter.initiated) {
                ots.searchResults({});
            }
        }

        /*Show phase two implementation box*/
        function phaseTwoImpl() {
            if(ots.selectedShowFilter.key !== 'number_of_deaths') {
                ots.selectedShowFilter = ots.showFilters[0];
                searchFactory.showPhaseTwoModal('label.show.impl.next');
            }
        }

    }

}());
<|endoftext|>


<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

var cordova                 = require('cordova'),
    cordovaUtils            = require('../node_modules/cordova/src/util'),
    pluginUtils             = require('./pluginUtils');

module.exports = function plugin(command, targets, callback) {

    var projectRoot = cordovaUtils.isCordova(process.cwd()),
        err;

    if (!projectRoot) {
        err = new Error('Current working directory is not a WebWorks-based project.');
        if (callback) return callback(err);
        else throw err;
    }

    //We were called directly from the CLI
    if (Array.isArray(command)) {
        if (typeof command[command.length -1] === "function") {
            callback = command.pop();
        }
        targets = command.slice(4);
        command = command[3];
    }

    if (command == "add") {
        targets = pluginUtils.updateTargets(targets);
    }

    cordova.plugin(command, targets, callback);

};
<commit_msg>Fixed error when calling plugin add<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

var cordova                 = require('cordova'),
    cordovaUtils            = require('../node_modules/cordova/src/util'),
    pluginUtils             = require('./pluginUtils');

module.exports = function plugin(command, targets) {

    var projectRoot = cordovaUtils.isCordova(process.cwd());

    if (!projectRoot) {
        throw new Error('Current working directory is not a WebWorks-based project.');
    }

    //We were called directly from the CLI
    if (Array.isArray(command)) {
        targets = command.slice(4);
        command = command[3];
    }

    if (command == "add") {
        targets = pluginUtils.updateTargets(targets);
    }

    cordova.plugin(command, targets);

};
<|endoftext|>


<commit_before>/*jshint browser:true, nonew:false*/
/*global WebInspector:true, InspectorFrontendHost:true, InspectorFrontendHostAPI:true*/
WebInspector.ConsoleExtensions = function() {
  this._extendConsoleDispatcher();
  this._overrideConsoleViewFilterAdd();
  this._overrideHandleContextMenuEvent();
};

WebInspector.ConsoleExtensions.prototype = {
  _extendConsoleDispatcher: function() {
    WebInspector.ConsoleDispatcher.prototype.showConsole = function() {
      InspectorFrontendHost.events.dispatchEventToListeners(
        InspectorFrontendHostAPI.Events.ShowConsole, WebInspector.inspectorView);
    };
  },
  _overrideConsoleViewFilterAdd: function(){
    WebInspector.ConsoleViewFilter.prototype.addFilters = function(filterBar)
    {
        this._textFilterUI = new WebInspector.TextFilterUI(true);
        this._textFilterUI.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._textFilterChanged, this);
        filterBar.addFilter(this._textFilterUI);

        var levels = [
            {name: "error", label: WebInspector.UIString("Errors")},
            {name: "warning", label: WebInspector.UIString("Warnings")},
            {name: "info", label: WebInspector.UIString("Info")},
            {name: "log", label: WebInspector.UIString("Logs")},
            {name: "debug", label: WebInspector.UIString("Debug")}
        ];
        this._levelFilterUI = new WebInspector.NamedBitSetFilterUI(levels, WebInspector.settings.messageLevelFilters);
        this._levelFilterUI.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._filterChanged, this);
        filterBar.addFilter(this._levelFilterUI);
        //this._hideNetworkMessagesCheckbox = new WebInspector.CheckboxFilterUI("hide-network-messages", WebInspector.UIString("Hide network messages"), true, WebInspector.settings.hideNetworkMessages);
        //this._hideNetworkMessagesCheckbox.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._filterChanged.bind(this), this);
        //filterBar.addFilter(this._hideNetworkMessagesCheckbox);
    }
  },
  _overrideHandleContextMenuEvent: function(){
    WebInspector.ConsoleView.prototype._handleContextMenuEvent = function(event)
    {
        if (event.target.enclosingNodeOrSelfWithNodeName("a"))
            return;

        var contextMenu = new WebInspector.ContextMenu(event);

        /*function monitoringXHRItemAction()
        {
            WebInspector.settings.monitoringXHREnabled.set(!WebInspector.settings.monitoringXHREnabled.get());
        }
        contextMenu.appendCheckboxItem(WebInspector.UIString("Log XMLHttpRequests"), monitoringXHRItemAction, WebInspector.settings.monitoringXHREnabled.get());*/

        var sourceElement = event.target.enclosingNodeOrSelfWithClass("console-message-wrapper");
        var consoleMessage = sourceElement ? sourceElement.message.consoleMessage() : null;

        var filterSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString("Filter"));

        if (consoleMessage && consoleMessage.url) {
            var menuTitle = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Hide messages from %s" : "Hide Messages from %s", new WebInspector.ParsedURL(consoleMessage.url).displayName);
            filterSubMenu.appendItem(menuTitle, this._filter.addMessageURLFilter.bind(this._filter, consoleMessage.url));
        }

        filterSubMenu.appendSeparator();
        var unhideAll = filterSubMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Unhide all" : "Unhide All"), this._filter.removeMessageURLFilter.bind(this._filter));
        filterSubMenu.appendSeparator();

        var hasFilters = false;

        for (var url in this._filter.messageURLFilters) {
            filterSubMenu.appendCheckboxItem(String.sprintf("%s (%d)", new WebInspector.ParsedURL(url).displayName, this._urlToMessageCount[url]), this._filter.removeMessageURLFilter.bind(this._filter, url), true);
            hasFilters = true;
        }

        filterSubMenu.setEnabled(hasFilters || (consoleMessage && consoleMessage.url));
        unhideAll.setEnabled(hasFilters);

        contextMenu.appendSeparator();
        contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear console" : "Clear Console"), this._requestClearMessages.bind(this));

        var request = consoleMessage ? consoleMessage.request : null;
        if (request && request.resourceType() === WebInspector.resourceTypes.XHR) {
            contextMenu.appendSeparator();
            contextMenu.appendItem(WebInspector.UIString("Replay XHR"), request.replayXHR.bind(request));
        }

        contextMenu.show();
    }
  }
};

new WebInspector.ConsoleExtensions();
<commit_msg>Front-end: added event dispatcher for console view<commit_after>/*jshint browser:true, nonew:false, proto:true*/
/*global WebInspector:true, InspectorFrontendHost:true, InspectorFrontendHostAPI:true*/
WebInspector.ConsoleViewEventDispatcher = {
  Events: {
    MessageFormatted: 'MessageFormatted'
  },
  __proto__: WebInspector.Object.prototype
};

WebInspector.ConsoleExtensions = function() {
  this._extendConsoleDispatcher();
  this._overrideConsoleViewFilterAdd();
  this._overrideHandleContextMenuEvent();
};

WebInspector.ConsoleExtensions.prototype = {
  _extendConsoleDispatcher: function() {
    WebInspector.ConsoleDispatcher.prototype.showConsole = function() {
      InspectorFrontendHost.events.dispatchEventToListeners(
        InspectorFrontendHostAPI.Events.ShowConsole, WebInspector.inspectorView);
    };
  },
  _overrideConsoleViewFilterAdd: function(){
    WebInspector.ConsoleViewFilter.prototype.addFilters = function(filterBar)
    {
        this._textFilterUI = new WebInspector.TextFilterUI(true);
        this._textFilterUI.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._textFilterChanged, this);
        filterBar.addFilter(this._textFilterUI);

        var levels = [
            {name: "error", label: WebInspector.UIString("Errors")},
            {name: "warning", label: WebInspector.UIString("Warnings")},
            {name: "info", label: WebInspector.UIString("Info")},
            {name: "log", label: WebInspector.UIString("Logs")},
            {name: "debug", label: WebInspector.UIString("Debug")}
        ];
        this._levelFilterUI = new WebInspector.NamedBitSetFilterUI(levels, WebInspector.settings.messageLevelFilters);
        this._levelFilterUI.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._filterChanged, this);
        filterBar.addFilter(this._levelFilterUI);
        //this._hideNetworkMessagesCheckbox = new WebInspector.CheckboxFilterUI("hide-network-messages", WebInspector.UIString("Hide network messages"), true, WebInspector.settings.hideNetworkMessages);
        //this._hideNetworkMessagesCheckbox.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._filterChanged.bind(this), this);
        //filterBar.addFilter(this._hideNetworkMessagesCheckbox);
    }
  },
  _overrideHandleContextMenuEvent: function(){
    WebInspector.ConsoleView.prototype._handleContextMenuEvent = function(event)
    {
        if (event.target.enclosingNodeOrSelfWithNodeName("a"))
            return;

        var contextMenu = new WebInspector.ContextMenu(event);

        /*function monitoringXHRItemAction()
        {
            WebInspector.settings.monitoringXHREnabled.set(!WebInspector.settings.monitoringXHREnabled.get());
        }
        contextMenu.appendCheckboxItem(WebInspector.UIString("Log XMLHttpRequests"), monitoringXHRItemAction, WebInspector.settings.monitoringXHREnabled.get());*/

        var sourceElement = event.target.enclosingNodeOrSelfWithClass("console-message-wrapper");
        var consoleMessage = sourceElement ? sourceElement.message.consoleMessage() : null;

        var filterSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString("Filter"));

        if (consoleMessage && consoleMessage.url) {
            var menuTitle = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Hide messages from %s" : "Hide Messages from %s", new WebInspector.ParsedURL(consoleMessage.url).displayName);
            filterSubMenu.appendItem(menuTitle, this._filter.addMessageURLFilter.bind(this._filter, consoleMessage.url));
        }

        filterSubMenu.appendSeparator();
        var unhideAll = filterSubMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Unhide all" : "Unhide All"), this._filter.removeMessageURLFilter.bind(this._filter));
        filterSubMenu.appendSeparator();

        var hasFilters = false;

        for (var url in this._filter.messageURLFilters) {
            filterSubMenu.appendCheckboxItem(String.sprintf("%s (%d)", new WebInspector.ParsedURL(url).displayName, this._urlToMessageCount[url]), this._filter.removeMessageURLFilter.bind(this._filter, url), true);
            hasFilters = true;
        }

        filterSubMenu.setEnabled(hasFilters || (consoleMessage && consoleMessage.url));
        unhideAll.setEnabled(hasFilters);

        contextMenu.appendSeparator();
        contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear console" : "Clear Console"), this._requestClearMessages.bind(this));

        var request = consoleMessage ? consoleMessage.request : null;
        if (request && request.resourceType() === WebInspector.resourceTypes.XHR) {
            contextMenu.appendSeparator();
            contextMenu.appendItem(WebInspector.UIString("Replay XHR"), request.replayXHR.bind(request));
        }

        contextMenu.show();
    }
  }
};

new WebInspector.ConsoleExtensions();
<|endoftext|>


<commit_before>const fs = require('mz/fs');
const JSZip = require('jszip');
const path = require('path');
const semver = require('semver');
const { parseChangelogMarkdown } = require('./changelogMarkdownParser');

function readInfoFromComposerJson(composerJsonString) {
    const composerJson = JSON.parse(composerJsonString);

    return {
        version: composerJson.version,
        shopwareCompatibility: composerJson.require['shopware/core'],
        label: {
            en: composerJson.extra.label['en-GB'],
            de: composerJson.extra.label['de-DE'],
        },
    };
}

function readInfoFromPluginJson(pluginJsonString) {
    const pluginJson = JSON.parse(pluginJsonString);
    const compatibility = pluginJson.compatibility;

    return {
        version: pluginJson.currentVersion,
        shopwareCompatibility: `>= ${compatibility.minimumVersion} && <= ${compatibility.maximumVersion}`,
        label: pluginJson.label,
    };
}

module.exports = class Plugin {
    static async readFromZipFile(zipFilePath) {
        if (!await fs.exists(zipFilePath)) {
            throw new Error(`File ${zipFilePath} does not exist`);
        }

        const data = await fs.readFile(zipFilePath);
        const zip = await JSZip.loadAsync(data);

        const sw5RootDirectory = zip.folder(/^(Backend|Frontend|Core)\/\w+\//)[0];
        const sw6RootDirectory = zip.folder(/^\w+\//)[0];

        const plugin = new Plugin();
        let rootDirectory;
        if (sw5RootDirectory) {
            rootDirectory = sw5RootDirectory.name;
            plugin.technicalName = rootDirectory.split('/')[1];
            plugin.shopwareMajorVersion = 5;
            Object.assign(plugin, readInfoFromPluginJson(
                await zip.file(path.join(rootDirectory, 'plugin.json')).async('string'),
            ));
        } else if (sw6RootDirectory) {
            rootDirectory = sw6RootDirectory.name;
            plugin.technicalName = rootDirectory.split('/')[0];
            plugin.shopwareMajorVersion = 6;
            Object.assign(plugin, readInfoFromComposerJson(
                await zip.file(path.join(rootDirectory, 'composer.json')).async('string'),
            ));
        } else {
            throw new Error('Could not detect whether plugin targets Shopware 5 or Shopware 6.');
        }

        const parsedChangelog = parseChangelogMarkdown(
            await zip.file(path.join(rootDirectory, 'CHANGELOG.md')).async('string'),
        );
        plugin.releaseNotes = parsedChangelog[plugin.version];

        return plugin;
    }

    isCompatibleWithShopwareVersion(shopwareVersion) {
        return semver.satisfies(shopwareVersion, this.shopwareCompatibility);
    }
};
<commit_msg>Fix Shopware version compatibility for Shopware 5 plugins<commit_after>const fs = require('mz/fs');
const JSZip = require('jszip');
const path = require('path');
const semver = require('semver');
const { parseChangelogMarkdown } = require('./changelogMarkdownParser');

function readInfoFromComposerJson(composerJsonString) {
    const composerJson = JSON.parse(composerJsonString);

    return {
        version: composerJson.version,
        shopwareCompatibility: composerJson.require['shopware/core'],
        label: {
            en: composerJson.extra.label['en-GB'],
            de: composerJson.extra.label['de-DE'],
        },
    };
}

function readInfoFromPluginJson(pluginJsonString) {
    const pluginJson = JSON.parse(pluginJsonString);
    const minimumVersion = pluginJson.compatibility.minimumVersion || '0.0.0';
    const maximumVersion = pluginJson.compatibility.maximumVersion || '99.99.99';

    return {
        version: pluginJson.currentVersion,
        shopwareCompatibility: `${minimumVersion} - ${maximumVersion}`,
        label: pluginJson.label,
    };
}

module.exports = class Plugin {
    static async readFromZipFile(zipFilePath) {
        if (!await fs.exists(zipFilePath)) {
            throw new Error(`File ${zipFilePath} does not exist`);
        }

        const data = await fs.readFile(zipFilePath);
        const zip = await JSZip.loadAsync(data);

        const sw5RootDirectory = zip.folder(/^(Backend|Frontend|Core)\/\w+\//)[0];
        const sw6RootDirectory = zip.folder(/^\w+\//)[0];

        const plugin = new Plugin();
        let rootDirectory;
        if (sw5RootDirectory) {
            rootDirectory = sw5RootDirectory.name;
            plugin.technicalName = rootDirectory.split('/')[1];
            plugin.shopwareMajorVersion = 5;
            Object.assign(plugin, readInfoFromPluginJson(
                await zip.file(path.join(rootDirectory, 'plugin.json')).async('string'),
            ));
        } else if (sw6RootDirectory) {
            rootDirectory = sw6RootDirectory.name;
            plugin.technicalName = rootDirectory.split('/')[0];
            plugin.shopwareMajorVersion = 6;
            Object.assign(plugin, readInfoFromComposerJson(
                await zip.file(path.join(rootDirectory, 'composer.json')).async('string'),
            ));
        } else {
            throw new Error('Could not detect whether plugin targets Shopware 5 or Shopware 6.');
        }

        const parsedChangelog = parseChangelogMarkdown(
            await zip.file(path.join(rootDirectory, 'CHANGELOG.md')).async('string'),
        );
        plugin.releaseNotes = parsedChangelog[plugin.version];

        return plugin;
    }

    isCompatibleWithShopwareVersion(shopwareVersion) {
        return semver.satisfies(shopwareVersion, this.shopwareCompatibility);
    }
};
<|endoftext|>


<commit_before>'use strict'
const config = require('../config')
const dayjs = require('dayjs')
const dayjsPluginUtc = require('dayjs/plugin/utc')
const dayjsPluginTimezone = require('dayjs/plugin/timezone')
const dayjsPluginDayOfYear = require('dayjs/plugin/dayOfYear')
dayjs.extend(dayjsPluginUtc) // Used by timezone
dayjs.extend(dayjsPluginTimezone) // Used to convert from one timezone to another
dayjs.extend(dayjsPluginDayOfYear) // Used to compare dates
dayjs.tz.setDefault('UTC') // Needed when working with different timezones

const fetch = require('node-fetch')
function Prices () {
  return this
}

Prices.prototype.at = async function (opts = {}) {
  opts.date = opts.date ? dayjs.tz(new Date(opts.date)) : dayjs.tz((new Date()).toISOString())
  opts.url = config.priceUrlHourly
  opts.maxRange = { hour: 1 }
  const results = await this.getValues(opts)
  for (const result of results) {
  // for (let i = 0; i < results.length; i++) {
    // const date = results[i].date
    if (dayjs(result.date).tz('UTC').dayOfYear() === opts.date.dayOfYear() &&
          dayjs(result.date).tz('UTC').hour() === opts.date.hour()) {
      return result
    }
  }
  throw new Error('No results found for ' + opts.date.format())
  // })
}

Prices.prototype.hourly = async function (opts = {}) {
  opts.url = config.priceUrlHourly
  opts.maxRange = { day: 1 }
  return this.getValues(opts)
}

Prices.prototype.daily = async function (opts = {}) {
  opts.url = config.priceUrlDaily
  opts.maxRange = { month: 1 }
  return this.getValues(opts)
}

Prices.prototype.weekly = async function (opts = {}) {
  opts.url = config.priceUrlWeekly
  opts.maxRange = { week: 24 }
  return this.getValues(opts)
}

Prices.prototype.monthly = async function (opts = {}) {
  opts.url = config.priceUrlMonthly
  opts.maxRange = { month: 53 }
  return this.getValues(opts)
}

Prices.prototype.yearly = async function (opts = {}) {
  opts.url = config.priceUrlYearly
  return this.getValues(opts)
}

Prices.prototype.getValues = async function (opts = {}) {
  let fromTime = opts.from ? dayjs.tz(new Date(opts.from)) : null
  const toTime = opts.to ? dayjs.tz(new Date(opts.to)) : null
  opts.maxRangeKey = opts.maxRange ? Object.entries(opts.maxRange)[0][0] : ''// Eg. hour or month
  opts.maxRangeValue = opts.maxRange ? Object.entries(opts.maxRange)[0][1] : 0 // Amount of time to add
  if (fromTime && toTime && opts.maxRange) {
    const minFromTime = toTime.subtract(opts.maxRangeValue, opts.maxRangeKey)
    if (fromTime.isBefore(minFromTime)) {
      console.warn('Time span too long. Setting start time to ' + minFromTime.format())
      fromTime = minFromTime
    }
  }
  if (fromTime && !toTime && !opts.date && opts.maxRange) {
    opts.date = dayjs(fromTime).add(opts.maxRangeValue, opts.maxRangeKey)
  } else if ((fromTime || toTime) && !opts.date) {
    opts.date = toTime || fromTime
  }
  opts.area = opts.area || null
  opts.currency = opts.currency || 'EUR'
  opts.date = opts.date || dayjs.tz((new Date()).toISOString())
  const url = opts.url +
    '?currency=,' + opts.currency + ',' + opts.currency + ',' + opts.currency +
    '&endDate=' + dayjs.tz(opts.date, config.timezone).format('DD-MM-YYYY')
  const { data } = await fetch(url).then(res => res.json())
  if (data && data.Rows && data.Rows.length) {
    const values = []
    for (const row of data.Rows) {
    // for (let i = 0; i < data.Rows.length; i++) {
      // const row = data.Rows[i]
      if (row.IsExtraRow) {
        continue
      }
      // intentionally create new time object for each row (reference returned)
      const date = dayjs.tz(row.StartTime, 'YYYY-MM-DDTHH:mm:ss', config.timezone)
      if (!date.isValid()) {
        continue
      } else if ((fromTime && date.unix() < (fromTime.unix())) ||
                (toTime && date.unix() >= (toTime.unix()))) {
        // date out of given range
        continue
      }
      for (const column of row.Columns) {
        const value = parseFloat(column.Value.replace(/,/, '.').replace(/ /g, ''))
        if (isNaN(value)) {
          continue
        }
        const area = column.Name
        // console.log(JSON.stringify(column, null, 2))
        if (!opts.area || opts.area.indexOf(area) >= 0) {
          values.push({ area: area, date: date.toISOString(), value: value })
        }
      }
    }
    return values
  }
}

module.exports = Prices
<commit_msg>Cleaned commented-out sections<commit_after>'use strict'
const config = require('../config')
const dayjs = require('dayjs')
const dayjsPluginUtc = require('dayjs/plugin/utc')
const dayjsPluginTimezone = require('dayjs/plugin/timezone')
const dayjsPluginDayOfYear = require('dayjs/plugin/dayOfYear')
dayjs.extend(dayjsPluginUtc) // Used by timezone
dayjs.extend(dayjsPluginTimezone) // Used to convert from one timezone to another
dayjs.extend(dayjsPluginDayOfYear) // Used to compare dates
dayjs.tz.setDefault('UTC') // Needed when working with different timezones

const fetch = require('node-fetch')
function Prices () {
  return this
}

Prices.prototype.at = async function (opts = {}) {
  opts.date = opts.date ? dayjs.tz(new Date(opts.date)) : dayjs.tz((new Date()).toISOString())
  opts.url = config.priceUrlHourly
  opts.maxRange = { hour: 1 }
  const results = await this.getValues(opts)
  for (const result of results) {
    if (dayjs(result.date).tz('UTC').dayOfYear() === opts.date.dayOfYear() &&
          dayjs(result.date).tz('UTC').hour() === opts.date.hour()) {
      return result
    }
  }
  throw new Error('No results found for ' + opts.date.format())
}

Prices.prototype.hourly = async function (opts = {}) {
  opts.url = config.priceUrlHourly
  opts.maxRange = { day: 1 }
  return this.getValues(opts)
}

Prices.prototype.daily = async function (opts = {}) {
  opts.url = config.priceUrlDaily
  opts.maxRange = { month: 1 }
  return this.getValues(opts)
}

Prices.prototype.weekly = async function (opts = {}) {
  opts.url = config.priceUrlWeekly
  opts.maxRange = { week: 24 }
  return this.getValues(opts)
}

Prices.prototype.monthly = async function (opts = {}) {
  opts.url = config.priceUrlMonthly
  opts.maxRange = { month: 53 }
  return this.getValues(opts)
}

Prices.prototype.yearly = async function (opts = {}) {
  opts.url = config.priceUrlYearly
  return this.getValues(opts)
}

Prices.prototype.getValues = async function (opts = {}) {
  let fromTime = opts.from ? dayjs.tz(new Date(opts.from)) : null
  const toTime = opts.to ? dayjs.tz(new Date(opts.to)) : null
  opts.maxRangeKey = opts.maxRange ? Object.entries(opts.maxRange)[0][0] : ''// Eg. hour or month
  opts.maxRangeValue = opts.maxRange ? Object.entries(opts.maxRange)[0][1] : 0 // Amount of time to add
  if (fromTime && toTime && opts.maxRange) {
    const minFromTime = toTime.subtract(opts.maxRangeValue, opts.maxRangeKey)
    if (fromTime.isBefore(minFromTime)) {
      console.warn('Time span too long. Setting start time to ' + minFromTime.format())
      fromTime = minFromTime
    }
  }
  if (fromTime && !toTime && !opts.date && opts.maxRange) {
    opts.date = dayjs(fromTime).add(opts.maxRangeValue, opts.maxRangeKey)
  } else if ((fromTime || toTime) && !opts.date) {
    opts.date = toTime || fromTime
  }
  opts.area = opts.area || null
  opts.currency = opts.currency || 'EUR'
  opts.date = opts.date || dayjs.tz((new Date()).toISOString())
  const url = opts.url +
    '?currency=,' + opts.currency + ',' + opts.currency + ',' + opts.currency +
    '&endDate=' + dayjs.tz(opts.date, config.timezone).format('DD-MM-YYYY')
  const { data } = await fetch(url).then(res => res.json())
  if (data && data.Rows && data.Rows.length) {
    const values = []
    for (const row of data.Rows) {
      if (row.IsExtraRow) {
        continue
      }

      const date = dayjs.tz(row.StartTime, 'YYYY-MM-DDTHH:mm:ss', config.timezone)
      if (!date.isValid()) {
        continue
      } else if ((fromTime && date.unix() < (fromTime.unix())) ||
                (toTime && date.unix() >= (toTime.unix()))) {
        // date out of given range
        continue
      }
      for (const column of row.Columns) {
        const value = parseFloat(column.Value.replace(/,/, '.').replace(/ /g, ''))
        if (isNaN(value)) {
          continue
        }
        const area = column.Name
        if (!opts.area || opts.area.indexOf(area) >= 0) {
          values.push({ area: area, date: date.toISOString(), value: value })
        }
      }
    }
    return values
  }
}

module.exports = Prices
<|endoftext|>


<commit_before>const React = require('react');
const Styled = require('styled-components');
const flatten = require('lodash.flatten');

const Container = require('@ui/components/container');
const Row = require('@ui/components/row');
const Column = require('@ui/components/column');
const BaseElements = require('@ui/components/base-elements');
const NavLink = require('@ui/components/nav-link');
const PropTypes = require('@root/prop-types');
const fns = require('@ui/shared/functions');
const constants = require('@ui/shared/constants');

const {
  remcalc,
  unitcalc
} = fns;

const {
  colors
} = constants;

const {
  H2
} = BaseElements;

const {
  default: styled
} = Styled;

// Main Contonent Wrapper Styles
const StyledDiv = styled.div`
  border-bottom: solid ${remcalc(1)} ${colors.base.grey};
  padding: ${unitcalc(4.5)} 0 ${unitcalc(4.5)} 0;
`;

const BreadcrumbA = styled(NavLink)`
  text-decoration: none;
`;

const BreadcrumbSpan = styled.span`
  color: ${colors.base.secondaryDark};
`;

function getNameLink(name) {
  return flatten(name.map((part, i) => {
    if (!part.name) {
      return null;
    }

    const link = (
      <BreadcrumbA key={part.pathname} to={part.pathname}>
        {part.name}
      </BreadcrumbA>
    );

    const key = `${part.pathname}${i}`;
    const slash = (
      <BreadcrumbSpan key={key}> / </BreadcrumbSpan>
    );

    return (i === 0) ? link : [
      slash,
      link
    ];
  }));
}

const StyledH2 = styled(H2)`
  color: ${colors.base.primary};
  margin: 0;
`;

const Breadcrumb = ({
  children,
  links = [],
  name = []
}) => {
  return (
    <Container>
      <Row>
        <Column xs={12}>
          <StyledDiv>
            <StyledH2>
              {getNameLink(name)}
            </StyledH2>
          </StyledDiv>
        </Column>
      </Row>
    </Container>
  );
};

Breadcrumb.propTypes = {
  children: React.PropTypes.node,
  links: React.PropTypes.arrayOf(PropTypes.link),
  name: React.PropTypes.arrayOf(PropTypes.link)
};

module.exports = Breadcrumb;
<commit_msg>fixing broken color constant<commit_after>const React = require('react');
const Styled = require('styled-components');
const flatten = require('lodash.flatten');

const Container = require('@ui/components/container');
const Row = require('@ui/components/row');
const Column = require('@ui/components/column');
const BaseElements = require('@ui/components/base-elements');
const NavLink = require('@ui/components/nav-link');
const PropTypes = require('@root/prop-types');
const fns = require('@ui/shared/functions');
const constants = require('@ui/shared/constants');

const {
  remcalc,
  unitcalc
} = fns;

const {
  colors
} = constants;

const {
  H2
} = BaseElements;

const {
  default: styled
} = Styled;

// Main Contonent Wrapper Styles
const StyledDiv = styled.div`
  border-bottom: solid ${remcalc(1)} ${colors.base.grey};
  padding: ${unitcalc(4.5)} 0 ${unitcalc(4.5)} 0;
`;

const BreadcrumbA = styled(NavLink)`
  text-decoration: none;
`;

const BreadcrumbSpan = styled.span`
  color: ${colors.base.text};
`;

function getNameLink(name) {
  return flatten(name.map((part, i) => {
    if (!part.name) {
      return null;
    }

    const link = (
      <BreadcrumbA key={part.pathname} to={part.pathname}>
        {part.name}
      </BreadcrumbA>
    );

    const key = `${part.pathname}${i}`;
    const slash = (
      <BreadcrumbSpan key={key}> / </BreadcrumbSpan>
    );

    return (i === 0) ? link : [
      slash,
      link
    ];
  }));
}

const StyledH2 = styled(H2)`
  color: ${colors.base.primary};
  margin: 0;
`;

const Breadcrumb = ({
  children,
  links = [],
  name = []
}) => {
  return (
    <Container>
      <Row>
        <Column xs={12}>
          <StyledDiv>
            <StyledH2>
              {getNameLink(name)}
            </StyledH2>
          </StyledDiv>
        </Column>
      </Row>
    </Container>
  );
};

Breadcrumb.propTypes = {
  children: React.PropTypes.node,
  links: React.PropTypes.arrayOf(PropTypes.link),
  name: React.PropTypes.arrayOf(PropTypes.link)
};

module.exports = Breadcrumb;
<|endoftext|>


<commit_before>// pub-sub functions for team interaction

var indexer = require('../lib/indexer');
var utils = require('../lib/utils');
var faye = require('faye');
var bayeux = new faye.NodeAdapter({mount: '/montr', timeout: 45});
var fayeClient = new faye.Client(GLOBAL.config.FAYEHOST);
var annotations = require('./annotations.js'), contentExtractor = require('./contentExtractor'), scraperLib = require('./scraper.js');

exports.requestAnnotate = requestAnnotate;
exports.start = start;

function start(server) {
  bayeux.attach(server);

// user functions

  fayeClient.subscribe('/team/list', function(data) {
    GLOBAL.info('team/list'.yellow, data);
    fayeClient.publish('/teamList', GLOBAL.config.users);
  });

  fayeClient.subscribe('/team/remove', function(member) {
    GLOBAL.info('team/remove'.yellow, member);
    for (var i = 0; i < GLOBAL.config.users.length; i++) {
      if (GLOBAL.config.users[i].username == member.username) {
        GLOBAL.config.users.splice(i, 1);
        saveUsers();
        fayeClient.publish('/teamList', GLOBAL.config.users);
      }
    }
  });

  fayeClient.subscribe('/team/save', function(member) {
    GLOBAL.info('team/save'.yellow, member);
    for (var i = 0; i < GLOBAL.config.users.length; i++) {
      if (GLOBAL.config.users[i].username == member.username) {
        GLOBAL.config.users[i] = member;
        saveUsers();
        fayeClient.publish('/teamList', GLOBAL.config.users);
      }
    }
  });

  fayeClient.subscribe('/team/add', function(candidate) {
    GLOBAL.info('team/add'.yellow, candidate);
    if (candidate.name && candidate.type) {
      saveUsers(function() {
        GLOBAL.config.users.push({id : new Date().getTime(), active: new Date(), username : candidate.name, type: candidate.type});
      });
      fayeClient.publish('/teamList', GLOBAL.config.users);
    }
  });

// FIXME log signouts
  fayeClient.subscribe('/logout', function(data) {
    console.log('/logout', data);
  });

// annotations

// annotations for an individual uri
  fayeClient.subscribe('/annotate', function(data) {
    GLOBAL.info('/annotate'.yellow, data);
    // FIXME deal with anchors
    indexer.retrieveAnnotations(data.uri.replace(/#.*$/, ''), function(err, results) {
      if (err) {
        GLOBAL.error('/annotate error' + err);
      } else {
        fayeClient.publish('/annotations', { uri: data.uri, annotations: results.hits.hits.map(function(h) { return h._source;})});
      }
    });
  });

  // index incoming annotations, adding validated state
  fayeClient.subscribe('/saveAnnotations', function(combo) {
    GLOBAL.info('saveAnnotations'.yellow, combo.uri, combo.annotations.length);
// apply validation state based on user
    combo.annotations.forEach(function(a) {
      a.validated = false;
      GLOBAL.config.users.forEach(function(u) {
        if (u.username === a.annotatedBy) {
          a.validated = !u.needsValidation;
        }
      });
    });
    GLOBAL.config.indexer.saveAnnotations(combo.uri, combo.annotations);
    fayeClient.publish('/annotations', { uri: combo.uri, annotations: combo.annotations});
  });

  // form search
  fayeClient.subscribe('/search', function(data) {
    GLOBAL.info('/search'.yellow, data.client);
    GLOBAL.config.indexer.formSearch(data, function(err, results) {
      if (err) {
        GLOBAL.error('/search query failed', JSON.stringify(results.query, null, 2));
      }
      if (results.hits) {
        GLOBAL.info('searchResults'.yellow, results.hits.hits.length);
        fayeClient.publish('/searchResults/' + data.client, results);
      } else {
        fayeClient.publish('/searchResults/' + data.client, []);
        GLOBAL.debug('no search results');
      }
    });
  });

  // form cluster
  fayeClient.subscribe('/cluster', function(data) {
    GLOBAL.info('/cluster'.yellow, data);
    GLOBAL.config.indexer.formCluster(data, function(err, results) {
      if (results) {
        GLOBAL.info('clusterResults'.yellow, err, results.hits.hits.length);
        fayeClient.publish('/clusterResults', results);
      } else {
        fayeClient.publish('/clusterResults', []);
        GLOBAL.debug('no cluster results');
      }
    });
  });

  // update content of existing item by uri
  fayeClient.subscribe('/updateContent', function(data) {
    GLOBAL.info('/updateContent'.yellow, data.uri);
    updateContent(data);
  });

  // retrieve an existing content item by uri
  fayeClient.subscribe('/getContentItem', function(uri) {
    GLOBAL.info('/getContentItem'.yellow, uri);
    indexer.retrieveByURI(uri, function(err, result) {
      fayeClient.publish('/updateItem', result);
    });
  });

  fayeClient.subscribe('/delete', function(cItemURIs) {
    GLOBAL.info('/delete'.yellow, cItemURIs);
    indexer.deleteContentItems(cItemURIs.selected, function(err, res) {
      if (err) {
        GLOBAL.error('/delete', err, res);
      } else {
        fayeClient.publish('/deletedItem', {_id: res._id});
      }
    });
  });

  fayeClient.subscribe('/moreLikeThis', function(data) {
    GLOBAL.info('/moreLikeThis'.yellow, data);
    GLOBAL.config.indexer.moreLikeThis(data.uri, function(err, results) {
      if (results) {
        GLOBAL.info('moreLikeThisResults', err, results.hits.hits.length);
        fayeClient.publish('/searchResults', results);
      } else {
        fayeClient.publish('/searchResults', []);
        GLOBAL.debug('NO RESULTS');
      }
    });
  });

  fayeClient.subscribe('/queueLinks', function(data) {
   var relevance = data.relevance, tags = data.tags, referers = [data.referer], scraper = data.scraper, validated = true;

    data.links.forEach(function(uri) {
      scraperLib.queueLink(uri, relevance, tags, referers, scraper, validated);
    });
  });
}

// updates clients with a content item
exports.updateItem = function(cItem) {
  fayeClient.publish('/updateItem', cItem);
};

// requests annotators to annotate. pass plain text or it will be extracted from cItem

function requestAnnotate(uri, html) {
  contentExtractor.extractContent(uri, html, function(uri, html, selector, content) {
    GLOBAL.info('selector', uri, selector, content ? content.length : 'nocontent');
    fayeClient.publish('/requestAnnotate', { uri: uri, source: html, html: content, selector: selector, text: utils.getTextFromHtml(content)});
  });
}

function saveUsers(istep) {
  fs.writeFileSync('versions/local-users.' + new Date().getTime() + '.json', JSON.stringify({ logins : GLOBAL.config.users}, null, 2));
  if (istep) { istep(); }
  fs.writeFileSync('local-users.json', JSON.stringify({ logins : GLOBAL.config.users}, null, 2));
}

function updateContent(desc) {
  indexer.resetAnnotations({ target: desc.uri }, function(err, res) {
    indexer.updateContent(desc, function(err, result) {
      if (err) {
        GLOBAL.error('error', err);
      } else {
        requestAnnotate(desc.uri, desc.content);
      }
    });
  });
}

<commit_msg>local config<commit_after>// pub-sub functions for team interaction

var indexer = require('../lib/indexer');
var utils = require('../lib/utils');
var faye = require('faye');
var bayeux = new faye.NodeAdapter({mount: GLOBAL.config.sitebase, timeout: 45});
var fayeClient = new faye.Client(GLOBAL.config.FAYEHOST);
var annotations = require('./annotations.js'), contentExtractor = require('./contentExtractor'), scraperLib = require('./scraper.js');

exports.requestAnnotate = requestAnnotate;
exports.start = start;

function start(server) {
  bayeux.attach(server);

// user functions

  fayeClient.subscribe('/team/list', function(data) {
    GLOBAL.info('team/list'.yellow, data);
    fayeClient.publish('/teamList', GLOBAL.config.users);
  });

  fayeClient.subscribe('/team/remove', function(member) {
    GLOBAL.info('team/remove'.yellow, member);
    for (var i = 0; i < GLOBAL.config.users.length; i++) {
      if (GLOBAL.config.users[i].username == member.username) {
        GLOBAL.config.users.splice(i, 1);
        saveUsers();
        fayeClient.publish('/teamList', GLOBAL.config.users);
      }
    }
  });

  fayeClient.subscribe('/team/save', function(member) {
    GLOBAL.info('team/save'.yellow, member);
    for (var i = 0; i < GLOBAL.config.users.length; i++) {
      if (GLOBAL.config.users[i].username == member.username) {
        GLOBAL.config.users[i] = member;
        saveUsers();
        fayeClient.publish('/teamList', GLOBAL.config.users);
      }
    }
  });

  fayeClient.subscribe('/team/add', function(candidate) {
    GLOBAL.info('team/add'.yellow, candidate);
    if (candidate.name && candidate.type) {
      saveUsers(function() {
        GLOBAL.config.users.push({id : new Date().getTime(), active: new Date(), username : candidate.name, type: candidate.type});
      });
      fayeClient.publish('/teamList', GLOBAL.config.users);
    }
  });

// FIXME log signouts
  fayeClient.subscribe('/logout', function(data) {
    console.log('/logout', data);
  });

// annotations

// annotations for an individual uri
  fayeClient.subscribe('/annotate', function(data) {
    GLOBAL.info('/annotate'.yellow, data);
    // FIXME deal with anchors
    indexer.retrieveAnnotations(data.uri.replace(/#.*$/, ''), function(err, results) {
      if (err) {
        GLOBAL.error('/annotate error' + err);
      } else {
        fayeClient.publish('/annotations', { uri: data.uri, annotations: results.hits.hits.map(function(h) { return h._source;})});
      }
    });
  });

  // index incoming annotations, adding validated state
  fayeClient.subscribe('/saveAnnotations', function(combo) {
    GLOBAL.info('saveAnnotations'.yellow, combo.uri, combo.annotations.length);
// apply validation state based on user
    combo.annotations.forEach(function(a) {
      a.validated = false;
      GLOBAL.config.users.forEach(function(u) {
        if (u.username === a.annotatedBy) {
          a.validated = !u.needsValidation;
        }
      });
    });
    GLOBAL.config.indexer.saveAnnotations(combo.uri, combo.annotations);
    fayeClient.publish('/annotations', { uri: combo.uri, annotations: combo.annotations});
  });

  // form search
  fayeClient.subscribe('/search', function(data) {
    GLOBAL.info('/search'.yellow, data.client);
    GLOBAL.config.indexer.formSearch(data, function(err, results) {
      if (err) {
        GLOBAL.error('/search query failed', JSON.stringify(results.query, null, 2));
      }
      if (results.hits) {
        GLOBAL.info('searchResults'.yellow, results.hits.hits.length);
        fayeClient.publish('/searchResults/' + data.client, results);
      } else {
        fayeClient.publish('/searchResults/' + data.client, []);
        GLOBAL.debug('no search results');
      }
    });
  });

  // form cluster
  fayeClient.subscribe('/cluster', function(data) {
    GLOBAL.info('/cluster'.yellow, data);
    GLOBAL.config.indexer.formCluster(data, function(err, results) {
      if (results) {
        GLOBAL.info('clusterResults'.yellow, err, results.hits.hits.length);
        fayeClient.publish('/clusterResults', results);
      } else {
        fayeClient.publish('/clusterResults', []);
        GLOBAL.debug('no cluster results');
      }
    });
  });

  // update content of existing item by uri
  fayeClient.subscribe('/updateContent', function(data) {
    GLOBAL.info('/updateContent'.yellow, data.uri);
    updateContent(data);
  });

  // retrieve an existing content item by uri
  fayeClient.subscribe('/getContentItem', function(uri) {
    GLOBAL.info('/getContentItem'.yellow, uri);
    indexer.retrieveByURI(uri, function(err, result) {
      fayeClient.publish('/updateItem', result);
    });
  });

  fayeClient.subscribe('/delete', function(cItemURIs) {
    GLOBAL.info('/delete'.yellow, cItemURIs);
    indexer.deleteContentItems(cItemURIs.selected, function(err, res) {
      if (err) {
        GLOBAL.error('/delete', err, res);
      } else {
        fayeClient.publish('/deletedItem', {_id: res._id});
      }
    });
  });

  fayeClient.subscribe('/moreLikeThis', function(data) {
    GLOBAL.info('/moreLikeThis'.yellow, data);
    GLOBAL.config.indexer.moreLikeThis(data.uri, function(err, results) {
      if (results) {
        GLOBAL.info('moreLikeThisResults', err, results.hits.hits.length);
        fayeClient.publish('/searchResults', results);
      } else {
        fayeClient.publish('/searchResults', []);
        GLOBAL.debug('NO RESULTS');
      }
    });
  });

  fayeClient.subscribe('/queueLinks', function(data) {
   var relevance = data.relevance, tags = data.tags, referers = [data.referer], scraper = data.scraper, validated = true;

    data.links.forEach(function(uri) {
      scraperLib.queueLink(uri, relevance, tags, referers, scraper, validated);
    });
  });
}

// updates clients with a content item
exports.updateItem = function(cItem) {
  fayeClient.publish('/updateItem', cItem);
};

// requests annotators to annotate. pass plain text or it will be extracted from cItem

function requestAnnotate(uri, html) {
  contentExtractor.extractContent(uri, html, function(uri, html, selector, content) {
    GLOBAL.info('selector', uri, selector, content ? content.length : 'nocontent');
    fayeClient.publish('/requestAnnotate', { uri: uri, source: html, html: content, selector: selector, text: utils.getTextFromHtml(content)});
  });
}

function saveUsers(istep) {
  fs.writeFileSync('versions/local-users.' + new Date().getTime() + '.json', JSON.stringify({ logins : GLOBAL.config.users}, null, 2));
  if (istep) { istep(); }
  fs.writeFileSync('local-users.json', JSON.stringify({ logins : GLOBAL.config.users}, null, 2));
}

function updateContent(desc) {
  indexer.resetAnnotations({ target: desc.uri }, function(err, res) {
    indexer.updateContent(desc, function(err, result) {
      if (err) {
        GLOBAL.error('error', err);
      } else {
        requestAnnotate(desc.uri, desc.content);
      }
    });
  });
}

<|endoftext|>


<commit_before>var crypto = require('crypto');
var fs = require('fs');

var q = require('q');
var async = require('async');

var mkdirp = require('mkdirp');

var request = require('request');

module.exports.ttl = 60 * 60 * 24;
module.exports.cacheDirectory = './temp/cache/';

module.exports._requestFromUrl = function (url, callback) {

    var hash = crypto.createHash('sha1').update(url).digest('hex');

    fs.stat(module.exports.cacheDirectory + hash, function (err, stats) {

        if (stats && ((Date.now() - stats.ctime.getTime()) / 1000) < module.exports.ttl) {

            fs.readFile(module.exports.cacheDirectory + hash, 'utf8', function (err, res) {

                callback(err, JSON.parse(res));

            });

        } else {

            request(url, function (err, res, body) {

                mkdirp(module.exports.cacheDirectory, function () {

                    fs.writeFile(module.exports.cacheDirectory + hash, JSON.stringify(res), function () {

                        callback(err, res);

                    });

                });

            });

        }

    });

};

module.exports.get = function (input) {

    var deferred = new q.defer();

    function callback (err, contents) {

        if (err) {

            deferred.reject(new Error(err));

        } else {

            deferred.resolve(contents);

        }

    }

    if (Array.isArray(input)) {

        async.map(input, module.exports._requestFromUrl, callback);

    } else {

        module.exports._requestFromUrl(url, callback);

    }

    return deferred.promise;

};
<commit_msg>Fixed invalid variable.<commit_after>var crypto = require('crypto');
var fs = require('fs');

var q = require('q');
var async = require('async');

var mkdirp = require('mkdirp');

var request = require('request');

module.exports.ttl = 60 * 60 * 24;
module.exports.cacheDirectory = './temp/cache/';

module.exports._requestFromUrl = function (url, callback) {

    var hash = crypto.createHash('sha1').update(url).digest('hex');

    fs.stat(module.exports.cacheDirectory + hash, function (err, stats) {

        if (stats && ((Date.now() - stats.ctime.getTime()) / 1000) < module.exports.ttl) {

            fs.readFile(module.exports.cacheDirectory + hash, 'utf8', function (err, res) {

                callback(err, JSON.parse(res));

            });

        } else {

            request(url, function (err, res, body) {

                mkdirp(module.exports.cacheDirectory, function () {

                    fs.writeFile(module.exports.cacheDirectory + hash, JSON.stringify(res), function () {

                        callback(err, res);

                    });

                });

            });

        }

    });

};

module.exports.get = function (input) {

    var deferred = new q.defer();

    function callback (err, contents) {

        if (err) {

            deferred.reject(new Error(err));

        } else {

            deferred.resolve(contents);

        }

    }

    if (Array.isArray(input)) {

        async.map(input, module.exports._requestFromUrl, callback);

    } else {

        module.exports._requestFromUrl(input, callback);

    }

    return deferred.promise;

};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var util = require('util');
var assert = require('assert');
var Parser = require('stream-parser');
var Transform = require('readable-stream/transform');
var debug = require('debug')('wave:reader');
var inherits = util.inherits;
var f = util.format;

var formats = {
  WAVE_FORMAT_PCM: 0x0001, // PCM
  WAVE_FORMAT_IEEE_FLOAT: 0x0003, // IEEE float
  WAVE_FORMAT_ALAW: 0x0006, // 8-bit ITU-T G.711 A-law
  WAVE_FORMAT_MULAW: 0x0007, // 8-bit ITU-T G.711 µ-law
  WAVE_FORMAT_EXTENSIBLE: 0xFFFE // Determined by SubFormat
};

/**
 * Module exports.
 */

module.exports = Reader;

/**
 * The `Reader` class accepts a WAV audio file written to it and outputs the raw
 * audio data with the WAV header stripped (most of the time, PCM audio data will
 * be output, depending on the `audioFormat` property).
 *
 * A `"format"` event gets emitted after the WAV header has been parsed.
 *
 * @param {Object} opts optional options object
 * @api public
 */

function Reader (opts) {
  if (!(this instanceof Reader)) {
    return new Reader(opts);
  }
  Transform.call(this, opts);

  this._bytes(4, this._onRiffID);
}
inherits(Reader, Transform);

/**
 * Mixin `Parser`.
 */

Parser(Reader.prototype);

// the beginning of the WAV file
Reader.prototype._onRiffID = function (chunk) {
  debug('onRiffID:', chunk);
  var id = this.riffId = chunk.toString('ascii');
  if ('RIFF' === id) {
    debug('detected little-endian WAVE file');
    this.endianness = 'LE';
    this._bytes(4, this._onChunkSize);
  } else if ('RIFX' === id) {
    debug('detected big-endian WAVE file');
    this.endianness = 'BE';
    this._bytes(4, this._onChunkSize);
  } else {
    this.emit('error', new Error(f('bad "chunk id": expected "RIFF" or "RIFX", got %j', id)));
  }
};

// size of the WAV
Reader.prototype._onChunkSize = function (chunk) {
  debug('onChunkSize:', chunk);
  this.chunkSize = chunk['readUInt32' + this.endianness](0);
  this._bytes(4, this._onFormat);
};

// the RIFF "format", should always be "WAVE"
Reader.prototype._onFormat = function (chunk) {
  debug('onFormat:', chunk);
  this.waveId = chunk.toString('ascii');
  if ('WAVE' === this.waveId) {
    this._bytes(4, this._onSubchunk1ID);
  } else {
    this.emit('error', new Error(f('bad "format": expected "WAVE", got %j', this.waveId)));
  }
};

// size of the "subchunk1" (the header)
Reader.prototype._onSubchunk1ID = function (chunk) {
  debug('onSubchunk1ID:', chunk);
  var subchunk1ID = chunk.toString('ascii');
  this.chunkId = subchunk1ID;
  if ('fmt ' === subchunk1ID) {
    this._bytes(4, this._onSubchunk1Size);
  } else {
    this.emit('error', new Error(f('bad "fmt id": expected "fmt ", got %j', subchunk1ID)));
  }
};

Reader.prototype._onSubchunk1Size = function (chunk) {
  debug('onSubchunk1Size:', chunk);
  this.subchunk1Size = chunk['readUInt32' + this.endianness](0);
  // TODO: assert should be 16 for PCM
  this._bytes(this.subchunk1Size, this._onSubchunk1);
};

Reader.prototype._onSubchunk1 = function (chunk) {
  debug('onSubchunk1:', chunk);
  // TODO: support formats other than PCM?
  this.audioFormat = chunk['readUInt16' + this.endianness](0);
  this.channels = chunk['readUInt16' + this.endianness](2);
  this.sampleRate = chunk['readUInt32' + this.endianness](4);
  this.byteRate = chunk['readUInt32' + this.endianness](8); // useless...
  this.blockAlign = chunk['readUInt16' + this.endianness](12); // useless...
  this.bitDepth = chunk['readUInt16' + this.endianness](14);
  this.signed = this.bitDepth != 8;

  var format = {
    audioFormat: this.audioFormat,
    endianness: this.endianness,
    channels: this.channels,
    sampleRate: this.sampleRate,
    byteRate: this.byteRate,
    blockAlign: this.blockAlign,
    bitDepth: this.bitDepth,
    signed: this.signed
  };

  switch (format.audioFormat) {
    case formats.WAVE_FORMAT_PCM:
      // default, common case. don't need to do anything.
      break;
    case: formats.WAVE_FORMAT_IEEE_FLOAT:
      format.float = true;
      break;
    case: formats.WAVE_FORMAT_ALAW:
      format.alaw = true;
      break;
    case: formats.WAVE_FORMAT_MULAW:
      format.ulaw = true;
      break;
  }

  this.emit('format', format);

  this._bytes(4, this._onSubchunk2ID);
};

Reader.prototype._onSubchunk2ID = function (chunk) {
  debug('onSubchunk2ID:', chunk);
  var subchunk2ID = chunk.toString('ascii');
  if ('data' === subchunk2ID) {
    this._bytes(4, this._onSubchunk2Size);
  } else {
    this.emit('error', new Error(f('bad "data" chunk: expected "data", got %j', subchunk2ID)));
  }
};

// size of the remaining data in this WAV file
Reader.prototype._onSubchunk2Size = function (chunk) {
  debug('onSubchunk2Size:', chunk);
  this.subchunk2Size = chunk['readUInt32' + this.endianness](0);

  // even though the WAV file reports a remaining byte length, in practice it
  // can't really be trusted since in streaming situations where the WAV file is
  // being generated on-the-fly, the number of remaining bytes would be impossible
  // to know beforehand. For this reason, some encoders write `0` for the byte
  // length here... In any case, we are just gonna pass through the rest of the
  // stream until EOF.
  this._passthrough(Infinity, this._onEnd);
};
<commit_msg>reader: fix syntax errors<commit_after>
/**
 * Module dependencies.
 */

var util = require('util');
var assert = require('assert');
var Parser = require('stream-parser');
var Transform = require('readable-stream/transform');
var debug = require('debug')('wave:reader');
var inherits = util.inherits;
var f = util.format;

var formats = {
  WAVE_FORMAT_PCM: 0x0001, // PCM
  WAVE_FORMAT_IEEE_FLOAT: 0x0003, // IEEE float
  WAVE_FORMAT_ALAW: 0x0006, // 8-bit ITU-T G.711 A-law
  WAVE_FORMAT_MULAW: 0x0007, // 8-bit ITU-T G.711 µ-law
  WAVE_FORMAT_EXTENSIBLE: 0xFFFE // Determined by SubFormat
};

/**
 * Module exports.
 */

module.exports = Reader;

/**
 * The `Reader` class accepts a WAV audio file written to it and outputs the raw
 * audio data with the WAV header stripped (most of the time, PCM audio data will
 * be output, depending on the `audioFormat` property).
 *
 * A `"format"` event gets emitted after the WAV header has been parsed.
 *
 * @param {Object} opts optional options object
 * @api public
 */

function Reader (opts) {
  if (!(this instanceof Reader)) {
    return new Reader(opts);
  }
  Transform.call(this, opts);

  this._bytes(4, this._onRiffID);
}
inherits(Reader, Transform);

/**
 * Mixin `Parser`.
 */

Parser(Reader.prototype);

// the beginning of the WAV file
Reader.prototype._onRiffID = function (chunk) {
  debug('onRiffID:', chunk);
  var id = this.riffId = chunk.toString('ascii');
  if ('RIFF' === id) {
    debug('detected little-endian WAVE file');
    this.endianness = 'LE';
    this._bytes(4, this._onChunkSize);
  } else if ('RIFX' === id) {
    debug('detected big-endian WAVE file');
    this.endianness = 'BE';
    this._bytes(4, this._onChunkSize);
  } else {
    this.emit('error', new Error(f('bad "chunk id": expected "RIFF" or "RIFX", got %j', id)));
  }
};

// size of the WAV
Reader.prototype._onChunkSize = function (chunk) {
  debug('onChunkSize:', chunk);
  this.chunkSize = chunk['readUInt32' + this.endianness](0);
  this._bytes(4, this._onFormat);
};

// the RIFF "format", should always be "WAVE"
Reader.prototype._onFormat = function (chunk) {
  debug('onFormat:', chunk);
  this.waveId = chunk.toString('ascii');
  if ('WAVE' === this.waveId) {
    this._bytes(4, this._onSubchunk1ID);
  } else {
    this.emit('error', new Error(f('bad "format": expected "WAVE", got %j', this.waveId)));
  }
};

// size of the "subchunk1" (the header)
Reader.prototype._onSubchunk1ID = function (chunk) {
  debug('onSubchunk1ID:', chunk);
  var subchunk1ID = chunk.toString('ascii');
  this.chunkId = subchunk1ID;
  if ('fmt ' === subchunk1ID) {
    this._bytes(4, this._onSubchunk1Size);
  } else {
    this.emit('error', new Error(f('bad "fmt id": expected "fmt ", got %j', subchunk1ID)));
  }
};

Reader.prototype._onSubchunk1Size = function (chunk) {
  debug('onSubchunk1Size:', chunk);
  this.subchunk1Size = chunk['readUInt32' + this.endianness](0);
  // TODO: assert should be 16 for PCM
  this._bytes(this.subchunk1Size, this._onSubchunk1);
};

Reader.prototype._onSubchunk1 = function (chunk) {
  debug('onSubchunk1:', chunk);
  // TODO: support formats other than PCM?
  this.audioFormat = chunk['readUInt16' + this.endianness](0);
  this.channels = chunk['readUInt16' + this.endianness](2);
  this.sampleRate = chunk['readUInt32' + this.endianness](4);
  this.byteRate = chunk['readUInt32' + this.endianness](8); // useless...
  this.blockAlign = chunk['readUInt16' + this.endianness](12); // useless...
  this.bitDepth = chunk['readUInt16' + this.endianness](14);
  this.signed = this.bitDepth != 8;

  var format = {
    audioFormat: this.audioFormat,
    endianness: this.endianness,
    channels: this.channels,
    sampleRate: this.sampleRate,
    byteRate: this.byteRate,
    blockAlign: this.blockAlign,
    bitDepth: this.bitDepth,
    signed: this.signed
  };

  switch (format.audioFormat) {
    case formats.WAVE_FORMAT_PCM:
      // default, common case. don't need to do anything.
      break;
    case formats.WAVE_FORMAT_IEEE_FLOAT:
      format.float = true;
      break;
    case formats.WAVE_FORMAT_ALAW:
      format.alaw = true;
      break;
    case formats.WAVE_FORMAT_MULAW:
      format.ulaw = true;
      break;
  }

  this.emit('format', format);

  this._bytes(4, this._onSubchunk2ID);
};

Reader.prototype._onSubchunk2ID = function (chunk) {
  debug('onSubchunk2ID:', chunk);
  var subchunk2ID = chunk.toString('ascii');
  if ('data' === subchunk2ID) {
    this._bytes(4, this._onSubchunk2Size);
  } else {
    this.emit('error', new Error(f('bad "data" chunk: expected "data", got %j', subchunk2ID)));
  }
};

// size of the remaining data in this WAV file
Reader.prototype._onSubchunk2Size = function (chunk) {
  debug('onSubchunk2Size:', chunk);
  this.subchunk2Size = chunk['readUInt32' + this.endianness](0);

  // even though the WAV file reports a remaining byte length, in practice it
  // can't really be trusted since in streaming situations where the WAV file is
  // being generated on-the-fly, the number of remaining bytes would be impossible
  // to know beforehand. For this reason, some encoders write `0` for the byte
  // length here... In any case, we are just gonna pass through the rest of the
  // stream until EOF.
  this._passthrough(Infinity, this._onEnd);
};
<|endoftext|>


<commit_before>import childProcess from 'child_process'
import fs from 'fs'
import moment from 'moment'
import path from 'path'
import { info } from './log'

function mkdirP (path) {
  return new Promise((resolve, reject) => {
    childProcess.exec(`mkdir -p ${path}`, (err, stdout, stderr) => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })
}

function echo (path, str) {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, str, err => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })
}

function addCommitPush (recordDir, filename) {
  return new Promise((resolve, reject) => {
    childProcess.exec(`cd ${recordDir} && git add ${filename} && git commit -m '${filename}' && git push origin master`, (err, stdout, stderr) => {
      if (err) {
        reject(err)
      } else {
        console.log(stdout)
        console.log(stderr)
        resolve()
      }
    })
  })
}

function dirExists (filename) {
  return new Promise((resolve, reject) => {
    fs.stat(filename, (err, stat) => {
      if (err == null) {
        resolve(true)
      } else if (err.code === 'ENOENT') {
        resolve(false)
      } else {
        reject(err)
      }
    })
  })
}

module.exports = function (recordDir) {
  return function (type, data, occurred = moment()) {
    const dateStr = occurred.format('YYYY-MM-DD-hh-mm-ss')
    const filename = `${dateStr}-${type}.json`
    const fullPath = path.resolve(recordDir, filename)
    info(`recording '${type}' action to ${fullPath}`)

    return mkdirP(recordDir).then(() => {
      return echo(fullPath, JSON.stringify(data, (k, v) => {
        if (k === 'parent' || k === 'group') {
          return v.id
        } else {
          return v
        }
      }, 2))
    }).then(() => {
      return dirExists(path.resolve(recordDir, '.git'))
    }).then(isGit => {
      if (isGit) {
        return addCommitPush(recordDir, filename)
      }
    })
  }
}
<commit_msg>Remove console.logs.<commit_after>import childProcess from 'child_process'
import fs from 'fs'
import moment from 'moment'
import path from 'path'
import { info } from './log'

function mkdirP (path) {
  return new Promise((resolve, reject) => {
    childProcess.exec(`mkdir -p ${path}`, (err, stdout, stderr) => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })
}

function echo (path, str) {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, str, err => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })
}

function addCommitPush (recordDir, filename) {
  return new Promise((resolve, reject) => {
    childProcess.exec(`cd ${recordDir} && git add ${filename} && git commit -m '${filename}' && git push origin master`, (err, stdout, stderr) => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })
}

function dirExists (filename) {
  return new Promise((resolve, reject) => {
    fs.stat(filename, (err, stat) => {
      if (err == null) {
        resolve(true)
      } else if (err.code === 'ENOENT') {
        resolve(false)
      } else {
        reject(err)
      }
    })
  })
}

module.exports = function (recordDir) {
  return function (type, data, occurred = moment()) {
    const dateStr = occurred.format('YYYY-MM-DD-hh-mm-ss')
    const filename = `${dateStr}-${type}.json`
    const fullPath = path.resolve(recordDir, filename)
    info(`recording '${type}' action to ${fullPath}`)

    return mkdirP(recordDir).then(() => {
      return echo(fullPath, JSON.stringify(data, (k, v) => {
        if (k === 'parent' || k === 'group') {
          return v.id
        } else {
          return v
        }
      }, 2))
    }).then(() => {
      return dirExists(path.resolve(recordDir, '.git'))
    }).then(isGit => {
      if (isGit) {
        return addCommitPush(recordDir, filename)
      }
    })
  }
}
<|endoftext|>