<commit_before>var Boom = require('boom');
var Promise = require('bluebird');
var archiver = require('archiver');
var errors = require('./errors');

function BaseController(model)  {
  this.Model = model;
}

BaseController.prototype.formatRequestData = function(req) {
  // Abstract base method,
  // formats data for database entry
};

BaseController.prototype.formatResponseData = function(model) {
  // Base method to format data that will be sent in the response
  // By default, it returns the model as is
  return model;
};

BaseController.prototype.getOne = function(req, reply) {
  var record = this.formatResponseData(req.pre.records.models[0].toJSON());
  reply(req.generateResponse(record)
    .code(200));
};

BaseController.prototype.getAll = function(req, reply) {
  var records = req.pre.records.toJSON().map(this.formatResponseData);
  reply(req.generateResponse(records));
};

BaseController.prototype.update = function(req, reply) {
  var reqData = this.formatRequestData(req);

  var result = Promise.resolve().then(function() {
    var record = req.pre.records.models[0];

    record.set(reqData);
    if (!record.hasChanged()) {
      return record;
    }

    return record
      .save(record.changed, { patch: true, method: 'update' });
  })
  .then(function (updatedState) {
    return req.generateResponse(updatedState.toJSON()).code(200);
  })
  .catch(errors.generateErrorResponse);

  reply(result);
};

BaseController.prototype.create = function(req, reply) {
  var result = this.Model
    .forge(this.formatRequestData(req))
    .save()
    .then(function(record) {
      if (!record) { throw Boom.notFound(); }
      return req.generateResponse(record.toJSON())
        .code(201);
    })
    .catch(errors.generateErrorResponse);
  reply(result);
};

BaseController.prototype.delete = function(req, reply) {
  var record = req.pre.records.models[0];

  var result = Promise.resolve().then(function() {
    return record.destroy();
  })
  .then(function() {
    return req.generateResponse(record.toJSON())
      .code(204);
  })
  .catch(errors.generateErrorResponse);

  reply(result);
};

BaseController.prototype.getAllAsMeta = function(req, reply) {
  reply(req.generateResponse(req.pre.records.toJSON()));
};

BaseController.prototype.getAllAsTar = function(req, reply) {
  var files = req.pre.records.models;
  var self = this;

  function createTarStream() {
    var archive = archiver('tar');

    return Promise.map(files, function(file) {
      return self.Model.query({
        where: {
          id: file.get('id')
        },
        columns: ['buffer']
      }).fetch()
      .then(function(model) {
        archive.append(model.get('buffer'), { name: file.get('path') });
      });
    }).then(function() {
      archive.finalize();

      return archive;
    });
  }

  return reply(createTarStream())
    .header('Content-Type', 'application/x-tar');
};

module.exports = BaseController;
<commit_msg>Fix Content-Type for IE so decompression works for tarballs<commit_after>var Boom = require('boom');
var Promise = require('bluebird');
var archiver = require('archiver');
var errors = require('./errors');

function BaseController(model)  {
  this.Model = model;
}

BaseController.prototype.formatRequestData = function(req) {
  // Abstract base method,
  // formats data for database entry
};

BaseController.prototype.formatResponseData = function(model) {
  // Base method to format data that will be sent in the response
  // By default, it returns the model as is
  return model;
};

BaseController.prototype.getOne = function(req, reply) {
  var record = this.formatResponseData(req.pre.records.models[0].toJSON());
  reply(req.generateResponse(record)
    .code(200));
};

BaseController.prototype.getAll = function(req, reply) {
  var records = req.pre.records.toJSON().map(this.formatResponseData);
  reply(req.generateResponse(records));
};

BaseController.prototype.update = function(req, reply) {
  var reqData = this.formatRequestData(req);

  var result = Promise.resolve().then(function() {
    var record = req.pre.records.models[0];

    record.set(reqData);
    if (!record.hasChanged()) {
      return record;
    }

    return record
      .save(record.changed, { patch: true, method: 'update' });
  })
  .then(function (updatedState) {
    return req.generateResponse(updatedState.toJSON()).code(200);
  })
  .catch(errors.generateErrorResponse);

  reply(result);
};

BaseController.prototype.create = function(req, reply) {
  var result = this.Model
    .forge(this.formatRequestData(req))
    .save()
    .then(function(record) {
      if (!record) { throw Boom.notFound(); }
      return req.generateResponse(record.toJSON())
        .code(201);
    })
    .catch(errors.generateErrorResponse);
  reply(result);
};

BaseController.prototype.delete = function(req, reply) {
  var record = req.pre.records.models[0];

  var result = Promise.resolve().then(function() {
    return record.destroy();
  })
  .then(function() {
    return req.generateResponse(record.toJSON())
      .code(204);
  })
  .catch(errors.generateErrorResponse);

  reply(result);
};

BaseController.prototype.getAllAsMeta = function(req, reply) {
  reply(req.generateResponse(req.pre.records.toJSON()));
};

BaseController.prototype.getAllAsTar = function(req, reply) {
  var files = req.pre.records.models;
  var self = this;

  function createTarStream() {
    var archive = archiver('tar');

    return Promise.map(files, function(file) {
      return self.Model.query({
        where: {
          id: file.get('id')
        },
        columns: ['buffer']
      }).fetch()
      .then(function(model) {
        archive.append(model.get('buffer'), { name: file.get('path') });
      });
    }).then(function() {
      archive.finalize();

      return archive;
    });
  }

  // Normally this type would be application/x-tar, but IE refuses to
  // decompress a gzipped stream when this is the type.
  return reply(createTarStream())
    .header('Content-Type', 'application/octet-stream');
};

module.exports = BaseController;
<|endoftext|>


<commit_before>/**
 * Basic [iOS] Example for react-native-blur
 * https://github.com/react-native-community/react-native-blur
 */
import React, {Component} from 'react'
import {
  AppRegistry,
  StyleSheet,
  Text,
  Image,
  View,
  SegmentedControlIOS,
  Switch
} from 'react-native'

import {BlurView, VibrancyView} from 'react-native-blur'

class Basic extends Component {

  constructor() {
    super()
    this.state = {
      hideBlurs: false,
      blurBlurType: 'light',
      blurActiveSegment: 1,
      vibrancyBlurType: 'dark',
      vibrancyActiveSegment: 2,
    }
  }

  _onBlurChange(event) {
    this.setState({blurActiveSegment: event.nativeEvent.selectedSegmentIndex})
  }

  _onBlurValueChange(value) {
    this.setState({blurBlurType: value})
  }

  _onVibrancyChange(event) {
    this.setState({vibrancyActiveSegment: event.nativeEvent.selectedSegmentIndex})
  }

  _onVibrancyValueChange(value) {
    this.setState({vibrancyBlurType: value})
  }

  render() {
    return (
      <View
        style={styles.container}>

        <Image
          source={require('./bgimage.jpeg')}
          resizeMode='cover'
          style={styles.img}/>

        {(this.state.hideBlurs

          ? null

          : <View style={styles.container}>

              <BlurView
                blurType={this.state.blurBlurType}
                blurAmount={10}
                style={[styles.container, styles.blurContainer]}>
                <Text style={styles.welcome}>{`Blur component`}</Text>
                <SegmentedControlIOS
                  values={['xlight', 'light', 'dark']}
                  selectedIndex={this.state.blurActiveSegment}
                  onChange={(event) => {this._onBlurChange(event)}}
                  onValueChange={(value) => {this._onBlurValueChange(value)}}
                  tintColor={this.state.blurBlurType == 'xlight' ? 'black' : 'white'}/>
              </BlurView>

              <VibrancyView
                blurType={this.state.vibrancyBlurType}
                blurAmount={1}
                style={[styles.container, styles.blurContainer]}>
                <Text style={styles.welcome}>{`Vibrancy component`}</Text>
                <SegmentedControlIOS
                  values={['xlight', 'light', 'dark']}
                  selectedIndex={this.state.vibrancyActiveSegment}
                  onChange={(event) => {this._onVibrancyChange(event)}}
                  onValueChange={(value) => {this._onVibrancyValueChange(value)}}
                  tintColor={this.state.vibrancyBlurType == 'xlight' ? 'black' : 'white'}/>
              </VibrancyView>

            </View>
        )}

        <View
          style={styles.blurToggle}>
          <Switch
            onValueChange={(value) => this.setState({hideBlurs: value})}
            value={this.state.hideBlurs} />
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: 'transparent',
  },
  blurContainer: {
    paddingHorizontal: 20,
  },
  img: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    height: null,
    width: null,
  },
  welcome: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    margin: 10,
    color: 'white',
  },
  blurToggle: {
    position: 'absolute',
    top: 30,
    right: 10,
    alignItems: 'flex-end',
  }
});

AppRegistry.registerComponent('Basic', () => Basic);<commit_msg>Basic example ios reverse toggle logic<commit_after>/**
 * Basic [iOS] Example for react-native-blur
 * https://github.com/react-native-community/react-native-blur
 */
import React, {Component} from 'react'
import {
  AppRegistry,
  StyleSheet,
  Text,
  Image,
  View,
  SegmentedControlIOS,
  Switch
} from 'react-native'

import {BlurView, VibrancyView} from 'react-native-blur'

class Basic extends Component {

  constructor() {
    super()
    this.state = {
      showBlurs: true,
      blurBlurType: 'light',
      blurActiveSegment: 1,
      vibrancyBlurType: 'dark',
      vibrancyActiveSegment: 2,
    }
  }

  _onBlurChange(event) {
    this.setState({blurActiveSegment: event.nativeEvent.selectedSegmentIndex})
  }

  _onBlurValueChange(value) {
    this.setState({blurBlurType: value})
  }

  _onVibrancyChange(event) {
    this.setState({vibrancyActiveSegment: event.nativeEvent.selectedSegmentIndex})
  }

  _onVibrancyValueChange(value) {
    this.setState({vibrancyBlurType: value})
  }

  render() {
    return (
      <View
        style={styles.container}>

        <Image
          source={require('./bgimage.jpeg')}
          resizeMode='cover'
          style={styles.img}/>

        {(this.state.showBlurs

          ? <View style={styles.container}>

              <BlurView
                blurType={this.state.blurBlurType}
                blurAmount={10}
                style={[styles.container, styles.blurContainer]}>
                <Text style={styles.welcome}>{`Blur component`}</Text>
                <SegmentedControlIOS
                  values={['xlight', 'light', 'dark']}
                  selectedIndex={this.state.blurActiveSegment}
                  onChange={(event) => {this._onBlurChange(event)}}
                  onValueChange={(value) => {this._onBlurValueChange(value)}}
                  tintColor={this.state.blurBlurType == 'xlight' ? 'black' : 'white'}/>
              </BlurView>

              <VibrancyView
                blurType={this.state.vibrancyBlurType}
                blurAmount={1}
                style={[styles.container, styles.blurContainer]}>
                <Text style={styles.welcome}>{`Vibrancy component`}</Text>
                <SegmentedControlIOS
                  values={['xlight', 'light', 'dark']}
                  selectedIndex={this.state.vibrancyActiveSegment}
                  onChange={(event) => {this._onVibrancyChange(event)}}
                  onValueChange={(value) => {this._onVibrancyValueChange(value)}}
                  tintColor={this.state.vibrancyBlurType == 'xlight' ? 'black' : 'white'}/>
              </VibrancyView>

            </View>

          : null
        )}

        <View
          style={styles.blurToggle}>
          <Switch
            onValueChange={(value) => this.setState({showBlurs: value})}
            value={this.state.showBlurs} />
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: 'transparent',
  },
  blurContainer: {
    paddingHorizontal: 20,
  },
  img: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    height: null,
    width: null,
  },
  welcome: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    margin: 10,
    color: 'white',
  },
  blurToggle: {
    position: 'absolute',
    top: 30,
    right: 10,
    alignItems: 'flex-end',
  }
});

AppRegistry.registerComponent('Basic', () => Basic);<|endoftext|>


<commit_before>/**
 * Created by Snippy Valson on 21/7/16.
 */
var stations=[
    {
        "name":"Alappuzha",
        "code":"ALLP"
    },
    {
        "name":"Aluva",
        "code":"AWY"
    },
    {
        "name":"Angamaly",
        "code":"AFK"
    },
    {
        "name":"Badagara",
        "code":"BDJ"
    },
    {
        "name":"Bekal Fort",
        "code":"BFR"
    },
    {
        "name":"Calicut",
        "code":"CLT"
    },
    {
        "name":"Cannanore",
        "code":"CAN"
    },
    {
        "name":"Chalakudi",
        "code":"CKI"
    },
    {
        "name":"Changanacherry",
        "code":"CGY"
    },
    {
        "name":"Charvattur",
        "code":"CHV"
    },
    {
        "name":"Chengannur",
        "code":"CNGR"
    },
    {
        "name":"Chirayinkil",
        "code":"CRY"
    },
    {
        "name":"Dhanuvachapuram",
        "code":"DAVM"
    },
    {
        "name":"Divinenagar",
        "code":"DINR"
    },
    {
        "name":"Edappally",
        "code":"IPL"
    },
    {
        "name":"Ernakulam Junction",
        "code":"ERS"
    },
    {
        "name":"Ernakulam Town",
        "code":"ERN"
    },
    {
        "name":"Ettumanur",
        "code":"ETM"
    },
    {
        "name":"Ezhimala",
        "code":"ELM"
    },
    {
        "name":"Ferok",
        "code":"FK"
    },
    {
        "name":"Guruvayur",
        "code":"GUV"
    },
    {
        "name":"Haripad",
        "code":"HAD"
    },
    {
        "name":"Irinjalakuda",
        "code":"IJK"
    },
    {
        "name":"Kadakavur",
        "code":"KVU"
    },
    {
        "name":"Kadalundi",
        "code":"KN"
    },
    {
        "name":"Kanhangad",
        "code":"KZE"
    },
    {
        "name":"Kannapuram",
        "code":"KPQ"
    },
    {
        "name":"Karunagapalli",
        "code":"KPY"
    },
    {
        "name":"Kasaragod",
        "code":"KGQ"
    },
    {
        "name":"Kayamkulam",
        "code":"KYJ"
    },
    {
        "name":"Kazhakuttam",
        "code":"KZK"
    },
    {
        "name":"Kollam Junction",
        "code":"QLN"
    },
    {
        "name":"Kotikulam",
        "code":"KQK"
    },
    {
        "name":"Kottayam",
        "code":"KTYM"
    },
    {
        "name":"Koyilandy",
        "code":"QLD"
    },
    {
        "name":"Kumbala",
        "code":"KMQ"
    },
    {
        "name":"Kuttippuram",
        "code":"KTU"
    },
    {
        "name":"Manjeshwar",
        "code":"MJS"
    },
    {
        "name":"Mararikulam",
        "code":"MAKM"
    },
    {
        "name":"Mavelikara",
        "code":"MVLK"
    },
    {
        "name":"Mayyanad",
        "code":"MYY"
    },
    {
        "name":"Mulanturutti",
        "code":"MNTT"
    },
    {
        "name":"Munroturuttu",
        "code":"MQO"
    },
    {
        "name":"Murukkampuzha",
        "code":"MQU"
    },
    {
        "name":"Neyyattinkara",
        "code":"NYY"
    },
    {
        "name":"Nileshwar",
        "code":"NLE"
    },
    {
        "name":"Ottappalam",
        "code":"OTP"
    },
    {
        "name":"Palakkad Town",
        "code":"PGTN"
    },
    {
        "name":"Palghat",
        "code":"PGT"
    },
    {
        "name":"Parassala",
        "code":"PASA"
    },
    {
        "name":"Paravur",
        "code":"PVU"
    },
    {
        "name":"Parpanangadi",
        "code":"PGI"
    },
    {
        "name":"Pattambi",
        "code":"PTB"
    },
    {
        "name":"Payangadi",
        "code":"PAZ"
    },
    {
        "name":"Payyanur",
        "code":"PAY"
    },
    {
        "name":"Payyoli",
        "code":"PYOL"
    },
    {
        "name":"Piravam Road",
        "code":"PVRD"
    },
    {
        "name":"Pudukad",
        "code":"PUK"
    },
    {
        "name":"Punkunnam",
        "code":"PNQ"
    },
    {
        "name":"Sasthamkotta",
        "code":"STKT"
    },
    {
        "name":"Shertalai",
        "code":"SRTL"
    },
    {
        "name":"Shoranur",
        "code":"SRR"
    },
    {
        "name":"Tanur",
        "code":"TA"
    },
    {
        "name":"Tellicherry",
        "code":"TLY"
    },
    {
        "name":"Thiruvananthapuram Pettah",
        "code":"TVP"
    },
    {
        "name":"Tirunnavaya",
        "code":"TUA"
    },
    {
        "name":"Tirur",
        "code":"TIR"
    },
    {
        "name":"Tiruvalla",
        "code":"TRVL"
    },
    {
        "name":"Trichur",
        "code":"TCR"
    },
    {
        "name":"Trikarpur",
        "code":"TKQ"
    },
    {
        "name":"Tripunittura",
        "code":"TRTR"
    },
    {
        "name":"Trivandrum Central",
        "code":"TVC"
    },
    {
        "name":"Trivandrum Kochuveli",
        "code":"KCVL"
    },
    {
        "name":"Turavur",
        "code":"TUVR"
    },
    {
        "name":"Uppala",
        "code":"UAA"
    },
    {
        "name":"Vaikam Road",
        "code":"VARD"
    },
    {
        "name":"Valapattanam",
        "code":"VAPM"
    },
    {
        "name":"Vallikunnu",
        "code":"VLI"
    },
    {
        "name":"Varkala Sivagiri Station",
        "code":"VAK"
    },
    {
        "name":"Wadakanchery",
        "code":"WKI"
    },
    {
        "name":"Adarsh Nagar",
        "code":"ANDI"
    },
    {
        "name":"Anand Vihar",
        "code":"ANVR"
    },
    {
        "name":"Anand Vihar Terminus",
        "code":"ANVT"
    },
    {
        "name":"Badli",
        "code":"BHD"
    },
    {
        "name":"Bijwasan",
        "code":"BWSN"
    },
    {
        "name":"Delhi",
        "code":"DLI"
    },
    {
        "name":"Delhi Cantonment",
        "code":"DEC"
    },
    {
        "name":"Delhi Kishanganj",
        "code":"DKZ"
    },
    {
        "name":"Delhi Safdarjung",
        "code":"DSJ"
    },
    {
        "name":"Delhi Sarai Rohilla",
        "code":"DEE"
    },
    {
        "name":"Delhi Shahdara",
        "code":"DSA"
    },
    {
        "name":"Hazrat Nizamuddin",
        "code":"NZM"
    },
    {
        "name":"Mangolpuri",
        "code":"MGLP"
    },
    {
        "name":"Nangloi",
        "code":"NNO"
    },
    {
        "name":"Narela",
        "code":"NUR"
    },
    {
        "name":"New Delhi",
        "code":"NDLS"
    },
    {
        "name":"Okhla",
        "code":"OKA"
    },
    {
        "name":"Palam",
        "code":"PM"
    },
    {
        "name":"Shakurbasti",
        "code":"SSB"
    },
    {
        "name":"Shivaji Bridge",
        "code":"CSB"
    },
    {
        "name":"Subzi Mandi",
        "code":"SZM"
    },
    {
        "name":"Tilak Bridge",
        "code":"TKJ"
    },
    {
        "name":"Tuglakabad",
        "code":"TKD"
    },
    {
        "name":"Viveka Vihar",
        "code":"VVB"
    },
    {
        "name":"Aattur",
        "code":"ATU"
    },
    {
        "name":"Aduturai",
        "code":"ADT"
    },
    {
        "name":"Ambaturai",
        "code":"ABI"
    },
    {
        "name":"Ambur",
        "code":"AB"
    },
    {
        "name":"Anavardikhanpet",
        "code":"AVN"
    },
    {
        "name":"Arakkonam Junction",
        "code":"AJJ"
    },
    {
        "name":"Aralvaymozhi",
        "code":"AAY"
    },
    {
        "name":"Ariyalur",
        "code":"ALU"
    },
    {
        "name":"Arumuganeri",
        "code":"ANY"
    },
    {
        "name":"Avadi",
        "code":"AVD"
    },
    {
        "name":"Ayodhyapattanam",
        "code":"APN"
    },
    {
        "name":"Bommidi",
        "code":"BQI"
    },
    {
        "name":"Budalur",
        "code":"BAL"
    },
    {
        "name":"Buddireddippati",
        "code":"BDY"
    },
    {
        "name":"Chengalpattu",
        "code":"CGL"
    },
    {
        "name":"Chennai Central",
        "code":"MAS"
    },
    {
        "name":"Chennai Egmore",
        "code":"MS"
    },
    {
        "name":"Chettinad",
        "code":"CTND"
    },
    {
        "name":"Chidambaram",
        "code":"CDM"
    },
    {
        "name":"Chinna Salem",
        "code":"CHSM"
    },
    {
        "name":"Coimbatore Junction",
        "code":"CBE"
    },
    {
        "name":"Coimbatore North Junction",
        "code":"CBF"
    },
    {
        "name":"Cuddalore Port",
        "code":"CUPJ"
    },
    {
        "name":"Devakottai Road",
        "code":"DKO"
    },
    {
        "name":"Dharmapuri",
        "code":"DPJ"
    },
    {
        "name":"Dindigul Junction",
        "code":"DG"
    },
    {
        "name":"Eraniel",
        "code":"ERL"
    },
    {
        "name":"Erode Junction",
        "code":"ED"
    },
    {
        "name":"Ettapur Road",
        "code":"ETP"
    },
    {
        "name":"Gudiyattam",
        "code":"GYM"
    },
    {
        "name":"Gummidipundi",
        "code":"GPD"
    },
    {
        "name":"Hosur",
        "code":"HSRA"
    },
    {
        "name":"Almatti",
        "code":"LMT"
    },
    {
        "name":"Alnavar Junction",
        "code":"LWR"
    },
    {
        "name":"Ammasandra",
        "code":"AMSA"
    },
    {
        "name":"Anandapuram",
        "code":"ANF"
    },
    {
        "name":"Ankola",
        "code":"ANKL"
    },
    {
        "name":"Annigeri",
        "code":"NGR"
    },
    {
        "name":"Arsikere Junction",
        "code":"ASK"
    },
    {
        "name":"Badami",
        "code":"BDM"
    },
    {
        "name":"Bagalkot",
        "code":"BGK"
    },
    {
        "name":"Bagevadi Road",
        "code":"BSRX"
    },
    {
        "name":"Banaswadi",
        "code":"BAND"
    },
    {
        "name":"Bangalore Cantonment",
        "code":"BNC"
    }
];

exports.getStationCode=function(stationName){
    var stationID=-1;
    stations.forEach(function(value){
        if(value['name'].toUpperCase()==stationName.toUpperCase())
        {
            stationID=value['code'];
        }
    });
    return stationID;
};
<commit_msg>Added mote station names and corresponding codes in stations.js<commit_after>/**
 * Created by Snippy Valson on 21/7/16.
 */
var stations=[
    {
        "name":"Alappuzha",
        "code":"ALLP"
    },
    {
        "name":"Aluva",
        "code":"AWY"
    },
    {
        "name":"Angamaly",
        "code":"AFK"
    },
    {
        "name":"Badagara",
        "code":"BDJ"
    },
    {
        "name":"Bekal Fort",
        "code":"BFR"
    },
    {
        "name":"Calicut",
        "code":"CLT"
    },
    {
        "name":"Cannanore",
        "code":"CAN"
    },
    {
        "name":"Chalakudi",
        "code":"CKI"
    },
    {
        "name":"Changanacherry",
        "code":"CGY"
    },
    {
        "name":"Charvattur",
        "code":"CHV"
    },
    {
        "name":"Chengannur",
        "code":"CNGR"
    },
    {
        "name":"Chirayinkil",
        "code":"CRY"
    },
    {
        "name":"Dhanuvachapuram",
        "code":"DAVM"
    },
    {
        "name":"Divinenagar",
        "code":"DINR"
    },
    {
        "name":"Edappally",
        "code":"IPL"
    },
    {
        "name":"Ernakulam Junction",
        "code":"ERS"
    },
    {
        "name":"Ernakulam Town",
        "code":"ERN"
    },
    {
        "name":"Ettumanur",
        "code":"ETM"
    },
    {
        "name":"Ezhimala",
        "code":"ELM"
    },
    {
        "name":"Ferok",
        "code":"FK"
    },
    {
        "name":"Guruvayur",
        "code":"GUV"
    },
    {
        "name":"Haripad",
        "code":"HAD"
    },
    {
        "name":"Irinjalakuda",
        "code":"IJK"
    },
    {
        "name":"Kadakavur",
        "code":"KVU"
    },
    {
        "name":"Kadalundi",
        "code":"KN"
    },
    {
        "name":"Kanhangad",
        "code":"KZE"
    },
    {
        "name":"Kannapuram",
        "code":"KPQ"
    },
    {
        "name":"Karunagapalli",
        "code":"KPY"
    },
    {
        "name":"Kasaragod",
        "code":"KGQ"
    },
    {
        "name":"Kayamkulam",
        "code":"KYJ"
    },
    {
        "name":"Kazhakuttam",
        "code":"KZK"
    },
    {
        "name":"Kollam Junction",
        "code":"QLN"
    },
    {
        "name":"Kotikulam",
        "code":"KQK"
    },
    {
        "name":"Kottayam",
        "code":"KTYM"
    },
    {
        "name":"Koyilandy",
        "code":"QLD"
    },
    {
        "name":"Kumbala",
        "code":"KMQ"
    },
    {
        "name":"Kuttippuram",
        "code":"KTU"
    },
    {
        "name":"Manjeshwar",
        "code":"MJS"
    },
    {
        "name":"Mararikulam",
        "code":"MAKM"
    },
    {
        "name":"Mavelikara",
        "code":"MVLK"
    },
    {
        "name":"Mayyanad",
        "code":"MYY"
    },
    {
        "name":"Mulanturutti",
        "code":"MNTT"
    },
    {
        "name":"Munroturuttu",
        "code":"MQO"
    },
    {
        "name":"Murukkampuzha",
        "code":"MQU"
    },
    {
        "name":"Neyyattinkara",
        "code":"NYY"
    },
    {
        "name":"Nileshwar",
        "code":"NLE"
    },
    {
        "name":"Ottappalam",
        "code":"OTP"
    },
    {
        "name":"Palakkad Town",
        "code":"PGTN"
    },
    {
        "name":"Palghat",
        "code":"PGT"
    },
    {
        "name":"Parassala",
        "code":"PASA"
    },
    {
        "name":"Paravur",
        "code":"PVU"
    },
    {
        "name":"Parpanangadi",
        "code":"PGI"
    },
    {
        "name":"Pattambi",
        "code":"PTB"
    },
    {
        "name":"Payangadi",
        "code":"PAZ"
    },
    {
        "name":"Payyanur",
        "code":"PAY"
    },
    {
        "name":"Payyoli",
        "code":"PYOL"
    },
    {
        "name":"Piravam Road",
        "code":"PVRD"
    },
    {
        "name":"Pudukad",
        "code":"PUK"
    },
    {
        "name":"Punkunnam",
        "code":"PNQ"
    },
    {
        "name":"Sasthamkotta",
        "code":"STKT"
    },
    {
        "name":"Shertalai",
        "code":"SRTL"
    },
    {
        "name":"Shoranur",
        "code":"SRR"
    },
    {
        "name":"Tanur",
        "code":"TA"
    },
    {
        "name":"Tellicherry",
        "code":"TLY"
    },
    {
        "name":"Thiruvananthapuram Pettah",
        "code":"TVP"
    },
    {
        "name":"Tirunnavaya",
        "code":"TUA"
    },
    {
        "name":"Tirur",
        "code":"TIR"
    },
    {
        "name":"Tiruvalla",
        "code":"TRVL"
    },
    {
        "name":"Trichur",
        "code":"TCR"
    },
    {
        "name":"Trikarpur",
        "code":"TKQ"
    },
    {
        "name":"Tripunittura",
        "code":"TRTR"
    },
    {
        "name":"Trivandrum Central",
        "code":"TVC"
    },
    {
        "name":"Trivandrum Kochuveli",
        "code":"KCVL"
    },
    {
        "name":"Turavur",
        "code":"TUVR"
    },
    {
        "name":"Uppala",
        "code":"UAA"
    },
    {
        "name":"Vaikam Road",
        "code":"VARD"
    },
    {
        "name":"Valapattanam",
        "code":"VAPM"
    },
    {
        "name":"Vallikunnu",
        "code":"VLI"
    },
    {
        "name":"Varkala Sivagiri Station",
        "code":"VAK"
    },
    {
        "name":"Wadakanchery",
        "code":"WKI"
    },
    {
        "name":"Adarsh Nagar",
        "code":"ANDI"
    },
    {
        "name":"Anand Vihar",
        "code":"ANVR"
    },
    {
        "name":"Anand Vihar Terminus",
        "code":"ANVT"
    },
    {
        "name":"Badli",
        "code":"BHD"
    },
    {
        "name":"Bijwasan",
        "code":"BWSN"
    },
    {
        "name":"Delhi",
        "code":"DLI"
    },
    {
        "name":"Delhi Cantonment",
        "code":"DEC"
    },
    {
        "name":"Delhi Kishanganj",
        "code":"DKZ"
    },
    {
        "name":"Delhi Safdarjung",
        "code":"DSJ"
    },
    {
        "name":"Delhi Sarai Rohilla",
        "code":"DEE"
    },
    {
        "name":"Delhi Shahdara",
        "code":"DSA"
    },
    {
        "name":"Hazrat Nizamuddin",
        "code":"NZM"
    },
    {
        "name":"Mangolpuri",
        "code":"MGLP"
    },
    {
        "name":"Nangloi",
        "code":"NNO"
    },
    {
        "name":"Narela",
        "code":"NUR"
    },
    {
        "name":"New Delhi",
        "code":"NDLS"
    },
    {
        "name":"Okhla",
        "code":"OKA"
    },
    {
        "name":"Palam",
        "code":"PM"
    },
    {
        "name":"Shakurbasti",
        "code":"SSB"
    },
    {
        "name":"Shivaji Bridge",
        "code":"CSB"
    },
    {
        "name":"Subzi Mandi",
        "code":"SZM"
    },
    {
        "name":"Tilak Bridge",
        "code":"TKJ"
    },
    {
        "name":"Tuglakabad",
        "code":"TKD"
    },
    {
        "name":"Viveka Vihar",
        "code":"VVB"
    },
    {
        "name":"Aattur",
        "code":"ATU"
    },
    {
        "name":"Aduturai",
        "code":"ADT"
    },
    {
        "name":"Ambaturai",
        "code":"ABI"
    },
    {
        "name":"Ambur",
        "code":"AB"
    },
    {
        "name":"Anavardikhanpet",
        "code":"AVN"
    },
    {
        "name":"Arakkonam Junction",
        "code":"AJJ"
    },
    {
        "name":"Aralvaymozhi",
        "code":"AAY"
    },
    {
        "name":"Ariyalur",
        "code":"ALU"
    },
    {
        "name":"Arumuganeri",
        "code":"ANY"
    },
    {
        "name":"Avadi",
        "code":"AVD"
    },
    {
        "name":"Ayodhyapattanam",
        "code":"APN"
    },
    {
        "name":"Bommidi",
        "code":"BQI"
    },
    {
        "name":"Budalur",
        "code":"BAL"
    },
    {
        "name":"Buddireddippati",
        "code":"BDY"
    },
    {
        "name":"Chengalpattu",
        "code":"CGL"
    },
    {
        "name":"Chennai Central",
        "code":"MAS"
    },
    {
        "name":"Chennai Egmore",
        "code":"MS"
    },
    {
        "name":"Chettinad",
        "code":"CTND"
    },
    {
        "name":"Chidambaram",
        "code":"CDM"
    },
    {
        "name":"Chinna Salem",
        "code":"CHSM"
    },
    {
        "name":"Coimbatore Junction",
        "code":"CBE"
    },
    {
        "name":"Coimbatore North Junction",
        "code":"CBF"
    },
    {
        "name":"Cuddalore Port",
        "code":"CUPJ"
    },
    {
        "name":"Devakottai Road",
        "code":"DKO"
    },
    {
        "name":"Dharmapuri",
        "code":"DPJ"
    },
    {
        "name":"Dindigul Junction",
        "code":"DG"
    },
    {
        "name":"Eraniel",
        "code":"ERL"
    },
    {
        "name":"Erode Junction",
        "code":"ED"
    },
    {
        "name":"Ettapur Road",
        "code":"ETP"
    },
    {
        "name":"Gudiyattam",
        "code":"GYM"
    },
    {
        "name":"Gummidipundi",
        "code":"GPD"
    },
    {
        "name":"Hosur",
        "code":"HSRA"
    },
    {
        "name":"Almatti",
        "code":"LMT"
    },
    {
        "name":"Alnavar Junction",
        "code":"LWR"
    },
    {
        "name":"Ammasandra",
        "code":"AMSA"
    },
    {
        "name":"Anandapuram",
        "code":"ANF"
    },
    {
        "name":"Ankola",
        "code":"ANKL"
    },
    {
        "name":"Annigeri",
        "code":"NGR"
    },
    {
        "name":"Arsikere Junction",
        "code":"ASK"
    },
    {
        "name":"Badami",
        "code":"BDM"
    },
    {
        "name":"Bagalkot",
        "code":"BGK"
    },
    {
        "name":"Bagevadi Road",
        "code":"BSRX"
    },
    {
        "name":"Banaswadi",
        "code":"BAND"
    },
    {
        "name":"Bangalore Cantonment",
        "code":"BNC"
    },
    {
        "name":"Bangalore City Junction",
        "code":"SBC"
    },
    {
        "name":"Bangalore East",
        "code":"BNCE"
    },
    {
        "name":"Bangarapet",
        "code":"BWT"
    },
    {
        "name":"Bantawala",
        "code":"BNTL"
    },
    {
        "name":"Barkur",
        "code":"BKJ"
    },
    {
        "name":"Belgaum",
        "code":"BGM"
    },
    {
        "name":"Bellary Junction",
        "code":"BAY"
    },
    {
        "name":"Bhadravati",
        "code":"BDVT"
    },
    {
        "name":"Bhalki",
        "code":"BHLK"
    },
    {
        "name":"Bhanapur",
        "code":"BNP"
    },
    {
        "name":"Bidadi",
        "code":"BID"
    },
    {
        "name":"Bidar",
        "code":"BIDR"
    },
    {
        "name":"Bijapur",
        "code":"BJP"
    },
    {
        "name":"Bijoor",
        "code":"BIJR"
    },
    {
        "name":"Birur Junction",
        "code":"RRB"
    },
    {
        "name":"Byadgi",
        "code":"BYD"
    },
    {
        "name":"Byndoor",
        "code":"BYNR"
    },
    {
        "name":"Adavali",
        "code":"ADVI"
    },
    {
        "name":"Ahmednagar",
        "code":"ANG"
    },
    {
        "name":"Ajni",
        "code":"AJNI"
    },
    {
        "name":"Akkalkot Road",
        "code":"AKOR"
    },
    {
        "name":"Akola Junction",
        "code":"AK"
    },
    {
        "name":"Amalner",
        "code":"AN"
    },
    {
        "name":"Ambale",
        "code":"ABLE"
    },
    {
        "name":"Amgaon",
        "code":"AGN"
    },
    {
        "name":"Amravati",
        "code":"AMI"
    },
    {
        "name":"Andheri",
        "code":"ADH"
    },
    {
        "name":"Ankai",
        "code":"ANK"
    },
    {
        "name":"Aravalli Road",
        "code":"AVRD"
    },
    {
        "name":"Aurangabad",
        "code":"AWB"
    },
    {
        "name":"Badnapur",
        "code":"BDU"
    },
    {
        "name":"Badnera Junction",
        "code":"BD"
    },
    {
        "name":"Balharshah",
        "code":"BPQ"
    },
    {
        "name":"Bandra Terminus",
        "code":"BDTS"
    },
    {
        "name":"Barsi Town",
        "code":"BTW"
    },
    {
        "name":"Basmat",
        "code":"BMF"
    },
    {
        "name":"Belapur",
        "code":"BAP"
    },
    {
        "name":"Bhandak",
        "code":"BUX"
    },
    {
        "name":"Bhandara Road",
        "code":"BRD"
    },
    {
        "name":"Bhavani Nagar",
        "code":"BVNR"
    },
    {
        "name":"Bhigwan",
        "code":"BGVN"
    },
    {
        "name":"",
        "code":""
    }
];

exports.getStationCode=function(stationName){
    var stationID=-1;
    stations.forEach(function(value){
        if(value['name'].toUpperCase()==stationName.toUpperCase())
        {
            stationID=value['code'];
        }
    });
    return stationID;
};
<|endoftext|>


<commit_before>'use strict';
TG.Engines.Game = (function (that) {
    var state = {
        score: 0,
        lives: 3,
        chain: {
            chaining: false,
            Pos: {},
            Tick: 0,
            Count: 0
        },
        ticks: 0,
        difficulty: 1,
        projectiles: 0
    },
    chainDistanceInTicks = function () {
        return 40 / state.difficulty;
    },
    enemiesInChain = 10,
    difficultyTick = 5000,
    totalProjectileCount = 2;

    $(function () {
        TG.Engines.GlobalVars._STEPTIMER = setInterval(TG.Engines.Game.Tick, 16);
    });

    // Returns a random position.
    function _getRndPos() {
        var areaSize = TG.Engines.Render.getPlayAreaSize();

        return new TG.Objects.Position(Math.floor(Math.random() * areaSize.width), Math.floor(Math.random() * areaSize.height));
    };

    function _getRndNum(max) {
        return Math.floor(Math.random() * max);
    };

    that.Tick = function () {
        var i = 0;
        state.ticks++;

        if (that.Player().getState().Combat.HP <= 0) {
            state.lives--;

            if (state.lives <= 0) {
                // Game Over
                resetGame();
            } else {
                // Death
                resetLevel();
            }
        }

        if (state.ticks >= difficultyTick) {
            state.ticks = 0;
            state.difficulty++;
        }

        for (i = 0; i < BackgroundObjects.length; i++) {
            (function (i) {
                BackgroundObjects[i].Tick();
            })(i);
        }

        var deleteIds = [];

        for (var i = 0; i < GameObjects.length; i++) {
            (function (i) {
                GameObjects[i]
                    .Tick();

                if (i!=0 && GameObjects[i].getDelete && GameObjects[i].getDelete()) {
                    // if an object gives a score on destruction then set the score.
                    if (GameObjects[i].getScore) {
                        state.score += GameObjects[i].getScore();
                    }

                    // if the object is a projectile then reduce the number of projectiles on the screen.
                    if (GameObjects[i] instanceof TG.Objects.Projectile) {
                        state.projectiles--;
                    }

                    // mark the id to be deleted
                    deleteIds.push(i);
                }
            })(i);
        }

        var deleteCount = 0;
        for (var d = 0; d < deleteIds.length; d++) {
            GameObjects.splice(deleteIds[d] - deleteCount, 1);
            deleteCount++;
        }

        GenerateNewObjects();
    };

    function resetGame() {
        state.score = 0;
        state.lives = 3;

        resetLevel();
    }

    function resetLevel() {
        state.chain = {
            chaining: false,
            Pos: {},
            Tick: 0,
            Count: 0
        };
        state.ticks = 0;
        state.difficulty = 1;
        state.projectiles = 0;

        GameObjects = [];

        GameObjects[0] = TG.Engines.Generate.Player('Player', { x: 100, y: 100 });
    }

    function GenerateNewObjects() {
        var areaSize = TG.Engines.Render.getPlayAreaSize();

        // Generate Background Objects
        if (_getRndNum(1) == 0) {
            var starSpeed = (_getRndNum(100) / 100) * -20;
            if(starSpeed < -1) {
                BackgroundObjects.push(
                    new TG.Objects.Actor(
                        'star',
                        new TG.Objects.Position(areaSize.width - 5, _getRndPos().y),
                        { horizontal: starSpeed, vertical: 0 },
                        TG.Engines.Animation.Star
                    )
                );
            }
        }

        // Generate Enemy Objects
        if (!state.chain.chaining) {
            state.chain.chaining = (_getRndNum((500 / state.difficulty)) == 0);
        } else {
            if (!state.chain.Pos.y) {
                state.chain.Pos.y = _getRndPos().y;
            }

            if (state.chain.Tick == 0) {
                state.chain.Count++;
                var npc = TG.Engines.Generate.NPC(GameObjects.length, { x: areaSize.width - 5, y: state.chain.Pos.y }, state.difficulty);
                GameObjects.push(npc);
            }

            state.chain.Tick++;

            if (state.chain.Tick > chainDistanceInTicks()) {
                state.chain.Tick = 0;
            }
            if (state.chain.Count >= enemiesInChain) {
                state.chain.Count = 0;
                state.chain.chaining = false;
                state.chain.Pos = {};
            }
        }
    }

    that.Player = function () {
        return GameObjects[0];
    }

    that.CurrentState = function () {
        return {
            GameObjects: GameObjects || [],
            BackgroundObjects: BackgroundObjects || []
        };
    }

    that.AddObject = function (o) {
        GameObjects.push(o);
    }

    that.Distance = {
        Between: function (o1, o2) {
            o2 = o2 || GameObjects[0];
            var p1 = o1.getPosition();
            var p2 = o2.getPosition();

            return that.Distance.BetweenPos(p1, p2);
        },
        BetweenPos: function (p1, p2) {
            var a, b;
            a = Math.abs(p1.x - p2.x);
            b = Math.abs(p1.y - p2.y);

            return Math.sqrt((a * a) + (b * b));
        },
        BetweenforCompare: function (o1, o2) {
            o2 = o2 || GameObjects[0];
            var p1 = o1.getPosition();
            var p2 = o2.getPosition();

            var a, b;
            a = Math.abs(p1.x - p2.x);
            b = Math.abs(p1.y - p2.y);

            return (a * a) + (b * b);
        },
        Closest: function (o1, propertyFilter, action, propertyEquals) {
            var rtnObject = { title: 'none' };
            var shortestDistance = 1000000;

            for (var i = 0; i < GameObjects.length; i++) {
                var thisDistance = that.Distance.BetweenforCompare(o1, GameObjects[i]);
                if (o1 != GameObjects[i] && GameObjects[i].getProperties(propertyFilter, propertyEquals) && thisDistance < shortestDistance) {
                    if (action) action(GameObjects[i]);
                    shortestDistance = thisDistance;
                    rtnObject = GameObjects[i];
                }
            }

            return rtnObject;
        },
        Within: function (o1, distance, action) {
            var rtnArray = new Array();

            for (var i = 0; i < GameObjects.length; i++) {
                var thisDistance = that.Distance.Between(o1, GameObjects[i]);
                if (thisDistance < distance && o1 != GameObjects[i]) {
                    if (action) action(GameObjects[i]);
                    rtnArray.push(GameObjects[i]);
                }
            }

            return rtnArray;
        }
    };

    var GameObjects = [];
    var BackgroundObjects = [];

    resetGame();

    /*-- Register Keys --*/
    (function (i) {
        // enable keyboard but no other input method.
        i.Init({
            keyboard: true
        });

        // Up - E
        i.AddKey('Up', '69', function () {
            GameObjects[0].setMoving({ vertical: -3 });
        }, function () {
            GameObjects[0].setMoving({ vertical: 0 });
        });

        // Down - D
        i.AddKey('Down', '68', function () {
            GameObjects[0].setMoving({ vertical: 3 });
        }, function () {
            GameObjects[0].setMoving({ vertical: 0 });
        });

        // Right - F
        //TG.Engines.Input.AddKey('70', function () {
        //    GameObjects[0].setMoving({ horizontal: 1 });
        //}, function () {
        //    GameObjects[0].setMoving({ horizontal: 0 });
        //});

        // Left - S
        //TG.Engines.Input.AddKey('83', function () {
        //    GameObjects[0].setMoving({ horizontal: -1 });
        //}, function () {
        //    GameObjects[0].setMoving({ horizontal: 0 });
        //});

        // Attack - Space
        i.AddKey('Attack', '32', function () {
            if (state.projectiles <= totalProjectileCount) {
                state.projectiles++;

                var pos = TG.Engines.Game.Player().getPosition();

                pos = new TG.Objects.Position(pos.x, pos.y);

                GameObjects.push(new TG.Objects.Projectile('Arrow', pos, { horizontal: 1, vertical: 0 }, 20, 1000, 50, that.Player()));
            }
        }, function () {

        });

        // Interact - R
        i.AddKey('Interact', '84', function () {
            TG.Engines.Game.Player().Interact.Perform();
        }, function () {

        });

        // PanRight - right
        i.AddKey('PanRight', '39', function () {
            TG.Engines.Render.MovePanLocation({ x: 20, y: 0 });
        }, function () {

        });
        // PanLeft - left
        i.AddKey('PanLeft', '37', function () {
            TG.Engines.Render.MovePanLocation({ x: -20, y: 0 });
        }, function () {

        });
        // PanDown - down
        i.AddKey('PanDown', '40', function () {
            TG.Engines.Render.MovePanLocation({ x: 0, y: 20 });
        }, function () {

        });
        // PanUp - up
        i.AddKey('PanUp', '38', function () {
            TG.Engines.Render.MovePanLocation({ x: 0, y: -20 });
        }, function () {

        });

        // Test - G
        i.AddKey('Test', '71', function () {
            TG.Test.Perform();
        }, function () {

        });

    }(TG.Engines.Input));

    /*-- Initialize Render Engine --*/
    (function (er, or) {
        // Initialize the Render Engine.
        er.Init([
            new or.Layer(function () { return BackgroundObjects || []; }, true),
            new or.Layer(function () { return GameObjects || []; }, false)
        ], [
            new or.Text(function () { return 'Score: ' + state.score; }, new TG.Objects.Position(50, 30)),
            new or.Text(function () { return 'Lives: ' + state.lives; }, new TG.Objects.Position(50, 50)),
            new or.Text(function () { return 'Health: ' + that.Player().getState().Combat.HP }, new TG.Objects.Position(50, 70)),
            new or.Text(function () { return 'Debug: ' + TG.Engines.Debug.debugString; }, new TG.Objects.Position(50, 90)),
        ]);
    }(TG.Engines.Render, TG.Objects.Render));

    return that;
})(TG.Engines.Game || {});
<commit_msg>start at a higher difficulty<commit_after>'use strict';
TG.Engines.Game = (function (that) {
    var state = {
        score: 0,
        lives: 3,
        chain: {
            chaining: false,
            Pos: {},
            Tick: 0,
            Count: 0
        },
        ticks: 0,
        difficulty: 1,
        projectiles: 0
    },
    chainDistanceInTicks = function () {
        return 40 / state.difficulty;
    },
    enemiesInChain = 10,
    difficultyTick = 5000,
    totalProjectileCount = 2;

    $(function () {
        TG.Engines.GlobalVars._STEPTIMER = setInterval(TG.Engines.Game.Tick, 16);
    });

    // Returns a random position.
    function _getRndPos() {
        var areaSize = TG.Engines.Render.getPlayAreaSize();

        return new TG.Objects.Position(Math.floor(Math.random() * areaSize.width), Math.floor(Math.random() * areaSize.height));
    };

    function _getRndNum(max) {
        return Math.floor(Math.random() * max);
    };

    that.Tick = function () {
        var i = 0;
        state.ticks++;

        if (that.Player().getState().Combat.HP <= 0) {
            state.lives--;

            if (state.lives <= 0) {
                // Game Over
                resetGame();
            } else {
                // Death
                resetLevel();
            }
        }

        if (state.ticks >= difficultyTick) {
            state.ticks = 0;
            state.difficulty++;
        }

        for (i = 0; i < BackgroundObjects.length; i++) {
            (function (i) {
                BackgroundObjects[i].Tick();
            })(i);
        }

        var deleteIds = [];

        for (var i = 0; i < GameObjects.length; i++) {
            (function (i) {
                GameObjects[i]
                    .Tick();

                if (i!=0 && GameObjects[i].getDelete && GameObjects[i].getDelete()) {
                    // if an object gives a score on destruction then set the score.
                    if (GameObjects[i].getScore) {
                        state.score += GameObjects[i].getScore();
                    }

                    // if the object is a projectile then reduce the number of projectiles on the screen.
                    if (GameObjects[i] instanceof TG.Objects.Projectile) {
                        state.projectiles--;
                    }

                    // mark the id to be deleted
                    deleteIds.push(i);
                }
            })(i);
        }

        var deleteCount = 0;
        for (var d = 0; d < deleteIds.length; d++) {
            GameObjects.splice(deleteIds[d] - deleteCount, 1);
            deleteCount++;
        }

        GenerateNewObjects();
    };

    function resetGame() {
        state.score = 0;
        state.lives = 3;

        resetLevel();
    }

    function resetLevel() {
        state.chain = {
            chaining: false,
            Pos: {},
            Tick: 0,
            Count: 0
        };
        state.ticks = 0;
        state.difficulty = 4;
        state.projectiles = 0;

        GameObjects = [];

        GameObjects[0] = TG.Engines.Generate.Player('Player', { x: 100, y: 100 });
    }

    function GenerateNewObjects() {
        var areaSize = TG.Engines.Render.getPlayAreaSize();

        // Generate Background Objects
        if (_getRndNum(1) == 0) {
            var starSpeed = (_getRndNum(100) / 100) * -20;
            if(starSpeed < -1) {
                BackgroundObjects.push(
                    new TG.Objects.Actor(
                        'star',
                        new TG.Objects.Position(areaSize.width - 5, _getRndPos().y),
                        { horizontal: starSpeed, vertical: 0 },
                        TG.Engines.Animation.Star
                    )
                );
            }
        }

        // Generate Enemy Objects
        if (!state.chain.chaining) {
            state.chain.chaining = (_getRndNum((500 / state.difficulty)) == 0);
        } else {
            if (!state.chain.Pos.y) {
                state.chain.Pos.y = _getRndPos().y;
            }

            if (state.chain.Tick == 0) {
                state.chain.Count++;
                var npc = TG.Engines.Generate.NPC(GameObjects.length, { x: areaSize.width - 5, y: state.chain.Pos.y }, state.difficulty);
                GameObjects.push(npc);
            }

            state.chain.Tick++;

            if (state.chain.Tick > chainDistanceInTicks()) {
                state.chain.Tick = 0;
            }
            if (state.chain.Count >= enemiesInChain) {
                state.chain.Count = 0;
                state.chain.chaining = false;
                state.chain.Pos = {};
            }
        }
    }

    that.Player = function () {
        return GameObjects[0];
    }

    that.CurrentState = function () {
        return {
            GameObjects: GameObjects || [],
            BackgroundObjects: BackgroundObjects || []
        };
    }

    that.AddObject = function (o) {
        GameObjects.push(o);
    }

    that.Distance = {
        Between: function (o1, o2) {
            o2 = o2 || GameObjects[0];
            var p1 = o1.getPosition();
            var p2 = o2.getPosition();

            return that.Distance.BetweenPos(p1, p2);
        },
        BetweenPos: function (p1, p2) {
            var a, b;
            a = Math.abs(p1.x - p2.x);
            b = Math.abs(p1.y - p2.y);

            return Math.sqrt((a * a) + (b * b));
        },
        BetweenforCompare: function (o1, o2) {
            o2 = o2 || GameObjects[0];
            var p1 = o1.getPosition();
            var p2 = o2.getPosition();

            var a, b;
            a = Math.abs(p1.x - p2.x);
            b = Math.abs(p1.y - p2.y);

            return (a * a) + (b * b);
        },
        Closest: function (o1, propertyFilter, action, propertyEquals) {
            var rtnObject = { title: 'none' };
            var shortestDistance = 1000000;

            for (var i = 0; i < GameObjects.length; i++) {
                var thisDistance = that.Distance.BetweenforCompare(o1, GameObjects[i]);
                if (o1 != GameObjects[i] && GameObjects[i].getProperties(propertyFilter, propertyEquals) && thisDistance < shortestDistance) {
                    if (action) action(GameObjects[i]);
                    shortestDistance = thisDistance;
                    rtnObject = GameObjects[i];
                }
            }

            return rtnObject;
        },
        Within: function (o1, distance, action) {
            var rtnArray = new Array();

            for (var i = 0; i < GameObjects.length; i++) {
                var thisDistance = that.Distance.Between(o1, GameObjects[i]);
                if (thisDistance < distance && o1 != GameObjects[i]) {
                    if (action) action(GameObjects[i]);
                    rtnArray.push(GameObjects[i]);
                }
            }

            return rtnArray;
        }
    };

    var GameObjects = [];
    var BackgroundObjects = [];

    resetGame();

    /*-- Register Keys --*/
    (function (i) {
        // enable keyboard but no other input method.
        i.Init({
            keyboard: true
        });

        // Up - E
        i.AddKey('Up', '69', function () {
            GameObjects[0].setMoving({ vertical: -3 });
        }, function () {
            GameObjects[0].setMoving({ vertical: 0 });
        });

        // Down - D
        i.AddKey('Down', '68', function () {
            GameObjects[0].setMoving({ vertical: 3 });
        }, function () {
            GameObjects[0].setMoving({ vertical: 0 });
        });

        // Right - F
        //TG.Engines.Input.AddKey('70', function () {
        //    GameObjects[0].setMoving({ horizontal: 1 });
        //}, function () {
        //    GameObjects[0].setMoving({ horizontal: 0 });
        //});

        // Left - S
        //TG.Engines.Input.AddKey('83', function () {
        //    GameObjects[0].setMoving({ horizontal: -1 });
        //}, function () {
        //    GameObjects[0].setMoving({ horizontal: 0 });
        //});

        // Attack - Space
        i.AddKey('Attack', '32', function () {
            if (state.projectiles <= totalProjectileCount) {
                state.projectiles++;

                var pos = TG.Engines.Game.Player().getPosition();

                pos = new TG.Objects.Position(pos.x, pos.y);

                GameObjects.push(new TG.Objects.Projectile('Arrow', pos, { horizontal: 1, vertical: 0 }, 20, 1000, 50, that.Player()));
            }
        }, function () {

        });

        // Interact - R
        i.AddKey('Interact', '84', function () {
            TG.Engines.Game.Player().Interact.Perform();
        }, function () {

        });

        // PanRight - right
        i.AddKey('PanRight', '39', function () {
            TG.Engines.Render.MovePanLocation({ x: 20, y: 0 });
        }, function () {

        });
        // PanLeft - left
        i.AddKey('PanLeft', '37', function () {
            TG.Engines.Render.MovePanLocation({ x: -20, y: 0 });
        }, function () {

        });
        // PanDown - down
        i.AddKey('PanDown', '40', function () {
            TG.Engines.Render.MovePanLocation({ x: 0, y: 20 });
        }, function () {

        });
        // PanUp - up
        i.AddKey('PanUp', '38', function () {
            TG.Engines.Render.MovePanLocation({ x: 0, y: -20 });
        }, function () {

        });

        // Test - G
        i.AddKey('Test', '71', function () {
            TG.Test.Perform();
        }, function () {

        });

    }(TG.Engines.Input));

    /*-- Initialize Render Engine --*/
    (function (er, or) {
        // Initialize the Render Engine.
        er.Init([
            new or.Layer(function () { return BackgroundObjects || []; }, true),
            new or.Layer(function () { return GameObjects || []; }, false)
        ], [
            new or.Text(function () { return 'Score: ' + state.score; }, new TG.Objects.Position(50, 30)),
            new or.Text(function () { return 'Lives: ' + state.lives; }, new TG.Objects.Position(50, 50)),
            new or.Text(function () { return 'Health: ' + that.Player().getState().Combat.HP }, new TG.Objects.Position(50, 70)),
            new or.Text(function () { return 'Debug: ' + TG.Engines.Debug.debugString; }, new TG.Objects.Position(50, 90)),
        ]);
    }(TG.Engines.Render, TG.Objects.Render));

    return that;
})(TG.Engines.Game || {});
<|endoftext|>


<commit_before>import Tessera from 'tessera';
import Utils from 'utils';

class Tesserae {

	constructor ({
		// container selector
		container,
		// tessera width
		tesseraWidth = 30,
		// tessera height
		tesseraHeight = 30,
		// randomcolor lib options
		randomcolor = {
			hue: 'monochrome',
			luminosity: 'light'
		},
		// filter: false or object
		filter = {
			color: '#000',
			opacity: 0.6
		},
		// gradual: false or object
		gradual = false,
		// animate: false or object
		animate = false
	}) {

		// container is the only required parameter
		if (!container) {
			throw 'Tesserae Error: container option is missing.';
		}

		// properties
		this.containerEl = document.querySelector(container);

		// make sure container selector gives an existing dom element
		if (!this.containerEl) {
			throw `Tesserae Error: no container element found: ${container}`;
		}

		this.tesseraWidth = parseInt(tesseraWidth, 10);
		this.tesseraHeight = parseInt(tesseraHeight, 10);
		this.randomcolor = randomcolor;
		this.filter = filter;
		this.gradual = gradual;
		this.animate = animate;
		this.containerStyle = window.getComputedStyle(this.containerEl, null);

		// all drawn tessera shapes are stored here
		this.tesserae = [];

		// render version
		// NOTE: this is used to avoid issues with re-renders
		// while current animation has not finished yet
		this.renderVersion = 0;

		// init
		this.init();
	}

	init () {
		// lazy draw function (debounced)
		this.lazyDraw = Utils.debounce(this.draw, 200).bind(this);
		window.addEventListener('resize', this.lazyDraw);
		// draw for the first time
		this.draw();
	}

	destroy () {
		this._emptyContainer();
		this._restoreContainer();
		this.tesserae.length = 0;
		window.removeEventListener('resize', this.lazyDraw);
	}

	draw () {
		this.renderVersion++;

		this._editContainer();
		this._prepareCanvas();
		this._generateTesserae();
		this._addFilter();

		// gradually show tesserae in random order
		if (this.gradual && this.gradual.enable) {
			const clone = Utils.cloneArrayShallow(this.tesserae);
			Utils.shuffle(clone);
			this._drawTesseraeGradually(clone, 0, this.gradual.step || 1, this.renderVersion);
		}
		// show all tesserae at once
		else {
			this._drawTesserae(this.tesserae);
		}
	}

	_editContainer () {
		// if parent has a non-static position, make it relative
		if (this.containerStyle.getPropertyValue('position') === 'static') {
			this.containerEl.style.position = 'relative';
		}
		this.containerEl.style.boxSizing = 'border-box';
	}

	_restoreContainer () {
		// TODO: restore original position & box-sizing of container
	}

	_addFilter () {
		if (!this.filter || this.filterEl) {
			return;
		}

		// prepare element
		let filterEl = this.filterEl = document.createElement('div');
		filterEl.style.width = '100%';
		filterEl.style.height = '100%';
		filterEl.style.backgroundColor = this.filter.color;
		filterEl.style.opacity = this.filter.opacity;
		filterEl.style.position = 'absolute';
		filterEl.style.zIndex = 1;
		filterEl.style.top = 0;

		this.containerEl.appendChild(filterEl);
	}

	_prepareCanvas () {
		let cs = this.containerStyle;

		let elementHeight = this.containerEl.clientHeight;  // height with padding
		let elementWidth = this.containerEl.clientWidth;   // width with padding

		elementHeight -= parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
		elementWidth -= parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);

		// canvas exists
		if (this.ctx && this.canvas) {
			this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
		}
		// canvas not created yet
		else {
			// create new canvas
			this.canvas = document.createElement('canvas');
			this.canvas.id = 'tesserae';
			this._emptyContainer();
			this.containerEl.appendChild(this.canvas);
			this.ctx = this.canvas.getContext('2d');
		}

		// set canvas width in any case
		this.canvas.width = elementWidth;
		this.canvas.height = elementHeight;
	}

	_generateTesserae () {
		let xMod = this.canvas.offsetWidth % this.tesseraWidth;
		let yMod = this.canvas.offsetHeight % this.tesseraHeight;

		let fullCols = Math.floor(this.canvas.offsetWidth / this.tesseraWidth);
		let allCols = xMod > 0 ? fullCols + 2 : fullCols;

		let fullRows = Math.floor(this.canvas.offsetHeight / this.tesseraHeight);
		let allRows = yMod > 0 ? fullRows + 2 : fullRows;

		// empty tesserae array
		this.tesserae.length = 0;

		let posY = 0;

		for (let r = 0; r < allRows; r++) {
			let posX = 0;
			let actualHeight = this.tesseraHeight;
			if (r === 0 && yMod > 0) {
				actualHeight = Math.floor(yMod / 2);
			}
			if (r === allRows - 1 && yMod > 0) {
				actualHeight = Math.ceil(yMod / 2);
			}

			for (let c = 0; c < allCols; c++) {
				let actualWidth = this.tesseraWidth;
				if (c === 0 && xMod > 0) {
					actualWidth = Math.floor(xMod / 2);
				}
				if (c === allCols - 1 && xMod > 0) {
					actualWidth = Math.ceil(xMod / 2);
				}
				let tessera = new Tessera({
					x: posX,
					y: posY,
					width: actualWidth,
					height: actualHeight,
					hslArray: Utils.getRandomColor(this.randomcolor, 'hslArray')
				});
				this.tesserae.push(tessera);
				posX = posX + actualWidth;
			}
			posY = posY + actualHeight;
		}
	}

	_drawTesserae (tesserae) {
		for (let i = 0, len = tesserae.length; i < len; i++) {
			tesserae[i].draw(this.ctx, this.animate);
		}
	}

	_drawTesseraeGradually (tesserae, i, step, renderVersion) {
		if (i in tesserae) {
			let s = step;
			while (s-- > 0 && tesserae[i]) {
				tesserae[i++].draw(this.ctx, this.animate);
			}
			requestAnimationFrame(() => {
				if (renderVersion === this.renderVersion) {
					this._drawTesseraeGradually(tesserae, i, step, renderVersion);
				}
			});
		}
	}

	_emptyContainer () {
		let el = this.containerEl;
		while (el.firstChild) {
		    el.removeChild(el.firstChild);
		}
	}

	_getRandomTessera () {
		return this.tesserae[Utils.getRandomInt(0, this.tesserae.length)];
	}
}

export default Tesserae;
<commit_msg>Changed some more defaults<commit_after>import Tessera from 'tessera';
import Utils from 'utils';

class Tesserae {

	constructor ({
		// container selector
		container,
		// tessera width
		tesseraWidth = 30,
		// tessera height
		tesseraHeight = 30,
		// randomcolor lib options
		randomcolor = {
			hue: 'monochrome',
			luminosity: 'light'
		},
		// filter: false or object
		filter = {
			color: '#000',
			opacity: 0.6
		},
		// gradual: false or object
		gradual = {
			enable: true,
			step: 10
		},
		// animate: false or object
		animate = {
			enable: true,
			step: 2
		}
	}) {

		// container is the only required parameter
		if (!container) {
			throw 'Tesserae Error: container option is missing.';
		}

		// properties
		this.containerEl = document.querySelector(container);

		// make sure container selector gives an existing dom element
		if (!this.containerEl) {
			throw `Tesserae Error: no container element found: ${container}`;
		}

		this.tesseraWidth = parseInt(tesseraWidth, 10);
		this.tesseraHeight = parseInt(tesseraHeight, 10);
		this.randomcolor = randomcolor;
		this.filter = filter;
		this.gradual = gradual;
		this.animate = animate;
		this.containerStyle = window.getComputedStyle(this.containerEl, null);

		// all drawn tessera shapes are stored here
		this.tesserae = [];

		// render version
		// NOTE: this is used to avoid issues with re-renders
		// while current animation has not finished yet
		this.renderVersion = 0;

		// init
		this.init();
	}

	init () {
		// lazy draw function (debounced)
		this.lazyDraw = Utils.debounce(this.draw, 200).bind(this);
		window.addEventListener('resize', this.lazyDraw);
		// draw for the first time
		this.draw();
	}

	destroy () {
		this._emptyContainer();
		this._restoreContainer();
		this.tesserae.length = 0;
		window.removeEventListener('resize', this.lazyDraw);
	}

	draw () {
		this.renderVersion++;

		this._editContainer();
		this._prepareCanvas();
		this._generateTesserae();
		this._addFilter();

		// gradually show tesserae in random order
		if (this.gradual && this.gradual.enable) {
			const clone = Utils.cloneArrayShallow(this.tesserae);
			Utils.shuffle(clone);
			this._drawTesseraeGradually(clone, 0, this.gradual.step || 1, this.renderVersion);
		}
		// show all tesserae at once
		else {
			this._drawTesserae(this.tesserae);
		}
	}

	_editContainer () {
		// if parent has a non-static position, make it relative
		if (this.containerStyle.getPropertyValue('position') === 'static') {
			this.containerEl.style.position = 'relative';
		}
		this.containerEl.style.boxSizing = 'border-box';
	}

	_restoreContainer () {
		// TODO: restore original position & box-sizing of container
	}

	_addFilter () {
		if (!this.filter || this.filterEl) {
			return;
		}

		// prepare element
		let filterEl = this.filterEl = document.createElement('div');
		filterEl.style.width = '100%';
		filterEl.style.height = '100%';
		filterEl.style.backgroundColor = this.filter.color;
		filterEl.style.opacity = this.filter.opacity;
		filterEl.style.position = 'absolute';
		filterEl.style.zIndex = 1;
		filterEl.style.top = 0;

		this.containerEl.appendChild(filterEl);
	}

	_prepareCanvas () {
		let cs = this.containerStyle;

		let elementHeight = this.containerEl.clientHeight;  // height with padding
		let elementWidth = this.containerEl.clientWidth;   // width with padding

		elementHeight -= parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
		elementWidth -= parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);

		// canvas exists
		if (this.ctx && this.canvas) {
			this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
		}
		// canvas not created yet
		else {
			// create new canvas
			this.canvas = document.createElement('canvas');
			this.canvas.id = 'tesserae';
			this._emptyContainer();
			this.containerEl.appendChild(this.canvas);
			this.ctx = this.canvas.getContext('2d');
		}

		// set canvas width in any case
		this.canvas.width = elementWidth;
		this.canvas.height = elementHeight;
	}

	_generateTesserae () {
		let xMod = this.canvas.offsetWidth % this.tesseraWidth;
		let yMod = this.canvas.offsetHeight % this.tesseraHeight;

		let fullCols = Math.floor(this.canvas.offsetWidth / this.tesseraWidth);
		let allCols = xMod > 0 ? fullCols + 2 : fullCols;

		let fullRows = Math.floor(this.canvas.offsetHeight / this.tesseraHeight);
		let allRows = yMod > 0 ? fullRows + 2 : fullRows;

		// empty tesserae array
		this.tesserae.length = 0;

		let posY = 0;

		for (let r = 0; r < allRows; r++) {
			let posX = 0;
			let actualHeight = this.tesseraHeight;
			if (r === 0 && yMod > 0) {
				actualHeight = Math.floor(yMod / 2);
			}
			if (r === allRows - 1 && yMod > 0) {
				actualHeight = Math.ceil(yMod / 2);
			}

			for (let c = 0; c < allCols; c++) {
				let actualWidth = this.tesseraWidth;
				if (c === 0 && xMod > 0) {
					actualWidth = Math.floor(xMod / 2);
				}
				if (c === allCols - 1 && xMod > 0) {
					actualWidth = Math.ceil(xMod / 2);
				}
				let tessera = new Tessera({
					x: posX,
					y: posY,
					width: actualWidth,
					height: actualHeight,
					hslArray: Utils.getRandomColor(this.randomcolor, 'hslArray')
				});
				this.tesserae.push(tessera);
				posX = posX + actualWidth;
			}
			posY = posY + actualHeight;
		}
	}

	_drawTesserae (tesserae) {
		for (let i = 0, len = tesserae.length; i < len; i++) {
			tesserae[i].draw(this.ctx, this.animate);
		}
	}

	_drawTesseraeGradually (tesserae, i, step, renderVersion) {
		if (i in tesserae) {
			let s = step;
			while (s-- > 0 && tesserae[i]) {
				tesserae[i++].draw(this.ctx, this.animate);
			}
			requestAnimationFrame(() => {
				if (renderVersion === this.renderVersion) {
					this._drawTesseraeGradually(tesserae, i, step, renderVersion);
				}
			});
		}
	}

	_emptyContainer () {
		let el = this.containerEl;
		while (el.firstChild) {
		    el.removeChild(el.firstChild);
		}
	}

	_getRandomTessera () {
		return this.tesserae[Utils.getRandomInt(0, this.tesserae.length)];
	}
}

export default Tesserae;
<|endoftext|>


<commit_before>/*
	Copyright 2010-2011 Vodafone Group Services GmbH

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

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

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

	configXmlDependent:{
		applies:!!window.Widget,
		files:[
			// Those are the tests that depend on a certain setup in the config.xml
			// so they normally can not be run form the all.html.
			"tests/jil/config.xml/jil-access-false.js",
			"tests/jil/config.xml/jil-access-warp.js",
			"tests/jil/config.xml/jil-access.js",
			"tests/jil/config.xml/missing-access.js",
			"tests/jil/config.xml/warp-jil-access.js",

			"tests/w3c/config.xml/warp.js",
		]
	},

	simple:{
		applies:true,
		files:[
			"tests/base/window.js",
			"tests/base/xhr/ports.js",

			"tests/w3c/css/animation.js",
			"tests/w3c/css/basics.js",
			"tests/w3c/css/transform.js",
			"tests/w3c/css/transition.js",

			"tests/w3c/mediaquery/orientation.js",
			"tests/w3c/mediaquery/widthHeight.js",
			"tests/w3c/mediaquery/misc.js",

			"tests/w3c/audio/properties.js",

			"tests/w3c/input/attributes.js",
			"tests/w3c/input/typeDate.js",

			"tests/misc/uri/sms.js",
			"tests/misc/uri/mailto.js",
		]
	},

	widget:{
		applies:!!window.widget,
		files:[
			"tests/vendor/vodafone/metrics.js",

			"tests/base/widget.js",
			"tests/base/widget-update/update0.js",
			"tests/base/widget-update/update1.js",
		]
	},

	jil:{
		applies:!!window.Widget,
		files:[
			"tests/jil/security/policy.js",

			"tests/jil/AccelerometerInfo.js",
			"tests/jil/AccountInfo.js",
			"tests/jil/AddressBook.js",
			"tests/jil/AddressBookItem.js",
			"tests/jil/Application.js",
			"tests/jil/AudioPlayer.js",
			"tests/jil/Basics.js",
			"tests/jil/Calendar.js",
			"tests/jil/Camera.js",
			"tests/jil/Config.js",
			"tests/jil/DataNetworkInfo.js",
			"tests/jil/Device.js",
			"tests/jil/DeviceInfo.js",
			"tests/jil/DeviceStateInfo.js",
			"tests/jil/File.js",
			//"tests/jil/MessageQuantities.js",
			"tests/jil/Messaging.js",
			"tests/jil/MessagingEmailAccount.js",
			"tests/jil/MessagingFolder.js",
			"tests/jil/PositionInfo.js",
			"tests/jil/PowerInfo.js",
			"tests/jil/RadioInfo.js",
			"tests/jil/Telephony.js",
			"tests/jil/VideoCamera.js",
			"tests/jil/VideoPlayer.js",
			"tests/jil/Widget.js",

			"tests/performance/jil/AddressBook.js",
		]
	}

};<commit_msg>Added datetime tests<commit_after>/*
	Copyright 2010-2011 Vodafone Group Services GmbH

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

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

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

	configXmlDependent:{
		applies:!!window.Widget,
		files:[
			// Those are the tests that depend on a certain setup in the config.xml
			// so they normally can not be run form the all.html.
			"tests/jil/config.xml/jil-access-false.js",
			"tests/jil/config.xml/jil-access-warp.js",
			"tests/jil/config.xml/jil-access.js",
			"tests/jil/config.xml/missing-access.js",
			"tests/jil/config.xml/warp-jil-access.js",

			"tests/w3c/config.xml/warp.js",
		]
	},

	simple:{
		applies:true,
		files:[
			"tests/base/window.js",
			"tests/base/xhr/ports.js",

			"tests/w3c/css/animation.js",
			"tests/w3c/css/basics.js",
			"tests/w3c/css/transform.js",
			"tests/w3c/css/transition.js",

			"tests/w3c/mediaquery/orientation.js",
			"tests/w3c/mediaquery/widthHeight.js",
			"tests/w3c/mediaquery/misc.js",

			"tests/w3c/audio/properties.js",

			"tests/w3c/input/attributes.js",
			"tests/w3c/input/typeDate.js",
			"tests/w3c/input/typeDatetime.js",

			"tests/misc/uri/sms.js",
			"tests/misc/uri/mailto.js",
		]
	},

	widget:{
		applies:!!window.widget,
		files:[
			"tests/vendor/vodafone/metrics.js",

			"tests/base/widget.js",
			"tests/base/widget-update/update0.js",
			"tests/base/widget-update/update1.js",
		]
	},

	jil:{
		applies:!!window.Widget,
		files:[
			"tests/jil/security/policy.js",

			"tests/jil/AccelerometerInfo.js",
			"tests/jil/AccountInfo.js",
			"tests/jil/AddressBook.js",
			"tests/jil/AddressBookItem.js",
			"tests/jil/Application.js",
			"tests/jil/AudioPlayer.js",
			"tests/jil/Basics.js",
			"tests/jil/Calendar.js",
			"tests/jil/Camera.js",
			"tests/jil/Config.js",
			"tests/jil/DataNetworkInfo.js",
			"tests/jil/Device.js",
			"tests/jil/DeviceInfo.js",
			"tests/jil/DeviceStateInfo.js",
			"tests/jil/File.js",
			//"tests/jil/MessageQuantities.js",
			"tests/jil/Messaging.js",
			"tests/jil/MessagingEmailAccount.js",
			"tests/jil/MessagingFolder.js",
			"tests/jil/PositionInfo.js",
			"tests/jil/PowerInfo.js",
			"tests/jil/RadioInfo.js",
			"tests/jil/Telephony.js",
			"tests/jil/VideoCamera.js",
			"tests/jil/VideoPlayer.js",
			"tests/jil/Widget.js",

			"tests/performance/jil/AddressBook.js",
		]
	}

};<|endoftext|>


<commit_before>var when = require( "when" );
var _ = require( "lodash" );
var Monologue = require( "monologue.js" );
var log = require( "./log" )( "rabbot.topology" );
var info = require( "./info" );
var Exchange, Queue;
var replyId;

/* log
	* `rabbot.topology`
	  * `info`
	    * creating a binding
	    * deleting an exchange
	    * deleting a queue
	    * reconnection established
	    * topology rebuilt (after reconnection)
	  * `error`
	    * failed to create reply queue
*/

function getKeys( keys ) {
	var actualKeys = [ "" ];
	if ( keys && keys.length > 0 ) {
		actualKeys = _.isArray( keys ) ? keys : [ keys ];
	}
	return actualKeys;
}

function toArray( x, list ) {
	if ( _.isArray( x ) ) {
		return x;
	}
	if ( _.isObject( x ) && list ) {
		return _.map( x, function( item ) {
			return item;
		} );
	}
	if ( _.isUndefined( x ) || _.isEmpty( x ) ) {
		return [];
	}
	return [ x ];
}

var Topology = function( connection, options, serializers, unhandledStrategies, returnedStrategies ) {
	var autoReplyTo = { name: [ replyId, "response", "queue" ].join( '.' ), autoDelete: true, subscribe: true };
	var rabbitReplyTo = { name: "amq.rabbitmq.reply-to", subscribe: true, noAck: true };
	var userReplyTo = _.isObject( options.replyQueue ) ? options.replyQueue : { name: options.replyQueue, autoDelete: true, subscribe: true };
	this.name = options.name;
	this.connection = connection;
	this.channels = {};
	this.promises = {};
	this.definitions = {
		bindings: {},
		exchanges: {},
		queues: {}
	};
	this.options = options;
	this.replyQueue = { name: false };
	this.serializers = serializers;
	this.onUnhandled = function( message ) {
		return unhandledStrategies.onUnhandled( message );
	};
	this.onReturned = function( message ) {
		return returnedStrategies.onReturned( message );
	};
	var replyQueueName = '';

	if ( _.has( options, "replyQueue" ) ) {
		replyQueueName = options.replyQueue.name || options.replyQueue;
		if ( replyQueueName === false ) {
			this.replyQueue = { name: false };
		} else if ( replyQueueName ) {
			this.replyQueue = userReplyTo;
		} else if ( replyQueueName === "rabbitmq" ) {
			this.replyQueue = rabbitReplyTo;
		}
	} else {
		this.replyQueue = autoReplyTo;
	}

	function onReplyQueueFailed( err ) {
		log.error( "Failed to create reply queue for connection name '" + connection.name || "default" + "' with ", err );
	}

	connection.on( "reconnected", function() {
		this.createReplyQueue().then( null, onReplyQueueFailed );
		this.onReconnect();
	}.bind( this ) );

	connection.on( "return", function(raw) {
		raw.type = _.isEmpty( raw.properties.type ) ? raw.fields.routingKey : raw.properties.type;
		var contentType = raw.properties.contentType || "application/octet-stream";
		var serializer = this.serializers[ contentType ];
		if( !serializer ) {
			log.error( "Could not deserialize message id %s, connection '%s' - no serializer defined",
				raw.properties.messageId, this.connection.name );
		} else {
			try {
				raw.body = serializer.deserialize( raw.content, raw.properties.contentEncoding );
			} catch( err ) {
			}
		}

		this.onReturned(raw);
	}.bind( this ) );

	// delay creation to allow for subscribers to attach a handler
	process.nextTick( function() {
		this.createReplyQueue().then( null, onReplyQueueFailed );
	}.bind( this ) );
};

Topology.prototype.configureBindings = function( bindingDef, list ) {
	if ( _.isUndefined( bindingDef ) ) {
		return when( true );
	} else {
		var actualDefinitions = toArray( bindingDef, list );
		var bindings = _.map( actualDefinitions, function( def ) {
				var q = this.definitions.queues[ def.queueAlias ? def.queueAlias : def.target ];
				return this.createBinding(
					{
						source: def.exchange || def.source,
						target: q ? q.uniqueName : def.target,
						keys: def.keys,
						queue: q !== undefined,
						queueAlias: q ? q.name : undefined
					} );
			}.bind( this ) );
		if ( bindings.length === 0 ) {
			return when( true );
		} else {
			return when.all( bindings );
		}
	}
};

Topology.prototype.configureQueues = function( queueDef, list ) {
	if ( _.isUndefined( queueDef ) ) {
		return when( true );
	} else {
		var actualDefinitions = toArray( queueDef, list );
		var queues = _.map( actualDefinitions, function( def ) {
			return this.createQueue( def );
		}.bind( this ) );
		return when.all( queues );
	}
};

Topology.prototype.configureExchanges = function( exchangeDef, list ) {
	if ( _.isUndefined( exchangeDef ) ) {
		return when( true );
	} else {
		var actualDefinitions = toArray( exchangeDef, list );
		var exchanges = _.map( actualDefinitions, function( def ) {
			return this.createExchange( def );
		}.bind( this ) );
		return when.all( exchanges );
	}
};

Topology.prototype.createBinding = function( options ) {
	var id = [ options.source, options.target ].join( "->" );
	var keys = getKeys( options.keys );
	if ( keys.length > 1 || keys[0] !== "" ) {
		id += ":" + keys.join(':');
	}
	var promise = this.promises[ id ];
	if( !promise ) {
		this.definitions.bindings[ id ] = options;
		var call = options.queue ? "bindQueue" : "bindExchange";
		var source = options.source;
		var target = options.target;
		this.promises[ id ] = promise = this.connection.getChannel( "control", false, "control channel for bindings" )
			.then( function( channel ) {
				log.info( "Binding %s '%s' to '%s' on '%s' with keys: %s",
					( options.queue ? "queue" : "exchange" ), target, source, this.connection.name, JSON.stringify( keys ) );
				return when.all(
					_.map( keys, function( key ) {
						return channel[ call ]( target, source, key );
					} ) );
			}.bind( this ) );

	}
	return promise;
};

Topology.prototype.createPrimitive = function( Primitive, primitiveType, options ) {
	var errorFn = function( err ) {
		return new Error( "Failed to create " + primitiveType + " '" + options.name +
			"' on connection '" + this.connection.name +
			"' with '" + ( err ? ( err.stack || err ) : "N/A" ) + "'" );
	}.bind( this );
	var definitions = primitiveType === "exchange" ? this.definitions.exchanges : this.definitions.queues;
	var channelName = [ primitiveType, options.name ].join( ":" );
	var promise = this.promises[ channelName ];
	if( !promise ) {
		this.promises[ channelName ] = promise = when.promise( function( resolve, reject ) {
			definitions[ options.name ] = options;
			var primitive = this.channels[ channelName ] = new Primitive( options, this.connection, this, this.serializers );
			var onConnectionFailed = function( connectionError ) {
				reject( errorFn( connectionError ) );
			};
			if ( this.connection.state === "failed" ) {
				onConnectionFailed( this.connection.lastError() );
			} else {
				var onFailed = this.connection.on( "failed", function( err ) {
					onConnectionFailed( err );
				} );
				primitive.once( "defined", function() {
					onFailed.unsubscribe();
					resolve( primitive );
				} );
			}
			primitive.once( "failed", function( err ) {
				delete definitions[ options.name ];
				delete this.channels[ channelName ];
				reject( errorFn( err ) );
			}.bind( this ) );
		}.bind( this ) );
	}
	return promise;
};

Topology.prototype.createExchange = function( options ) {
	return this.createPrimitive( Exchange, "exchange", options );
};

Topology.prototype.createQueue = function( options ) {
	options.uniqueName = this.getUniqueName( options );
	return this.createPrimitive( Queue, "queue", options );
};

Topology.prototype.createReplyQueue = function() {
	if ( this.replyQueue.name === undefined || this.replyQueue.name === false ) {
		return when.resolve();
	}
	var key = "queue:" + this.replyQueue.name;
	var promise;
	if ( !this.channels[ key ] ) {
		promise = this.createQueue( this.replyQueue );
		promise.then( function( channel ) {
			this.channels[ key ] = channel;
			this.emit( "replyQueue.ready", this.replyQueue );
		}.bind( this ) );
	} else {
		promise = when.resolve( this.channels[ key ] );
		this.emit( "replyQueue.ready", this.replyQueue );
	}
	return promise;
};

Topology.prototype.deleteExchange = function( name ) {
	var key = "exchange:" + name;
	var channel = this.channels[ key ];
	if ( channel ) {
		channel.release();
		delete this.channels[ key ];
		log.info( "Deleting %s exchange '%s' on connection '%s'", channel.type, name, this.connection.name );
	}
	return this.connection.getChannel( "control", false, "control channel for bindings"  )
		.then( function( channel ) {
			return channel.deleteExchange( name );
		} );
};

Topology.prototype.deleteQueue = function( name ) {
	var key = "queue:" + name;
	var channel = this.channels[ key ];
	if ( channel ) {
		channel.release();
		delete this.channels[ key ];
		log.info( "Deleting queue '%s' on connection '%s'", name, this.connection.name );
	}
	return this.connection.getChannel( "control", false, "control channel for bindings"  )
		.then( function( channel ) {
			return channel.deleteQueue( name );
		} );
};

Topology.prototype.getUniqueName = function( options ) {
	if( options.unique === "id" ) {
		return [ info.id, options.name ].join( "-" );
	} else if( options.unique === "hash" ) {
		return [ options.name, info.createHash() ].join( "-" );
	} else if( options.unique === "consistent" ) {
		return [ options.name, info.createConsistentHash() ].join( "-" );
	} else {
		return options.name;
	}
};

Topology.prototype.onReconnect = function() {
	log.info( "Reconnection to '%s' established - rebuilding topology", this.connection.name );
	this.promises = {};
	var prerequisites = _.map( this.channels, function( channel ) {
		return channel.check ? channel.check() : when( true );
	}.bind( this ) );
	return when.all( prerequisites )
		.then( function() {
			return this.configureBindings( this.definitions.bindings, true )
				.then( function() {
					log.info( "Topology rebuilt for connection '%s'", this.connection.name );
					this.emit( "bindings-completed", this.definitions );
				}.bind( this ) );
		}.bind( this ) );
};

Topology.prototype.reset = function() {
	this.channels = {};
	this.definitions = {
		bindings: {},
		exchanges: {},
		queues: {},
		subscriptions: {}
	};
};

Monologue.mixInto( Topology );

module.exports = function( connection, options, serializers, unhandledStrategies, returnedStrategies, exchangeFsm, queueFsm, defaultId ) {
	// allows us to optionally provide mocks and control the default queue name
	Exchange = exchangeFsm || require( "./exchangeFsm.js" );
	Queue = queueFsm || require( "./queueFsm.js" );
	replyId = defaultId || info.id;

	return new Topology( connection, options, serializers, unhandledStrategies, returnedStrategies );
};
<commit_msg>Removing unnecessary length check<commit_after>var when = require( "when" );
var _ = require( "lodash" );
var Monologue = require( "monologue.js" );
var log = require( "./log" )( "rabbot.topology" );
var info = require( "./info" );
var Exchange, Queue;
var replyId;

/* log
	* `rabbot.topology`
	  * `info`
	    * creating a binding
	    * deleting an exchange
	    * deleting a queue
	    * reconnection established
	    * topology rebuilt (after reconnection)
	  * `error`
	    * failed to create reply queue
*/

function getKeys( keys ) {
	var actualKeys = [ "" ];
	if ( keys && keys.length > 0 ) {
		actualKeys = _.isArray( keys ) ? keys : [ keys ];
	}
	return actualKeys;
}

function toArray( x, list ) {
	if ( _.isArray( x ) ) {
		return x;
	}
	if ( _.isObject( x ) && list ) {
		return _.map( x, function( item ) {
			return item;
		} );
	}
	if ( _.isUndefined( x ) || _.isEmpty( x ) ) {
		return [];
	}
	return [ x ];
}

var Topology = function( connection, options, serializers, unhandledStrategies, returnedStrategies ) {
	var autoReplyTo = { name: [ replyId, "response", "queue" ].join( '.' ), autoDelete: true, subscribe: true };
	var rabbitReplyTo = { name: "amq.rabbitmq.reply-to", subscribe: true, noAck: true };
	var userReplyTo = _.isObject( options.replyQueue ) ? options.replyQueue : { name: options.replyQueue, autoDelete: true, subscribe: true };
	this.name = options.name;
	this.connection = connection;
	this.channels = {};
	this.promises = {};
	this.definitions = {
		bindings: {},
		exchanges: {},
		queues: {}
	};
	this.options = options;
	this.replyQueue = { name: false };
	this.serializers = serializers;
	this.onUnhandled = function( message ) {
		return unhandledStrategies.onUnhandled( message );
	};
	this.onReturned = function( message ) {
		return returnedStrategies.onReturned( message );
	};
	var replyQueueName = '';

	if ( _.has( options, "replyQueue" ) ) {
		replyQueueName = options.replyQueue.name || options.replyQueue;
		if ( replyQueueName === false ) {
			this.replyQueue = { name: false };
		} else if ( replyQueueName ) {
			this.replyQueue = userReplyTo;
		} else if ( replyQueueName === "rabbitmq" ) {
			this.replyQueue = rabbitReplyTo;
		}
	} else {
		this.replyQueue = autoReplyTo;
	}

	function onReplyQueueFailed( err ) {
		log.error( "Failed to create reply queue for connection name '" + connection.name || "default" + "' with ", err );
	}

	connection.on( "reconnected", function() {
		this.createReplyQueue().then( null, onReplyQueueFailed );
		this.onReconnect();
	}.bind( this ) );

	connection.on( "return", function(raw) {
		raw.type = _.isEmpty( raw.properties.type ) ? raw.fields.routingKey : raw.properties.type;
		var contentType = raw.properties.contentType || "application/octet-stream";
		var serializer = this.serializers[ contentType ];
		if( !serializer ) {
			log.error( "Could not deserialize message id %s, connection '%s' - no serializer defined",
				raw.properties.messageId, this.connection.name );
		} else {
			try {
				raw.body = serializer.deserialize( raw.content, raw.properties.contentEncoding );
			} catch( err ) {
			}
		}

		this.onReturned(raw);
	}.bind( this ) );

	// delay creation to allow for subscribers to attach a handler
	process.nextTick( function() {
		this.createReplyQueue().then( null, onReplyQueueFailed );
	}.bind( this ) );
};

Topology.prototype.configureBindings = function( bindingDef, list ) {
	if ( _.isUndefined( bindingDef ) ) {
		return when( true );
	} else {
		var actualDefinitions = toArray( bindingDef, list );
		var bindings = _.map( actualDefinitions, function( def ) {
				var q = this.definitions.queues[ def.queueAlias ? def.queueAlias : def.target ];
				return this.createBinding(
					{
						source: def.exchange || def.source,
						target: q ? q.uniqueName : def.target,
						keys: def.keys,
						queue: q !== undefined,
						queueAlias: q ? q.name : undefined
					} );
			}.bind( this ) );
		if ( bindings.length === 0 ) {
			return when( true );
		} else {
			return when.all( bindings );
		}
	}
};

Topology.prototype.configureQueues = function( queueDef, list ) {
	if ( _.isUndefined( queueDef ) ) {
		return when( true );
	} else {
		var actualDefinitions = toArray( queueDef, list );
		var queues = _.map( actualDefinitions, function( def ) {
			return this.createQueue( def );
		}.bind( this ) );
		return when.all( queues );
	}
};

Topology.prototype.configureExchanges = function( exchangeDef, list ) {
	if ( _.isUndefined( exchangeDef ) ) {
		return when( true );
	} else {
		var actualDefinitions = toArray( exchangeDef, list );
		var exchanges = _.map( actualDefinitions, function( def ) {
			return this.createExchange( def );
		}.bind( this ) );
		return when.all( exchanges );
	}
};

Topology.prototype.createBinding = function( options ) {
	var id = [ options.source, options.target ].join( "->" );
	var keys = getKeys( options.keys );
	if ( keys[0] !== "" ) {
		id += ":" + keys.join(':');
	}
	var promise = this.promises[ id ];
	if( !promise ) {
		this.definitions.bindings[ id ] = options;
		var call = options.queue ? "bindQueue" : "bindExchange";
		var source = options.source;
		var target = options.target;
		this.promises[ id ] = promise = this.connection.getChannel( "control", false, "control channel for bindings" )
			.then( function( channel ) {
				log.info( "Binding %s '%s' to '%s' on '%s' with keys: %s",
					( options.queue ? "queue" : "exchange" ), target, source, this.connection.name, JSON.stringify( keys ) );
				return when.all(
					_.map( keys, function( key ) {
						return channel[ call ]( target, source, key );
					} ) );
			}.bind( this ) );

	}
	return promise;
};

Topology.prototype.createPrimitive = function( Primitive, primitiveType, options ) {
	var errorFn = function( err ) {
		return new Error( "Failed to create " + primitiveType + " '" + options.name +
			"' on connection '" + this.connection.name +
			"' with '" + ( err ? ( err.stack || err ) : "N/A" ) + "'" );
	}.bind( this );
	var definitions = primitiveType === "exchange" ? this.definitions.exchanges : this.definitions.queues;
	var channelName = [ primitiveType, options.name ].join( ":" );
	var promise = this.promises[ channelName ];
	if( !promise ) {
		this.promises[ channelName ] = promise = when.promise( function( resolve, reject ) {
			definitions[ options.name ] = options;
			var primitive = this.channels[ channelName ] = new Primitive( options, this.connection, this, this.serializers );
			var onConnectionFailed = function( connectionError ) {
				reject( errorFn( connectionError ) );
			};
			if ( this.connection.state === "failed" ) {
				onConnectionFailed( this.connection.lastError() );
			} else {
				var onFailed = this.connection.on( "failed", function( err ) {
					onConnectionFailed( err );
				} );
				primitive.once( "defined", function() {
					onFailed.unsubscribe();
					resolve( primitive );
				} );
			}
			primitive.once( "failed", function( err ) {
				delete definitions[ options.name ];
				delete this.channels[ channelName ];
				reject( errorFn( err ) );
			}.bind( this ) );
		}.bind( this ) );
	}
	return promise;
};

Topology.prototype.createExchange = function( options ) {
	return this.createPrimitive( Exchange, "exchange", options );
};

Topology.prototype.createQueue = function( options ) {
	options.uniqueName = this.getUniqueName( options );
	return this.createPrimitive( Queue, "queue", options );
};

Topology.prototype.createReplyQueue = function() {
	if ( this.replyQueue.name === undefined || this.replyQueue.name === false ) {
		return when.resolve();
	}
	var key = "queue:" + this.replyQueue.name;
	var promise;
	if ( !this.channels[ key ] ) {
		promise = this.createQueue( this.replyQueue );
		promise.then( function( channel ) {
			this.channels[ key ] = channel;
			this.emit( "replyQueue.ready", this.replyQueue );
		}.bind( this ) );
	} else {
		promise = when.resolve( this.channels[ key ] );
		this.emit( "replyQueue.ready", this.replyQueue );
	}
	return promise;
};

Topology.prototype.deleteExchange = function( name ) {
	var key = "exchange:" + name;
	var channel = this.channels[ key ];
	if ( channel ) {
		channel.release();
		delete this.channels[ key ];
		log.info( "Deleting %s exchange '%s' on connection '%s'", channel.type, name, this.connection.name );
	}
	return this.connection.getChannel( "control", false, "control channel for bindings"  )
		.then( function( channel ) {
			return channel.deleteExchange( name );
		} );
};

Topology.prototype.deleteQueue = function( name ) {
	var key = "queue:" + name;
	var channel = this.channels[ key ];
	if ( channel ) {
		channel.release();
		delete this.channels[ key ];
		log.info( "Deleting queue '%s' on connection '%s'", name, this.connection.name );
	}
	return this.connection.getChannel( "control", false, "control channel for bindings"  )
		.then( function( channel ) {
			return channel.deleteQueue( name );
		} );
};

Topology.prototype.getUniqueName = function( options ) {
	if( options.unique === "id" ) {
		return [ info.id, options.name ].join( "-" );
	} else if( options.unique === "hash" ) {
		return [ options.name, info.createHash() ].join( "-" );
	} else if( options.unique === "consistent" ) {
		return [ options.name, info.createConsistentHash() ].join( "-" );
	} else {
		return options.name;
	}
};

Topology.prototype.onReconnect = function() {
	log.info( "Reconnection to '%s' established - rebuilding topology", this.connection.name );
	this.promises = {};
	var prerequisites = _.map( this.channels, function( channel ) {
		return channel.check ? channel.check() : when( true );
	}.bind( this ) );
	return when.all( prerequisites )
		.then( function() {
			return this.configureBindings( this.definitions.bindings, true )
				.then( function() {
					log.info( "Topology rebuilt for connection '%s'", this.connection.name );
					this.emit( "bindings-completed", this.definitions );
				}.bind( this ) );
		}.bind( this ) );
};

Topology.prototype.reset = function() {
	this.channels = {};
	this.definitions = {
		bindings: {},
		exchanges: {},
		queues: {},
		subscriptions: {}
	};
};

Monologue.mixInto( Topology );

module.exports = function( connection, options, serializers, unhandledStrategies, returnedStrategies, exchangeFsm, queueFsm, defaultId ) {
	// allows us to optionally provide mocks and control the default queue name
	Exchange = exchangeFsm || require( "./exchangeFsm.js" );
	Queue = queueFsm || require( "./queueFsm.js" );
	replyId = defaultId || info.id;

	return new Topology( connection, options, serializers, unhandledStrategies, returnedStrategies );
};
<|endoftext|>