<commit_before>"use strict";
/*
 * ooiui/static/js/views/science/StreamTableView.js
 * View definitions to build a table view of streams
 *
 * Dependencies
 * Partials:
 * - ooiui/static/js/partials/StreamTable.html
 * - ooiui/static/js/partials/StreamTableItem.html
 * Libs
 * - ooiui/static/lib/underscore/underscore.js
 * - ooiui/static/lib/backbone/backbone.js
 * - ooiui/static/js/ooi.js
 * Usage
 */

var StreamTableView = Backbone.View.extend({
    columns: [
        {
            name: 'plot',
            label: ''
        },
        {
            name: 'download',
            label: ''
        },
        {
            name : 'array_name',
            label : 'Array'
        },
        {
            name : 'site_name',
            label : 'Site Name'
        },
        {
            name : 'platform_name',
            label : 'Platform Name'
        },
        {
            name : 'assembly_name',
            label : 'Node'
        },
        {
            name : 'display_name',
            label : 'Instrument'
        },
        {
            name : 'stream_name',
            label : 'Stream Identifier'
        },
        {
            name: 'stream_type',
            label: 'Stream Type'
        },
        {
            name: 'depth',
            label: 'Depth (m)'
        },
        {
            name: 'lat_lon',
            label: 'Lat / Lon (ddm)'
        },
        {
            name : 'start',
            label : 'Start Time'
        },
        {
            name : 'end',
            label : 'End Time'
        },
        {
            name: 'reference_designator',
            label: 'Reference Designator'
        }
    ],
    tagName: 'tbody',
    initialize: function() {
        _.bindAll(this, "render");
        this.listenTo(this.collection, 'reset', this.render);
        this.collection.on("add", this.addOne, this);
    },
    events: {
        'click th': 'sortBy'
    },
    sortBy: function(event) {
        event.stopPropagation();
        var eTarget = event.target;
        if ( !(eTarget.id.indexOf('plot') > -1 || eTarget.id.indexOf('download') > -1) ) {
            ooi.trigger('StreamTableHeader:sort', eTarget.id.split('-')[1]);
        }
    },
    template: JST['ooiui/static/js/partials/StreamTable.html'],
    render: function() {
        var self = this;
        this.$el.html(this.template({collection: this.collection, columns: this.columns}));
        this.$el.find('th').append('');
        this.$el.find('th#th-plot > i').remove();
        this.$el.find('th#th-download > i').remove();
        this.collection.each(function(model) {
           var streamTableItemView = new StreamTableItemView({
                    columns: self.columns,
                    model: model
                }),
                streamTableItemSubView = new StreamTableItemSubView({
                    model: model
                });
            self.$el.append(streamTableItemView.el);
            self.$el.append(streamTableItemSubView.render().el);
        });
    }
});

/*
model : StreamModel
*/
var StreamTableItemView = Backbone.View.extend({
    tagName: 'tr',
    attributes: function() {
        return {
            'valign': 'middle',
            'class': 'accordion-toggle stream-row',
            'data-toggle': 'collapse',
            'style': 'cursor: pointer;'
        }
    },
    events: {
        'click .download' : 'onDownload',
        'click .plot' : 'onRowClick'
    },
    initialize: function(options) {
        if(options && options.columns) {
            this.columns = options.columns;
        }
        this.listenTo(this.model, 'change', this.render);
        this.render();
    },
    onDownload: function(event) {
        event.stopPropagation();
        event.preventDefault();
        var option = $(event.currentTarget).attr("download-type");
        ooi.trigger('StreamTableItemView:onClick', {model: this.model, selection: option});
    },
    focus: function() {
        this.$el.addClass('highlight').siblings().removeClass('highlight');
    },
    template: JST['ooiui/static/js/partials/StreamTableItem.html'],
    render: function() {
        var attributes = this.model.toJSON();
        this.$el.html(this.template({attributes: this.attributes, model: this.model, columns: this.columns}));
        this.$el.attr('data-target', '#'+this.model.cid);
        var endDate = new Date(this.model.attributes.end);
        var timeSinceEndDate = new Date().getTime()-endDate.getTime();
        var endColumn = this.$el.find('.stream-end');
        if(timeSinceEndDate <= 1000*60*60*12){
            endColumn.addClass('twelve-hours');
        } else if(timeSinceEndDate < 1000*60*60*24){
            endColumn.addClass('twenty-four-hours');
        } else if(timeSinceEndDate >= 1000*60*60*24){
            endColumn.addClass('older');
        }
        if (attributes.variables.indexOf("filepath") > -1) {
            // debugger;
            var plotColumn = this.$el.find('.plot');
            // plotColumn.addClass('disabled');
            plotColumn.removeClass('td.download');
        }

    },
    onRowClick: function(event) {
        event.stopPropagation();
        if (this.model.attributes.variables.indexOf("filepath") > -1) {
            console.log('WOOHOOO');
        }else{
            ooi.trigger('StreamTableItemView:onRowClick', this);
        }
    },
});

var StreamTableItemSubView = Backbone.View.extend({
    tagName: 'tr',
    attributes: function() {
        return {
            'class': 'collapse'
        }
    },
    initialize: function() {
        "use strict";
        this.listenTo(this.model, 'change', this.render);
    },
    template: JST['ooiui/static/js/partials/StreamTableItemSubView.html'],
    render: function() {
        "use strict";
        this.$el.attr('id', this.model.cid);
        this.$el.html(this.template({model: this.model.toJSON()}));
        return this;
    }
});
<commit_msg>cleanup<commit_after>"use strict";
/*
 * ooiui/static/js/views/science/StreamTableView.js
 * View definitions to build a table view of streams
 *
 * Dependencies
 * Partials:
 * - ooiui/static/js/partials/StreamTable.html
 * - ooiui/static/js/partials/StreamTableItem.html
 * Libs
 * - ooiui/static/lib/underscore/underscore.js
 * - ooiui/static/lib/backbone/backbone.js
 * - ooiui/static/js/ooi.js
 * Usage
 */

var StreamTableView = Backbone.View.extend({
    columns: [
        {
            name: 'plot',
            label: ''
        },
        {
            name: 'download',
            label: ''
        },
        {
            name : 'array_name',
            label : 'Array'
        },
        {
            name : 'site_name',
            label : 'Site Name'
        },
        {
            name : 'platform_name',
            label : 'Platform Name'
        },
        {
            name : 'assembly_name',
            label : 'Node'
        },
        {
            name : 'display_name',
            label : 'Instrument'
        },
        {
            name : 'stream_name',
            label : 'Stream Identifier'
        },
        {
            name: 'stream_type',
            label: 'Stream Type'
        },
        {
            name: 'depth',
            label: 'Depth (m)'
        },
        {
            name: 'lat_lon',
            label: 'Lat / Lon (ddm)'
        },
        {
            name : 'start',
            label : 'Start Time'
        },
        {
            name : 'end',
            label : 'End Time'
        },
        {
            name: 'reference_designator',
            label: 'Reference Designator'
        }
    ],
    tagName: 'tbody',
    initialize: function() {
        _.bindAll(this, "render");
        this.listenTo(this.collection, 'reset', this.render);
        this.collection.on("add", this.addOne, this);
    },
    events: {
        'click th': 'sortBy'
    },
    sortBy: function(event) {
        event.stopPropagation();
        var eTarget = event.target;
        if ( !(eTarget.id.indexOf('plot') > -1 || eTarget.id.indexOf('download') > -1) ) {
            ooi.trigger('StreamTableHeader:sort', eTarget.id.split('-')[1]);
        }
    },
    template: JST['ooiui/static/js/partials/StreamTable.html'],
    render: function() {
        var self = this;
        this.$el.html(this.template({collection: this.collection, columns: this.columns}));
        this.$el.find('th').append('');
        this.$el.find('th#th-plot > i').remove();
        this.$el.find('th#th-download > i').remove();
        this.collection.each(function(model) {
           var streamTableItemView = new StreamTableItemView({
                    columns: self.columns,
                    model: model
                }),
                streamTableItemSubView = new StreamTableItemSubView({
                    model: model
                });
            self.$el.append(streamTableItemView.el);
            self.$el.append(streamTableItemSubView.render().el);
        });
    }
});

/*
model : StreamModel
*/
var StreamTableItemView = Backbone.View.extend({
    tagName: 'tr',
    attributes: function() {
        return {
            'valign': 'middle',
            'class': 'accordion-toggle stream-row',
            'data-toggle': 'collapse',
            'style': 'cursor: pointer;'
        }
    },
    events: {
        'click .download' : 'onDownload',
        'click .plot' : 'onRowClick'
    },
    initialize: function(options) {
        if(options && options.columns) {
            this.columns = options.columns;
        }
        this.listenTo(this.model, 'change', this.render);
        this.render();
    },
    onDownload: function(event) {
        event.stopPropagation();
        event.preventDefault();
        var option = $(event.currentTarget).attr("download-type");
        ooi.trigger('StreamTableItemView:onClick', {model: this.model, selection: option});
    },
    focus: function() {
        this.$el.addClass('highlight').siblings().removeClass('highlight');
    },
    template: JST['ooiui/static/js/partials/StreamTableItem.html'],
    render: function() {
        var attributes = this.model.toJSON();
        this.$el.html(this.template({attributes: this.attributes, model: this.model, columns: this.columns}));
        this.$el.attr('data-target', '#'+this.model.cid);
        var endDate = new Date(this.model.attributes.end);
        var timeSinceEndDate = new Date().getTime()-endDate.getTime();
        var endColumn = this.$el.find('.stream-end');
        if(timeSinceEndDate <= 1000*60*60*12){
            endColumn.addClass('twelve-hours');
        } else if(timeSinceEndDate < 1000*60*60*24){
            endColumn.addClass('twenty-four-hours');
        } else if(timeSinceEndDate >= 1000*60*60*24){
            endColumn.addClass('older');
        }

    },
    onRowClick: function(event) {
        event.stopPropagation();
        if (this.model.attributes.variables.indexOf("filepath") == -1) {
            ooi.trigger('StreamTableItemView:onRowClick', this);
        }
    },
});

var StreamTableItemSubView = Backbone.View.extend({
    tagName: 'tr',
    attributes: function() {
        return {
            'class': 'collapse'
        }
    },
    initialize: function() {
        "use strict";
        this.listenTo(this.model, 'change', this.render);
    },
    template: JST['ooiui/static/js/partials/StreamTableItemSubView.html'],
    render: function() {
        "use strict";
        this.$el.attr('id', this.model.cid);
        this.$el.html(this.template({model: this.model.toJSON()}));
        return this;
    }
});
<|endoftext|>


<commit_before>define((require, exports, module) => {
  return class TRHMasterData {
    static getMasterData (k) {
      return TRHMasterData[k]
    }
    // Load data from local cache
    static load (store) {
      if (!chrome.devtools) {
        // TRHMasterData.UserLevel = require('data/UserLevelMaster1507123959917')
        // TRHMasterData.SwordLevel = require('data/SwordLevelMaster1507123959924')
        // TRHMasterData.Sword = require('data/SwordMaster1507123959937')
        // TRHMasterData.Equip = require('data/EquipMaster1507123959946')
        _.each(['UserLevel', 'SwordLevel', 'Sword', 'Equip', 'Consumable'], k => {
          store.commit('loadData', {
            key: k,
            loaded: true
          })
        })
      }
      return Promise.props({
        UserLevel: localforage.getItem('UserLevelMaster'),
        SwordLevel: localforage.getItem('SwordLevelMaster'),
        Sword: localforage.getItem('SwordMaster'),
        Equip: localforage.getItem('EquipMaster'),
        Consumable: localforage.getItem('ConsumableMaster')
      }).then((saved) => {
        console.log('loadLocal')
        _.each(saved, (v, k) => {
          TRHMasterData[k] = v
          console.log(TRHMasterData[k])
          store.commit('loadData', {
            key: k,
            loaded: !_.isNull(v)
          })
        })
      })
    }
    // Init data from Game Resource
    static init (content, store) {
      TRHMasterData.masterData = null
      // Convert data type
      let encodeData = atob(content)
      let convertTemp = encodeData.split('').map(x => x.charCodeAt(0))
      let originData = new Uint8Array(convertTemp)
      // Pack Zlib inflate
      let inflatedData = pako.inflate(originData)
      // Decrypt
      let decryptData = CryptoJS.AES.decrypt({
        ciphertext: CryptoJS.lib.WordArray.create(inflatedData)
      },
        CryptoJS.enc.Utf8.parse('xTs|0dw2swypRrry'), {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.NoPadding
        }
      )
      // Magic ?
      let jsonText = CryptoJS.enc.Utf8.stringify(decryptData)
      jsonText = jsonText.substr(0, jsonText.lastIndexOf('}') + 1)
      // To Object
      let dataObj = JSON.parse(jsonText)
      console.log(dataObj);
      // Take useful part
      TRHMasterData.masterData = dataObj
      // level_master
      TRHMasterData.UserLevel = null
      // sword_level_master
      TRHMasterData.SwordLevel = null
      // sword_master
      TRHMasterData.Sword = null
      // equip_master
      TRHMasterData.Equip = null
      // consumable_master
      TRHMasterData.Consumable = null
      //voice
      TRHMasterData.Voice = null
      // wait promise
      return Promise.all([
        TRHMasterData.initUserLevelMaster(store),
        TRHMasterData.initSwordLevelMaster(store),
        TRHMasterData.initSwordMaster(store),
        TRHMasterData.initEquipMaster(store),
        TRHMasterData.initConsumableMaster(store),
        //TRHMasterData.initIcons(store)
        //魔改voice抓取
        //TRHMasterData.initVoiceMaster(store)
      ]).then(() => {
        console.log('done', store)
      })
    }
    // Init Icons
    /*static initIcons(store) {
      if (TRHMasterData.masterData === null) return
      return hex_md5("swr_crest_s_000003u0xq7npke")
        .then(() => {
          console.log('IconDone')
        })
    }*/
    static initVoiceMaster(store){
      if (TRHMasterData.masterData === null) return
        TRHMasterData.Voice = _(TRHMasterData.masterData.voice_master)
          .split('\n')
          .map((line) => {
            let arr = line.split(',')
            let obj ={}
            obj['swordId'] = _.toInteger(arr[0])
            obj['type'] = _.toInteger(arr[1])
            obj['text'] = arr[3]
            obj['fileName'] = arr[4]
            return obj
          })
          .keyBy('fileName')
          .value()
        /*_.each(TRHMasterData.Voice, k => {
          return console.log("curl -o "+k.fileName+".mp3 http://static.touken-ranbu.jp/s/"+$.md5(k.fileName+"u0xq7npke")+".mp3")
        })*/
        return console.log("voiceDone")
    }
    // Init User Level Data
    static initUserLevelMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.UserLevel = _(TRHMasterData.masterData.level_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['level'] = _.toInteger(arr[0])
          obj['exp'] = _.toInteger(arr[1])
          obj['maxResource'] = _.toInteger(arr[2])
          obj['money'] = _.toInteger(arr[3])
          return obj
        })
        .keyBy('level')
        .value()
      return localforage.setItem('UserLevelMaster', TRHMasterData.UserLevel)
        .then(() => {
          console.log(TRHMasterData.UserLevel)
          store.commit('loadData', {
            key: 'UserLevel',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'UserLevel',
            loaded: false
          })
        })
    }

    // Init Sword Level Data
    static initSwordLevelMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.SwordLevel = _(TRHMasterData.masterData.sword_level_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['type'] = _.toInteger(arr[0])
          obj['level'] = _.toInteger(arr[1])
          obj['exp'] = _.toInteger(arr[2])
          return obj
        })
        .groupBy('type')
        .mapValues((val) => {
          return _(val).keyBy('level').mapValues(v => v.exp).value()
        })
        .value()
      return localforage.setItem('SwordLevelMaster', TRHMasterData.SwordLevel)
        .then(() => {
          console.log(TRHMasterData.SwordLevel)
          store.commit('loadData', {
            key: 'SwordLevel',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'SwordLevel',
            loaded: false
          })
        })
    }

    // Init Sword Data
    static initSwordMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.Sword = _(TRHMasterData.masterData.sword_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['swordId'] = _.toInteger(arr[0])
          obj['baseId'] = _.toInteger(arr[1])
          obj['name'] = arr[2]
          obj['alias'] = arr[3]
          obj['symbol'] = _.toInteger(arr[4])
          obj['styleId'] = _.toInteger(arr[5])
          obj['type'] = _.toInteger(arr[6])
          obj['realType'] = _.toInteger(arr[7])
          obj['rarity'] = _.toInteger(arr[8])
          obj['maxLevel'] = _.toInteger(arr[9])
          obj['hp'] = _.toInteger(arr[10])
          obj['atk'] = _.toInteger(arr[11])
          obj['def'] = _.toInteger(arr[12])
          obj['mobile'] = _.toInteger(arr[13])
          obj['back'] = _.toInteger(arr[14])
          obj['scout'] = _.toInteger(arr[15])
          obj['hide'] = _.toInteger(arr[16])
          obj['hpUp'] = _.toInteger(arr[17])
          obj['atkUp'] = _.toInteger(arr[18])
          obj['defUp'] = _.toInteger(arr[19])
          obj['mobileUp'] = _.toInteger(arr[20])
          obj['backUp'] = _.toInteger(arr[21])
          obj['scoutUp'] = _.toInteger(arr[22])
          obj['hideUp'] = _.toInteger(arr[23])
          obj['getCharcoal'] = _.toInteger(arr[24])
          obj['getSteel'] = _.toInteger(arr[25])
          obj['getCoolant'] = _.toInteger(arr[26])
          obj['getFile'] = _.toInteger(arr[27])
          obj['careCharcoal'] = _.toInteger(arr[28])
          obj['careSteel'] = _.toInteger(arr[29])
          obj['careCoolant'] = _.toInteger(arr[30])
          obj['careFile'] = _.toInteger(arr[31])
          obj['equipSlot'] = _.toInteger(arr[32])
          obj['loyalties'] = _.toInteger(arr[33])
          obj['artist'] = arr[34]
          obj['voiceActor'] = arr[35]
          obj['imageId'] = _.toInteger(arr[36])
          obj['shareWord'] = _.toInteger(arr[37])
          return obj
        })
        .keyBy('swordId')
        .value()
      return localforage.setItem('SwordMaster', TRHMasterData.Sword)
        .then(() => {
          console.log(TRHMasterData.Sword)
          store.commit('loadData', {
            key: 'Sword',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'Sword',
            loaded: false
          })
        })
    }

    // Init Equip Data
    static initEquipMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.Equip = _(TRHMasterData.masterData.equip_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['equipId'] = _.toInteger(arr[0])
          obj['name'] = arr[1]
          obj['description'] = arr[2]
          obj['type'] = _.toInteger(arr[3])
          obj['rarity'] = _.toInteger(arr[4])
          obj['atk'] = _.toInteger(arr[5])
          obj['def'] = _.toInteger(arr[6])
          obj['mobility'] = _.toInteger(arr[7])
          obj['back'] = _.toInteger(arr[8])
          obj['scout'] = _.toInteger(arr[9])
          obj['hide'] = _.toInteger(arr[10])
          obj['soldier'] = _.toInteger(arr[11])
          obj['disposeCharcoal'] = _.toInteger(arr[12])
          obj['disposeSteel'] = _.toInteger(arr[13])
          obj['disposeCoolant'] = _.toInteger(arr[14])
          obj['disposeFile'] = _.toInteger(arr[15])
          return obj
        })
        .keyBy('equipId')
        .value()
      return localforage.setItem('EquipMaster', TRHMasterData.Equip)
        .then(() => {
          console.log(TRHMasterData.Equip)
          store.commit('loadData', {
            key: 'Equip',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'Equip',
            loaded: false
          })
        })
    }

    //Init Consumable Data
    static initConsumableMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.Consumable = _(TRHMasterData.masterData.consumable_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['consumableId'] = _.toInteger(arr[0])
          obj['baseId'] = _.toInteger(arr[1])
          obj['name'] = arr[2]
          obj['description'] = arr[3]
          obj['type'] = _.toInteger(arr[4])
          obj['value'] = _.toInteger(arr[5])
          obj['limitNum'] = _.toInteger(arr[6])
          //flg of available?
          obj['flg'] = _.toInteger(arr[7])
          //abandoned but exist??
          obj['unknown'] = _.toInteger(arr[8])
          return obj
        })
        .keyBy('consumableId')
        .value()
      return localforage.setItem('ConsumableMaster', TRHMasterData.Consumable)
        .then(() => {
          console.log(TRHMasterData.Consumable)
          store.commit('loadData', {
            key: 'Consumable',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'Consumable',
            loaded: false
          })
        })
    }
  }
})
<commit_msg>read square master data<commit_after>define((require, exports, module) => {
  return class TRHMasterData {
    static getMasterData (k) {
      return TRHMasterData[k]
    }
    // Load data from local cache
    static load (store) {
      if (!chrome.devtools) {
        // TRHMasterData.UserLevel = require('data/UserLevelMaster1507123959917')
        // TRHMasterData.SwordLevel = require('data/SwordLevelMaster1507123959924')
        // TRHMasterData.Sword = require('data/SwordMaster1507123959937')
        // TRHMasterData.Equip = require('data/EquipMaster1507123959946')
        _.each(['UserLevel', 'SwordLevel', 'Sword', 'Equip', 'Consumable', 'FieldSquare', "EventSquare"], k => {
          store.commit('loadData', {
            key: k,
            loaded: true
          })
        })
      }
      return Promise.props({
        UserLevel: localforage.getItem('UserLevelMaster'),
        SwordLevel: localforage.getItem('SwordLevelMaster'),
        Sword: localforage.getItem('SwordMaster'),
        Equip: localforage.getItem('EquipMaster'),
        Consumable: localforage.getItem('ConsumableMaster'),
        FieldSquare: localforage.getItem('FieldSquareMaster'),
        EventSquare: localforage.getItem('EventSquareMaster')
      }).then((saved) => {
        console.log('loadLocal')
        _.each(saved, (v, k) => {
          TRHMasterData[k] = v
          console.log(TRHMasterData[k])
          store.commit('loadData', {
            key: k,
            loaded: !_.isNull(v)
          })
        })
      })
    }
    // Init data from Game Resource
    static init (content, store) {
      TRHMasterData.masterData = null
      // Convert data type
      let encodeData = atob(content)
      let convertTemp = encodeData.split('').map(x => x.charCodeAt(0))
      let originData = new Uint8Array(convertTemp)
      // Pack Zlib inflate
      let inflatedData = pako.inflate(originData)
      // Decrypt
      let decryptData = CryptoJS.AES.decrypt({
        ciphertext: CryptoJS.lib.WordArray.create(inflatedData)
      },
        CryptoJS.enc.Utf8.parse('xTs|0dw2swypRrry'), {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.NoPadding
        }
      )
      // Magic ?
      let jsonText = CryptoJS.enc.Utf8.stringify(decryptData)
      jsonText = jsonText.substr(0, jsonText.lastIndexOf('}') + 1)
      // To Object
      let dataObj = JSON.parse(jsonText)
      console.log(dataObj);
      // Take useful part
      TRHMasterData.masterData = dataObj
      // level_master
      TRHMasterData.UserLevel = null
      // sword_level_master
      TRHMasterData.SwordLevel = null
      // sword_master
      TRHMasterData.Sword = null
      // equip_master
      TRHMasterData.Equip = null
      // consumable_master
      TRHMasterData.Consumable = null
      // field_square_master
      TRHMasterData.FieldSquare = null
      // event_square_master
      TRHMasterData.EventSquare = null
      // wait promise
      return Promise.all([
        TRHMasterData.initUserLevelMaster(store),
        TRHMasterData.initSwordLevelMaster(store),
        TRHMasterData.initSwordMaster(store),
        TRHMasterData.initEquipMaster(store),
        TRHMasterData.initConsumableMaster(store),
        TRHMasterData.initFieldSquareMaster(store),
        TRHMasterData.initEventSquareMaster(store)
      ]).then(() => {
        console.log('done', store)
      })
    }
    // Init User Level Data
    static initUserLevelMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.UserLevel = _(TRHMasterData.masterData.level_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['level'] = _.toInteger(arr[0])
          obj['exp'] = _.toInteger(arr[1])
          obj['maxResource'] = _.toInteger(arr[2])
          obj['money'] = _.toInteger(arr[3])
          return obj
        })
        .keyBy('level')
        .value()
      return localforage.setItem('UserLevelMaster', TRHMasterData.UserLevel)
        .then(() => {
          console.log(TRHMasterData.UserLevel)
          store.commit('loadData', {
            key: 'UserLevel',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'UserLevel',
            loaded: false
          })
        })
    }

    // Init Sword Level Data
    static initSwordLevelMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.SwordLevel = _(TRHMasterData.masterData.sword_level_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['type'] = _.toInteger(arr[0])
          obj['level'] = _.toInteger(arr[1])
          obj['exp'] = _.toInteger(arr[2])
          return obj
        })
        .groupBy('type')
        .mapValues((val) => {
          return _(val).keyBy('level').mapValues(v => v.exp).value()
        })
        .value()
      return localforage.setItem('SwordLevelMaster', TRHMasterData.SwordLevel)
        .then(() => {
          console.log(TRHMasterData.SwordLevel)
          store.commit('loadData', {
            key: 'SwordLevel',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'SwordLevel',
            loaded: false
          })
        })
    }

    // Init Sword Data
    static initSwordMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.Sword = _(TRHMasterData.masterData.sword_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['swordId'] = _.toInteger(arr[0])
          obj['baseId'] = _.toInteger(arr[1])
          obj['name'] = arr[2]
          obj['alias'] = arr[3]
          obj['symbol'] = _.toInteger(arr[4])
          obj['styleId'] = _.toInteger(arr[5])
          obj['type'] = _.toInteger(arr[6])
          obj['realType'] = _.toInteger(arr[7])
          obj['rarity'] = _.toInteger(arr[8])
          obj['maxLevel'] = _.toInteger(arr[9])
          obj['hp'] = _.toInteger(arr[10])
          obj['atk'] = _.toInteger(arr[11])
          obj['def'] = _.toInteger(arr[12])
          obj['mobile'] = _.toInteger(arr[13])
          obj['back'] = _.toInteger(arr[14])
          obj['scout'] = _.toInteger(arr[15])
          obj['hide'] = _.toInteger(arr[16])
          obj['hpUp'] = _.toInteger(arr[17])
          obj['atkUp'] = _.toInteger(arr[18])
          obj['defUp'] = _.toInteger(arr[19])
          obj['mobileUp'] = _.toInteger(arr[20])
          obj['backUp'] = _.toInteger(arr[21])
          obj['scoutUp'] = _.toInteger(arr[22])
          obj['hideUp'] = _.toInteger(arr[23])
          obj['getCharcoal'] = _.toInteger(arr[24])
          obj['getSteel'] = _.toInteger(arr[25])
          obj['getCoolant'] = _.toInteger(arr[26])
          obj['getFile'] = _.toInteger(arr[27])
          obj['careCharcoal'] = _.toInteger(arr[28])
          obj['careSteel'] = _.toInteger(arr[29])
          obj['careCoolant'] = _.toInteger(arr[30])
          obj['careFile'] = _.toInteger(arr[31])
          obj['equipSlot'] = _.toInteger(arr[32])
          obj['loyalties'] = _.toInteger(arr[33])
          obj['artist'] = arr[34]
          obj['voiceActor'] = arr[35]
          obj['imageId'] = _.toInteger(arr[36])
          obj['shareWord'] = _.toInteger(arr[37])
          return obj
        })
        .keyBy('swordId')
        .value()
      return localforage.setItem('SwordMaster', TRHMasterData.Sword)
        .then(() => {
          console.log(TRHMasterData.Sword)
          store.commit('loadData', {
            key: 'Sword',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'Sword',
            loaded: false
          })
        })
    }

    // Init Equip Data
    static initEquipMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.Equip = _(TRHMasterData.masterData.equip_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['equipId'] = _.toInteger(arr[0])
          obj['name'] = arr[1]
          obj['description'] = arr[2]
          obj['type'] = _.toInteger(arr[3])
          obj['rarity'] = _.toInteger(arr[4])
          obj['atk'] = _.toInteger(arr[5])
          obj['def'] = _.toInteger(arr[6])
          obj['mobility'] = _.toInteger(arr[7])
          obj['back'] = _.toInteger(arr[8])
          obj['scout'] = _.toInteger(arr[9])
          obj['hide'] = _.toInteger(arr[10])
          obj['soldier'] = _.toInteger(arr[11])
          obj['disposeCharcoal'] = _.toInteger(arr[12])
          obj['disposeSteel'] = _.toInteger(arr[13])
          obj['disposeCoolant'] = _.toInteger(arr[14])
          obj['disposeFile'] = _.toInteger(arr[15])
          return obj
        })
        .keyBy('equipId')
        .value()
      return localforage.setItem('EquipMaster', TRHMasterData.Equip)
        .then(() => {
          console.log(TRHMasterData.Equip)
          store.commit('loadData', {
            key: 'Equip',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'Equip',
            loaded: false
          })
        })
    }

    //Init Consumable Data
    static initConsumableMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.Consumable = _(TRHMasterData.masterData.consumable_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['consumableId'] = _.toInteger(arr[0])
          obj['baseId'] = _.toInteger(arr[1])
          obj['name'] = arr[2]
          obj['description'] = arr[3]
          obj['type'] = _.toInteger(arr[4])
          obj['value'] = _.toInteger(arr[5])
          obj['limitNum'] = _.toInteger(arr[6])
          //flg of available?
          obj['flg'] = _.toInteger(arr[7])
          //abandoned but exist??
          obj['unknown'] = _.toInteger(arr[8])
          return obj
        })
        .keyBy('consumableId')
        .value()
      return localforage.setItem('ConsumableMaster', TRHMasterData.Consumable)
        .then(() => {
          console.log(TRHMasterData.Consumable)
          store.commit('loadData', {
            key: 'Consumable',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'Consumable',
            loaded: false
          })
        })
    }

    //Init Square Data
    static initFieldSquareMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.FieldSquare = _(TRHMasterData.masterData.field_square_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['episodeId'] = _.toInteger(arr[0])
          obj['fieldId'] = _.toInteger(arr[1])
          obj['layerNum'] = _.toInteger(arr[2])
          obj['squareId'] = _.toInteger(arr[3])
          obj['category'] = _.toInteger(arr[4])
          obj['itemType'] = _.toInteger(arr[5])
          obj['itemId'] = _.toInteger(arr[6])
          obj['itemNum'] = _.toInteger(arr[7])
          obj['bgmId'] = _.toInteger(arr[8])
          return obj
        })
        .groupBy('episodeId')
        .mapValues((val) => {
          return _(val)
            .groupBy('fieldId')
            .mapValues((v) => {
              return _(v)
                .groupBy('layerNum')
                .mapValues((vv) =>{
                  return _(vv)
                    .keyBy('squareId')
                    .value()
                })
                .value()
            })
            .value()
        })
        .value()
      return localforage.setItem('FieldSquareMaster', TRHMasterData.FieldSquare)
        .then(() => {
          console.log(TRHMasterData.FieldSquare)
          store.commit('loadData', {
            key: 'FieldSquare',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'FieldSquare',
            loaded: false
          })
        })
    }

    //Init Event Square Data
    static initEventSquareMaster (store) {
      if (TRHMasterData.masterData === null) return
      TRHMasterData.EventSquare = _(TRHMasterData.masterData.event_square_master)
        .split('\n')
        .map((line) => {
          let arr = line.split(',')
          let obj = {}
          obj['episodeId'] = _.toInteger(arr[0])*(-1)
          obj['fieldId'] = _.toInteger(arr[1])
          obj['layerNum'] = _.toInteger(arr[2])
          obj['squareId'] = _.toInteger(arr[3])
          obj['category'] = _.toInteger(arr[4])
          obj['itemType'] = _.toInteger(arr[5])
          obj['itemId'] = _.toInteger(arr[6])
          obj['itemNum'] = _.toInteger(arr[7])
          obj['bgmId'] = _.toInteger(arr[8])
          return obj
        })
        .groupBy('episodeId')
        .mapValues((val) => {
          return _(val)
            .groupBy('fieldId')
            .mapValues((v) => {
              return _(v)
                .groupBy('layerNum')
                .mapValues((vv) =>{
                  return _(vv)
                    .keyBy('squareId')
                    .value()
                })
                .value()
            })
            .value()
        })
        .value()
      return localforage.setItem('EventSquareMaster', TRHMasterData.EventSquare)
        .then(() => {
          console.log(TRHMasterData.EventSquare)
          store.commit('loadData', {
            key: 'EventSquare',
            loaded: true
          })
        })
        .catch((err) => {
          console.log('err', err)
          store.commit('loadData', {
            key: 'EventSquare',
            loaded: false
          })
        })
    }
  }
})
<|endoftext|>


<commit_before>(function() {
    var BASE_URL = "https://api.dropbox.com/1/";
    var nonce = 1;

    function Session(appKey, appSecret, accessType) {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.accessType = accessType;
        this.requestTokenSecret = '';
    }
    var p = Session.prototype;

    p._generateOauthData = function() {
        return {
            oauth_consumer_key: this.appKey,
            oauth_token: this.requestToken,
            oauth_signature_method: 'PLAINTEXT',
            oauth_signature: encodeURIComponent(this.appSecret + '&' + this.requestTokenSecret),
            oauth_nonce: nonce++,
            oauth_timestamp: Date.now()
        };
    };

    p.obtainRequestToken = function(k) {
        var self = this;
        $.ajax({
            url: BASE_URL + 'oauth/request_token?callback=?',
            dataType: 'jsonp',
            data: this._generateOauthData(),
            success: function(resp) {
                var parts = resp.split('&');
                self.requestTokenSecret = parts[0].split('=')[1];
                self.requestToken = parts[1].split('=')[1];
                k();
            }
        });
    };

    p.buildAuthorizeUrl = function() {
        return 'https://www.dropbox.com/1/oauth/authorize?oauth_token=' + this.requestToken;
    };

    p.obtainAccessToken = function(k) {
        var self = this;
        $.ajax({
            url: BASE_URL + 'oauth/access_token?callback=?',
            dataType: 'jsonp',
            data: this._generateOauthData(),
            timeout: 1000,
            success: function(resp) {
                var parts = resp.split('&');
                self.accessTokenSecret = parts[0].split('=')[1];
                self.accessToken = parts[1].split('=')[1];
                self.uid = parts[2].split('=')[1];
                k();
            },
            error: function() {
                self.obtainAccessToken(k);
            }
        });
    };

    p.getState = function() {
        return {
            accessToken: this.accessToken,
            accessTokenSecret: this.accessTokenSecret
        };
    };

    p.setState = function(tokens) {
        this.accessToken = tokens.accessToken;
        this.accessTokenSecret = tokens.accessTokenSecret;
    };

    function Client(session) {
        this.session = session;
    }
    var c = Client.prototype;

    c._generateOauthData = function() {
        return {
            oauth_consumer_key: this.session.appKey,
            oauth_token: this.session.accessToken,
            oauth_signature_method: 'PLAINTEXT',
            oauth_signature: encodeURIComponent(this.session.appSecret + '&' + this.session.accessTokenSecret),
            oauth_nonce: nonce++,
            oauth_timestamp: Date.now()
        };
    };

    c.api = function(method, params, successCallback, errorCallback) {
        var data = this._generateOauthData();
        params = params || {};
        for (key in params) {
            if (params.hasOwnProperty(key)) {
                data[key] = params[key];
            }
        }

        $.ajax({
            url: BASE_URL + method,
            dataType: 'jsonp',
            data: data,
            success: successCallback,
            error: errorCallback
        });
    };

    c._getRoot = function() {
        return this.session.accessType == 'dropbox' ? 'dropbox' : 'sandbox';
    };

    c._getPath = function(params) {
        if (!params || !params.path) {
            throw new Error("Must provide a path to get metadata from");
        }
        var path = params.path;
        delete params.path;
        return path;
    };

    c._getFileUrl = function(prefix, params) {
        var root = this._getRoot();
        var path = this._getPath(params);
        return [prefix, root, path].join('/');
    };

    c.accountInfo = function(successCallback, errorCallback) {
        this.api('account/info', {}, successCallback, errorCallback);
    };

    c.metadata = function(params, successCallback, errorCallback) {
        var url = this._getFileUrl('metadata', params);
        this.api(url, params, successCallback, errorCallback);
    };

    c.shares = function(params, successCallback, errorCallback) {
        var url = this._getFileUrl('shares', params);
    };

    this.Dropbox = {
        Session: Session,
        Client: Client
    };
})();
<commit_msg>have the session deal with a generic token object that can be set through setToken<commit_after>(function() {
    var BASE_URL = "https://api.dropbox.com/1/";
    var nonce = 1;

    function Session(appKey, appSecret, accessType) {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.accessType = accessType;
        this.token = {
            key: '',
            secret: ''
        };
    }
    var p = Session.prototype;

    p._generateOauthData = function() {
        return {
            oauth_consumer_key: this.appKey,
            oauth_token: this.token.key,
            oauth_signature_method: 'PLAINTEXT',
            oauth_signature: encodeURIComponent(this.appSecret + '&' + this.token.secret),
            oauth_nonce: nonce++,
            oauth_timestamp: Date.now()
        };
    };

    p.obtainRequestToken = function(k) {
        var self = this;
        $.ajax({
            url: BASE_URL + 'oauth/request_token?callback=?',
            dataType: 'jsonp',
            data: this._generateOauthData(),
            success: function(resp) {
                var parts = resp.split('&');
                self.token.secret = parts[0].split('=')[1];
                self.token.key = parts[1].split('=')[1];
                k();
            }
        });
    };

    p.buildAuthorizeUrl = function() {
        return 'https://www.dropbox.com/1/oauth/authorize?oauth_token=' + this.token.key;
    };

    p.obtainAccessToken = function(k) {
        var self = this;
        $.ajax({
            url: BASE_URL + 'oauth/access_token?callback=?',
            dataType: 'jsonp',
            data: this._generateOauthData(),
            timeout: 1000,
            success: function(resp) {
                var parts = resp.split('&');
                self.token.secret = parts[0].split('=')[1];
                self.token.key = parts[1].split('=')[1];
                self.uid = parts[2].split('=')[1];
                k();
            },
            error: function() {
                self.obtainAccessToken(k);
            }
        });
    };

    p.setToken = function(token) {
        this.token = token;
    };

    function Client(session) {
        this.session = session;
    }
    var c = Client.prototype;

    c._generateOauthData = function() {
        return {
            oauth_consumer_key: this.session.appKey,
            oauth_token: this.session.token.key,
            oauth_signature_method: 'PLAINTEXT',
            oauth_signature: encodeURIComponent(this.session.appSecret + '&' + this.session.token.secret),
            oauth_nonce: nonce++,
            oauth_timestamp: Date.now()
        };
    };

    c.api = function(method, params, successCallback, errorCallback) {
        var data = this._generateOauthData();
        params = params || {};
        for (key in params) {
            if (params.hasOwnProperty(key)) {
                data[key] = params[key];
            }
        }

        $.ajax({
            url: BASE_URL + method,
            dataType: 'jsonp',
            data: data,
            success: successCallback,
            error: errorCallback
        });
    };

    c._getRoot = function() {
        return this.session.accessType == 'dropbox' ? 'dropbox' : 'sandbox';
    };

    c._getPath = function(params) {
        if (!params || !params.path) {
            throw new Error("Must provide a path to get metadata from");
        }
        var path = params.path;
        delete params.path;
        return path;
    };

    c._getFileUrl = function(prefix, params) {
        var root = this._getRoot();
        var path = this._getPath(params);
        return [prefix, root, path].join('/');
    };

    c.accountInfo = function(successCallback, errorCallback) {
        this.api('account/info', {}, successCallback, errorCallback);
    };

    c.metadata = function(params, successCallback, errorCallback) {
        var url = this._getFileUrl('metadata', params);
        this.api(url, params, successCallback, errorCallback);
    };

    c.shares = function(params, successCallback, errorCallback) {
        var url = this._getFileUrl('shares', params);
    };

    this.Dropbox = {
        Session: Session,
        Client: Client
    };
})();
<|endoftext|>


<commit_before>import elasticsearch from 'elasticsearch'

const client = new elasticsearch.Client({
  host: process.env.FOUNDELASTICSEARCH_URL || 'localhost:9200',
  log: process.env.ELASTIC_LOG || 'trace'
})

class Elastic {
  static get type () {
    return this.name.toLowerCase()
  }

  static get index () {
    return process.env.ELASTIC_INDEX || 'bolaget_dev'
  }

  static async createIndex () {
    const options = {
      index: Elastic.index,
      body: {
        mappings: {},
        settings: {
          index: {
            number_of_replicas: 0,
            analysis: {
              filter: {
                swedish_stop: {
                  type: 'stop',
                  stopwords: '_swedish_'
                },
                swedish_stemmer: {
                  type: 'stemmer',
                  language: 'swedish'
                },
                swedish_sort: {
                  type: 'icu_collation',
                  language: 'sv',
                  country: 'SE',
                  variant: '@collation=phonebook'
                }
              },
              analyzer: {
                swedish_sort: {
                  tokenizer: 'keyword',
                  filter: ['swedish_sort']
                },
                standard_text: {
                  tokenizer: 'standard',
                  filter: 'lowercase'
                },
                swedish_edgegram: {
                  type: 'custom',
                  tokenizer: 'standard',
                  filter: [
                    'lowercase',
                    'swedish_stop',
                    'swedish_stemmer'
                  ]
                }
              }
            }
          }
        }
      }
    }

    return client.indices.create(options)
  }

  static async getIndex () {
    const options = {
      index: Elastic.index
    }

    return client.indices.get(options)
  }

  static async deleteIndex () {
    const options = {
      index: Elastic.index
    }

    return client.indices.delete(options)
  }

  static async getById (id) {
    return client.get({
      index: Elastic.index,
      type: this.type,
      id
    }).then(result => {
      return result._source
    })
    .catch(e => {
      throw e
    })
  }

  static async find (query, offset, limit, sort) {
    let filter = {
      index: Elastic.index,
      type: this.type,
      body: {
        from: offset,
        size: limit,
        sort
      }
    }

    if (Object.keys(query).length) {
      Object.assign(filter.body, { query })
    }

    return client.search(filter)
      .then(data => {
        const result = data.hits.hits.map(obj => {
          return obj._source
        })

        return { result, count: data.hits.total }
      })
      .catch(e => {
        throw e
      })
  }

  static async putMapping () {
    const mapping = {
      index: Elastic.index,
      type: this.type,
      body: this.mapping
    }

    return client.indices.putMapping(mapping)
  }

  static async bulk (data) {
    let batch = []

    data.forEach(obj => {
      batch.push({
        index: {
          _index: Elastic.index,
          _type: this.type,
          _id: obj.body.nr
        }
      })

      batch.push(obj.body)
    })

    return client.bulk({ body: batch })
  }

  constructor (data) {
    let mapped = {}
    this.body = {}
    this.id = null
    this.type = this.constructor.type
    this.model = this.constructor.model
    this.mapping = this.constructor.mapping.properties

    for (let prop in data) {
      if (data.hasOwnProperty(prop)) {
        if (this.model.hasOwnProperty(prop)) {
          const obj = this.model[prop]
          try {
            mapped[obj.value] = obj.transform(data[prop])
          } catch (e) {
            mapped[obj.value] = data[prop]
          }
        }
      }
    }

    for (let key in this.mapping) {
      if (this.mapping.hasOwnProperty(key)) {
        this.body[key] = mapped[key]
      }
    }
  }

  static get mapping () {
    throw new Error('Mapping not implemented!')
  }

  static get model () {
    throw new Error('Model not implemented!')
  }

  save () {
    const doc = {
      index: Elastic.index,
      type: this.type,
      id: this.body.nr,
      body: this.body
    }

    return client.index(doc)
  }
}

export default Elastic
<commit_msg>Changing process var for elastic<commit_after>import elasticsearch from 'elasticsearch'

const client = new elasticsearch.Client({
  host: process.env.ELASTIC_HOST || 'localhost:9200',
  log: process.env.ELASTIC_LOG || 'trace'
})

class Elastic {
  static get type () {
    return this.name.toLowerCase()
  }

  static get index () {
    return process.env.ELASTIC_INDEX || 'bolaget_dev'
  }

  static async createIndex () {
    const options = {
      index: Elastic.index,
      body: {
        mappings: {},
        settings: {
          index: {
            number_of_replicas: 0,
            analysis: {
              filter: {
                swedish_stop: {
                  type: 'stop',
                  stopwords: '_swedish_'
                },
                swedish_stemmer: {
                  type: 'stemmer',
                  language: 'swedish'
                },
                swedish_sort: {
                  type: 'icu_collation',
                  language: 'sv',
                  country: 'SE',
                  variant: '@collation=phonebook'
                }
              },
              analyzer: {
                swedish_sort: {
                  tokenizer: 'keyword',
                  filter: ['swedish_sort']
                },
                standard_text: {
                  tokenizer: 'standard',
                  filter: 'lowercase'
                },
                swedish_edgegram: {
                  type: 'custom',
                  tokenizer: 'standard',
                  filter: [
                    'lowercase',
                    'swedish_stop',
                    'swedish_stemmer'
                  ]
                }
              }
            }
          }
        }
      }
    }

    return client.indices.create(options)
  }

  static async getIndex () {
    const options = {
      index: Elastic.index
    }

    return client.indices.get(options)
  }

  static async deleteIndex () {
    const options = {
      index: Elastic.index
    }

    return client.indices.delete(options)
  }

  static async getById (id) {
    return client.get({
      index: Elastic.index,
      type: this.type,
      id
    }).then(result => {
      return result._source
    })
    .catch(e => {
      throw e
    })
  }

  static async find (query, offset, limit, sort) {
    let filter = {
      index: Elastic.index,
      type: this.type,
      body: {
        from: offset,
        size: limit,
        sort
      }
    }

    if (Object.keys(query).length) {
      Object.assign(filter.body, { query })
    }

    return client.search(filter)
      .then(data => {
        const result = data.hits.hits.map(obj => {
          return obj._source
        })

        return { result, count: data.hits.total }
      })
      .catch(e => {
        throw e
      })
  }

  static async putMapping () {
    const mapping = {
      index: Elastic.index,
      type: this.type,
      body: this.mapping
    }

    return client.indices.putMapping(mapping)
  }

  static async bulk (data) {
    let batch = []

    data.forEach(obj => {
      batch.push({
        index: {
          _index: Elastic.index,
          _type: this.type,
          _id: obj.body.nr
        }
      })

      batch.push(obj.body)
    })

    return client.bulk({ body: batch })
  }

  constructor (data) {
    let mapped = {}
    this.body = {}
    this.id = null
    this.type = this.constructor.type
    this.model = this.constructor.model
    this.mapping = this.constructor.mapping.properties

    for (let prop in data) {
      if (data.hasOwnProperty(prop)) {
        if (this.model.hasOwnProperty(prop)) {
          const obj = this.model[prop]
          try {
            mapped[obj.value] = obj.transform(data[prop])
          } catch (e) {
            mapped[obj.value] = data[prop]
          }
        }
      }
    }

    for (let key in this.mapping) {
      if (this.mapping.hasOwnProperty(key)) {
        this.body[key] = mapped[key]
      }
    }
  }

  static get mapping () {
    throw new Error('Mapping not implemented!')
  }

  static get model () {
    throw new Error('Model not implemented!')
  }

  save () {
    const doc = {
      index: Elastic.index,
      type: this.type,
      id: this.body.nr,
      body: this.body
    }

    return client.index(doc)
  }
}

export default Elastic
<|endoftext|>


<commit_before>var Crypto = {
util: {

	// Convert n to unsigned 32-bit integer
	u32: function (n) {
		return n >>> 0;
	},

	// Unsigned 32-bit addition
	add: function (m, n) {

		// Shortcut
		var u32 = this.u32;

		// If only two numbers given, add them
		if (arguments.length == 2)
			return u32(u32(m) + u32(n));

		// Else, add any number of arguments
		var result = arguments[0];
		for (var i = 1; i < arguments.length; i++)
			result = this.add(result, arguments[i]);
		return result;

	},

	// Unsigned 32-bit multiplication
	mult: function (m, n) {
		return this.add((n & 0xFFFF0000) * m,
		                (n & 0x0000FFFF) * m);
	},

	// Unsigned 32-bit greater than (>) comparison
	gt: function (m, n) {
		return this.u32(m) > this.u32(n);
	},

	// Unsigned 32-bit less than (<) comparison
	lt: function (m, n) {
		return this.u32(m) < this.u32(n);
	},

	// Bit-wise rotate left
	rotl: function (n, b) {
		return (n << b) | (n >>> (32 - b));
	},

	// Bit-wise rotate right
	rotr: function (n, b) {
		return (n << (32 - b)) | (n >>> b);
	},

	// Swap big-endian to little-endian and vice versa
	endian: function (n) {

		// If number given, swap endian
		if (n.constructor == Number) {
			return this.rotl(n,  8) & 0x00FF00FF |
			       this.rotl(n, 24) & 0xFF00FF00;
		}

		// Else, assume array and swap all items
		for (var i = 0; i < n.length; i++)
			n[i] = this.endian(n[i]);
		return n;

	},

	// Convert a string to a byte array
	string_bytes: function (str) {
		var bytes = [];
		for (var i = 0; i < str.length; i++)
			bytes.push(str.charCodeAt(i));
		return bytes;
	},

	// Convert a byte array to a string
	bytes_string: function (bytes) {
		var str = [];
		for (var i = 0; i < bytes.length; i++)
			str.push(String.fromCharCode(bytes[i]));
		return str.join("");
	},

	// Convert a string to big-endian 32-bit words
	string_words: function (str) {
		var words = [];
		for (var c = 0, b = 0; c < str.length; c++, b += 8)
			words[b >>> 5] |= str.charCodeAt(c) << (24 - b % 32);
		return words;
	},

	// Convert big-endian 32-bit words to a string
	words_string: function (words) {
		var str = [];
		for (var b = 0; b < words.length * 32; b += 8)
			str.push(String.fromCharCode((words[b >>> 5] >>> (24 - b % 32)) & 0xFF));
		return str.join("");
	},

	// Convert a byte array to big-endian 32-bits words
	bytes_words: function (bytes) {
		var words = [];
		for (var i = 0, b = 0; i < bytes.length; i++, b += 8)
			words[b >>> 5] |= bytes[i] << (24 - b % 32);
		return words;
	},

	// Convert big-endian 32-bit words to a byte array
	words_bytes: function (words) {
		var bytes = [];
		for (var b = 0; b < words.length * 32; b += 8)
			bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
		return bytes;
	},

	// Convert a byte array to a hex string
	bytes_hex: function (bytes) {
		var hex = [];
		for (var i = 0; i < bytes.length; i++) {
			hex.push((bytes[i] >>> 4).toString(16));
			hex.push((bytes[i] & 0xF).toString(16));
		}
		return hex.join("");
	},

	// Convert a hex string to a byte array
	hex_bytes: function (hex) {
		var bytes = [];
		for (var c = 0; c < hex.length; c += 2)
			bytes.push(parseInt(hex.substr(c, 2), 16));
		return bytes;
	}

}
};
<commit_msg>Implemented private scope.<commit_after>var Crypto = function () {

	return {
		util: {

			// Convert n to unsigned 32-bit integer
			u32: function (n) {
				return n >>> 0;
			},

			// Unsigned 32-bit addition
			add: function (m, n) {

				// Shortcut
				var u32 = this.u32;

				// If only two numbers given, add them
				if (arguments.length == 2)
					return u32(u32(m) + u32(n));

				// Else, add any number of arguments
				var result = arguments[0];
				for (var i = 1; i < arguments.length; i++)
					result = this.add(result, arguments[i]);
				return result;

			},

			// Unsigned 32-bit multiplication
			mult: function (m, n) {
				return this.add((n & 0xFFFF0000) * m,
				                (n & 0x0000FFFF) * m);
			},

			// Unsigned 32-bit greater than (>) comparison
			gt: function (m, n) {
				return this.u32(m) > this.u32(n);
			},

			// Unsigned 32-bit less than (<) comparison
			lt: function (m, n) {
				return this.u32(m) < this.u32(n);
			},

			// Bit-wise rotate left
			rotl: function (n, b) {
				return (n << b) | (n >>> (32 - b));
			},

			// Bit-wise rotate right
			rotr: function (n, b) {
				return (n << (32 - b)) | (n >>> b);
			},

			// Swap big-endian to little-endian and vice versa
			endian: function (n) {

				// If number given, swap endian
				if (n.constructor == Number) {
					return this.rotl(n,  8) & 0x00FF00FF |
					       this.rotl(n, 24) & 0xFF00FF00;
				}

				// Else, assume array and swap all items
				for (var i = 0; i < n.length; i++)
					n[i] = this.endian(n[i]);
				return n;

			},

			// Convert a string to a byte array
			string_bytes: function (str) {
				var bytes = [];
				for (var i = 0; i < str.length; i++)
					bytes.push(str.charCodeAt(i));
				return bytes;
			},

			// Convert a byte array to a string
			bytes_string: function (bytes) {
				var str = [];
				for (var i = 0; i < bytes.length; i++)
					str.push(String.fromCharCode(bytes[i]));
				return str.join("");
			},

			// Convert a string to big-endian 32-bit words
			string_words: function (str) {
				var words = [];
				for (var c = 0, b = 0; c < str.length; c++, b += 8)
					words[b >>> 5] |= str.charCodeAt(c) << (24 - b % 32);
				return words;
			},

			// Convert big-endian 32-bit words to a string
			words_string: function (words) {
				var str = [];
				for (var b = 0; b < words.length * 32; b += 8)
					str.push(String.fromCharCode((words[b >>> 5] >>> (24 - b % 32)) & 0xFF));
				return str.join("");
			},

			// Convert a byte array to big-endian 32-bits words
			bytes_words: function (bytes) {
				var words = [];
				for (var i = 0, b = 0; i < bytes.length; i++, b += 8)
					words[b >>> 5] |= bytes[i] << (24 - b % 32);
				return words;
			},

			// Convert big-endian 32-bit words to a byte array
			words_bytes: function (words) {
				var bytes = [];
				for (var b = 0; b < words.length * 32; b += 8)
					bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
				return bytes;
			},

			// Convert a byte array to a hex string
			bytes_hex: function (bytes) {
				var hex = [];
				for (var i = 0; i < bytes.length; i++) {
					hex.push((bytes[i] >>> 4).toString(16));
					hex.push((bytes[i] & 0xF).toString(16));
				}
				return hex.join("");
			},

			// Convert a hex string to a byte array
			hex_bytes: function (hex) {
				var bytes = [];
				for (var c = 0; c < hex.length; c += 2)
					bytes.push(parseInt(hex.substr(c, 2), 16));
				return bytes;
			}

		}
	};

}();
<|endoftext|>


<commit_before>const ini = require('ini');
const tap = require('tap');
const chalk = require('chalk');
const { beforeEach, test, mock } = tap;
const { stdout, stderr } = require('test-console');

const { NPMRC, NRMRC, REGISTRY, REGISTRIES } = require('./constants');

// ========== mock `fs` within helpers.js ==========

let mockedFiles = Object.create(null);

function readFileSync(path) {
  return mockedFiles[path];
}

function writeFileSync(path, content) {
  mockedFiles[path] = content;
}

function existsSync(path) {
  return path in mockedFiles;
}

const helpers = mock('./helpers.js', {
  fs: {
    existsSync,
    readFileSync,
    writeFileSync,
  },
  './process': {
    exit: () => console.error('process exit'),
  },
});

// ========== test cases ==========

beforeEach(() => {
  mockedFiles = Object.create(null);
  mockedFiles[NPMRC] = '';
  mockedFiles[NRMRC] = '';
});

test('geneDashLine', t => {
  const result1 = helpers.geneDashLine('taobao', 10);
  const result2 = helpers.geneDashLine('taobao', 1);
  t.equal(result1, ` ${chalk.dim('-----')} `, 'geneDashLine(taobao, 10) equal to ` ----- `');
  t.equal(result2, ` ${chalk.dim('-')} `, 'geneDashLine(taobao, 1) equal to ` - `');
  t.end();
});

test('getCurrentRegistry', async t => {
  const registry = ' https://registry.npmjs.org/';
  writeFileSync(NPMRC, ini.stringify({ [REGISTRY]: registry }));
  const currentRegistry = await helpers.getCurrentRegistry();
  t.equal(currentRegistry, registry, 'can get the current registry in use');
  t.end();
});

test('getRegistries', async t => {
  const name = 'fake name';
  const registry = 'https://registry.example.com/';
  writeFileSync(NRMRC, ini.stringify({ [name]: { registry } }));
  const registries = await helpers.getRegistries();
  t.equal(Object.keys(registries).includes(name), true, 'can get all registries');
  t.end();
});

test('readFile', async t => {
  const content = 'hello nrm';
  writeFileSync(NRMRC, ini.stringify({ content: content }));
  const result1 = await helpers.readFile(NRMRC);
  const result2 = await helpers.readFile('file not exist');
  t.equal(result1.content, content, 'can get the file content');
  t.same(result2, Object.create(null), 'can get an empty object when file is not exist');
  t.end();
});

test('writeFile', async t => {
  const content = { nrm: 'nrm is great' };
  await helpers.writeFile(NRMRC, { content });
  const result = await helpers.readFile(NRMRC);
  t.same(result.content, content, 'can write content to the file');
  t.end();
});

test('isLowerCaseEqual', t => {
  const result1 = helpers.isLowerCaseEqual('taobao', 'TAOBAO');
  const result2 = helpers.isLowerCaseEqual('jd', 'tb');
  const result3 = helpers.isLowerCaseEqual('taobao', '');
  const result4 = helpers.isLowerCaseEqual('', '');
  t.equal(result1, true, '`taobao` is considered equal to `TAOBAO`');
  t.equal(result2, false, '`jd` is not equal to `tb`');
  t.equal(result3, false, '`taobao` is not equal to an empty string');
  t.equal(result4, true, 'two empty strings are considered equal');
  t.end();
});

test('printError', t => {
  const error = 'an error';
  const output = stderr.inspectSync(() => helpers.printError(error));
  t.same(output, printLineByLine(chalk.bgRed(' ERROR ') + ' ' + chalk.red(error)), 'can print an error message');
  t.end();
});

test('printSuccess', t => {
  const message = 'hello nrm';
  const output = stdout.inspectSync(() => helpers.printSuccess(message));
  t.same(output, printLineByLine(chalk.bgGreenBright(' SUCCESS ') + ' ' + message), 'can print a success message');
  t.end();
});

test('printMessages', t => {
  const output = stdout.inspectSync(() => helpers.printMessages(['hello', 'nrm']));
  t.same(output, printLineByLine('hello', 'nrm'), 'can print a group messages');
  t.end();
});

test('isRegistryNotFound', async t => {
  const unknown = 'unknown';
  writeFileSync(NPMRC, ini.stringify(REGISTRIES));
  const result1 = await helpers.isRegistryNotFound(unknown, false);
  const result2 = await helpers.isRegistryNotFound('npm', false);
  t.ok(result1, 'can return true when registry is not found');
  t.notOk(result2, 'can return false when registry is exist');
  t.end();
});

test('isInternalRegistry', async t => {
  const name = 'custom name';
  const registry = 'https://registry.example.com/';
  writeFileSync(NPMRC, ini.stringify(REGISTRIES));
  writeFileSync(NRMRC, ini.stringify({ [name]: registry }));
  const result1 = await helpers.isInternalRegistry(name);
  const result2 = await helpers.isInternalRegistry('npm');
  t.notOk(result1, 'can return false when registry is customized');
  t.ok(result2, 'can return true when registry is internal');
  t.end();
});

test('exit', async t => {
  const error = 'error message';
  const [errorMessage, exitMessage] = await stderr.inspectSync(() => helpers.exit(error));
  t.ok(errorMessage.includes(error), 'can print error message');
  t.ok(exitMessage.includes('process exit'), 'process will exit after print error message');
  t.end();
});

function printLineByLine(...lines) {
  return lines.map(line => line + '\n');
}
<commit_msg>remove write npmrc<commit_after>const ini = require('ini');
const tap = require('tap');
const chalk = require('chalk');
const { beforeEach, test, mock } = tap;
const { stdout, stderr } = require('test-console');

const { NPMRC, NRMRC, REGISTRY } = require('./constants');

// ========== mock `fs` within helpers.js ==========

let mockedFiles = Object.create(null);

function readFileSync(path) {
  return mockedFiles[path];
}

function writeFileSync(path, content) {
  mockedFiles[path] = content;
}

function existsSync(path) {
  return path in mockedFiles;
}

const helpers = mock('./helpers.js', {
  fs: {
    existsSync,
    readFileSync,
    writeFileSync,
  },
  './process': {
    exit: () => console.error('process exit'),
  },
});

// ========== test cases ==========

beforeEach(() => {
  mockedFiles = Object.create(null);
  mockedFiles[NPMRC] = '';
  mockedFiles[NRMRC] = '';
});

test('geneDashLine', t => {
  const result1 = helpers.geneDashLine('taobao', 10);
  const result2 = helpers.geneDashLine('taobao', 1);
  t.equal(result1, ` ${chalk.dim('-----')} `, 'geneDashLine(taobao, 10) equal to ` ----- `');
  t.equal(result2, ` ${chalk.dim('-')} `, 'geneDashLine(taobao, 1) equal to ` - `');
  t.end();
});

test('getCurrentRegistry', async t => {
  const registry = ' https://registry.npmjs.org/';
  writeFileSync(NPMRC, ini.stringify({ [REGISTRY]: registry }));
  const currentRegistry = await helpers.getCurrentRegistry();
  t.equal(currentRegistry, registry, 'can get the current registry in use');
  t.end();
});

test('getRegistries', async t => {
  const name = 'fake name';
  const registry = 'https://registry.example.com/';
  writeFileSync(NRMRC, ini.stringify({ [name]: { registry } }));
  const registries = await helpers.getRegistries();
  t.equal(Object.keys(registries).includes(name), true, 'can get all registries');
  t.end();
});

test('readFile', async t => {
  const content = 'hello nrm';
  writeFileSync(NRMRC, ini.stringify({ content: content }));
  const result1 = await helpers.readFile(NRMRC);
  const result2 = await helpers.readFile('file not exist');
  t.equal(result1.content, content, 'can get the file content');
  t.same(result2, Object.create(null), 'can get an empty object when file is not exist');
  t.end();
});

test('writeFile', async t => {
  const content = { nrm: 'nrm is great' };
  await helpers.writeFile(NRMRC, { content });
  const result = await helpers.readFile(NRMRC);
  t.same(result.content, content, 'can write content to the file');
  t.end();
});

test('isLowerCaseEqual', t => {
  const result1 = helpers.isLowerCaseEqual('taobao', 'TAOBAO');
  const result2 = helpers.isLowerCaseEqual('jd', 'tb');
  const result3 = helpers.isLowerCaseEqual('taobao', '');
  const result4 = helpers.isLowerCaseEqual('', '');
  t.equal(result1, true, '`taobao` is considered equal to `TAOBAO`');
  t.equal(result2, false, '`jd` is not equal to `tb`');
  t.equal(result3, false, '`taobao` is not equal to an empty string');
  t.equal(result4, true, 'two empty strings are considered equal');
  t.end();
});

test('printError', t => {
  const error = 'an error';
  const output = stderr.inspectSync(() => helpers.printError(error));
  t.same(output, printLineByLine(chalk.bgRed(' ERROR ') + ' ' + chalk.red(error)), 'can print an error message');
  t.end();
});

test('printSuccess', t => {
  const message = 'hello nrm';
  const output = stdout.inspectSync(() => helpers.printSuccess(message));
  t.same(output, printLineByLine(chalk.bgGreenBright(' SUCCESS ') + ' ' + message), 'can print a success message');
  t.end();
});

test('printMessages', t => {
  const output = stdout.inspectSync(() => helpers.printMessages(['hello', 'nrm']));
  t.same(output, printLineByLine('hello', 'nrm'), 'can print a group messages');
  t.end();
});

test('isRegistryNotFound', async t => {
  const unknown = 'unknown';
  const name = 'custom name';
  const registry = 'https://registry.example.com/';
  writeFileSync(NRMRC, ini.stringify({ [name]: registry }));
  const result1 = await helpers.isRegistryNotFound(unknown, false);
  const result2 = await helpers.isRegistryNotFound(name, false);
  t.ok(result1, 'can return true when registry is not found');
  t.notOk(result2, 'can return false when registry is exist');
  t.end();
});

test('isInternalRegistry', async t => {
  const name = 'custom name';
  const registry = 'https://registry.example.com/';
  writeFileSync(NRMRC, ini.stringify({ [name]: registry }));
  const result1 = await helpers.isInternalRegistry(name);
  const result2 = await helpers.isInternalRegistry('npm');
  t.notOk(result1, 'can return false when registry is customized');
  t.ok(result2, 'can return true when registry is internal');
  t.end();
});

test('exit', async t => {
  const error = 'error message';
  const [errorMessage, exitMessage] = await stderr.inspectSync(() => helpers.exit(error));
  t.ok(errorMessage.includes(error), 'can print error message');
  t.ok(exitMessage.includes('process exit'), 'process will exit after print error message');
  t.end();
});

function printLineByLine(...lines) {
  return lines.map(line => line + '\n');
}
<|endoftext|>


<commit_before>var events = require('events')
var util = require('util')

function Plan(planned) {
  this._planned = planned || 0
  events.EventEmitter.call(this)
}
util.inherits(Plan, events.EventEmitter)

Plan.prototype.inc = function(times) {
  times = times || 1
  this._planned += times
}

Plan.prototype.done = function(label, arg) {
  if ( this._planned == 0 ) return
  this._planned--
  this.emit('done::' + label, arg)
  if ( this._planned === 0 ) this.emit('done')
}

module.exports = Plan<commit_msg>fixing a bug because callbacks get called twice when there is a last labeled planned task<commit_after>var events = require('events')
var util = require('util')

function Plan(planned) {
  this._planned = planned || 0
  events.EventEmitter.call(this)
}
util.inherits(Plan, events.EventEmitter)

Plan.prototype.inc = function(times) {
  times = times || 1
  this._planned += times
}

Plan.prototype.done = function(label, arg) {
  if ( this._planned == 0 ) return
  this._planned--
  if (label)
    return this.emit('done::' + label, arg)
  if ( this._planned === 0 ) this.emit('done')
}

module.exports = Plan<|endoftext|>


<commit_before>describe("Splash Page", function() {

  beforeEach(function() {
    jasmine.getFixtures().fixturesPath = '../www/';
    jasmine.getFixtures().load('index.html');
  });

  describe ('container div', function(){
    it('should have a div with container class', function() {
      expect(document.getElementsByClassName('container')[0]).toBeInDOM();
    });

    it('should have a div with container class', function() {
      expect(document.getElementsByClassName('container')[0]).toBeInDOM();
    });

  });
});

  // describe("when song has been paused", function() {
  //   beforeEach(function() {
  //     player.play(song);
  //     player.pause();
  //   });

  //   it("should indicate that the song is currently paused", function() {
  //     expect(player.isPlaying).toBeFalsy();

  //     // demonstrates use of 'not' with a custom matcher
  //     expect(player).not.toBePlaying(song);
  //   });

  //   it("should be possible to resume", function() {
  //     player.resume();
  //     expect(player.isPlaying).toBeTruthy();
  //     expect(player.currentlyPlayingSong).toEqual(song);
  //   });
  // });

  // // demonstrates use of spies to intercept and test method calls
  // it("tells the current song if the user has made it a favorite", function() {
  //   spyOn(song, 'persistFavoriteStatus');

  //   player.play(song);
  //   player.makeFavorite();

  //   expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
  // });

  // //demonstrates use of expected exceptions
  // describe("#resume", function() {
  //   it("should throw an exception if song is already playing", function() {
  //     player.play(song);

  //     expect(function() {
  //       player.resume();
  //     }).toThrowError("song is already playing");
  //   });

<commit_msg>Get rid of duplicate test in AppSpec.js<commit_after>describe("Splash Page", function() {

  beforeEach(function() {
    jasmine.getFixtures().fixturesPath = '../www/';
    jasmine.getFixtures().load('index.html');
  });

  describe ('container div', function(){
    it('should have a div with container class', function() {
      expect(document.getElementsByClassName('container')[0]).toBeInDOM();
    });
  });
});

  // describe("when song has been paused", function() {
  //   beforeEach(function() {
  //     player.play(song);
  //     player.pause();
  //   });

  //   it("should indicate that the song is currently paused", function() {
  //     expect(player.isPlaying).toBeFalsy();

  //     // demonstrates use of 'not' with a custom matcher
  //     expect(player).not.toBePlaying(song);
  //   });

  //   it("should be possible to resume", function() {
  //     player.resume();
  //     expect(player.isPlaying).toBeTruthy();
  //     expect(player.currentlyPlayingSong).toEqual(song);
  //   });
  // });

  // // demonstrates use of spies to intercept and test method calls
  // it("tells the current song if the user has made it a favorite", function() {
  //   spyOn(song, 'persistFavoriteStatus');

  //   player.play(song);
  //   player.makeFavorite();

  //   expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
  // });

  // //demonstrates use of expected exceptions
  // describe("#resume", function() {
  //   it("should throw an exception if song is already playing", function() {
  //     player.play(song);

  //     expect(function() {
  //       player.resume();
  //     }).toThrowError("song is already playing");
  //   });

<|endoftext|>


<commit_before>/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.EffectComposer = function ( renderer, renderTarget ) {

	this.renderer = renderer;
  this.domElement = this.renderer.domElement;

	if ( renderTarget === undefined ) {

		var pixelRatio = renderer.getPixelRatio();

		var width  = Math.floor( renderer.context.canvas.width  / pixelRatio ) || 1;
		var height = Math.floor( renderer.context.canvas.height / pixelRatio ) || 1;
		var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };

		renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );

	}

	this.renderTarget1 = renderTarget;
	this.renderTarget2 = renderTarget.clone();

	this.writeBuffer = this.renderTarget1;
	this.readBuffer = this.renderTarget2;

	this.passes = [];

	if ( THREE.CopyShader === undefined )
		console.error( "THREE.EffectComposer relies on THREE.CopyShader" );

	this.copyPass = new THREE.ShaderPass( THREE.CopyShader );

};

THREE.EffectComposer.prototype = {

	swapBuffers: function() {

		var tmp = this.readBuffer;
		this.readBuffer = this.writeBuffer;
		this.writeBuffer = tmp;

	},

	addPass: function ( pass ) {

		this.passes.push( pass );

	},

	insertPass: function ( pass, index ) {

		this.passes.splice( index, 0, pass );

	},

	render: function ( delta ) {

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

		var maskActive = false;

		var pass, i, il = this.passes.length;

		for ( i = 0; i < il; i ++ ) {

			pass = this.passes[ i ];

			if ( ! pass.enabled ) continue;

			pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive );

			if ( pass.needsSwap ) {

				if ( maskActive ) {

					var context = this.renderer.context;

					context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );

					this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta );

					context.stencilFunc( context.EQUAL, 1, 0xffffffff );

				}

				this.swapBuffers();

			}

			if ( pass instanceof THREE.MaskPass ) {

				maskActive = true;

			} else if ( pass instanceof THREE.ClearMaskPass ) {

				maskActive = false;

			}

		}

	},

	reset: function ( renderTarget ) {

		if ( renderTarget === undefined ) {

			renderTarget = this.renderTarget1.clone();

			var pixelRatio = this.renderer.getPixelRatio();

			renderTarget.setSize(
				Math.floor( this.renderer.context.canvas.width  / pixelRatio ),
				Math.floor( this.renderer.context.canvas.height / pixelRatio )
			);

		}

		this.renderTarget1.dispose();
		this.renderTarget1 = renderTarget;
		this.renderTarget2.dispose();
		this.renderTarget2 = renderTarget.clone();

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

	},

	setSize: function ( width, height ) {

		this.renderTarget1.setSize( width, height );
		this.renderTarget2.setSize( width, height );

	},

  getSize: function () {
    return this.renderer.getSize();
  },

  setScissor: function(x, y, width, height) {
    return this.renderer.setScissor(x, y, width, height);
  },
  setScissorTest: function( boolean ) {
    return this.renderer.setScissorTest( boolean );
  },
  setViewport: function( x, y, width, height ) {
    return this.renderer.setViewport( x, y, width, height );
  },
	clear: function ( color, depth, stencil ) {
    return this.renderer.clear( color, depth, stencil );
  }

};
<commit_msg>Added functions for setting/getting pixel ratio in composer<commit_after>/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.EffectComposer = function ( renderer, renderTarget ) {

	this.renderer = renderer;
  this.domElement = this.renderer.domElement;

	if ( renderTarget === undefined ) {

		var pixelRatio = renderer.getPixelRatio();

		var width  = Math.floor( renderer.context.canvas.width  / pixelRatio ) || 1;
		var height = Math.floor( renderer.context.canvas.height / pixelRatio ) || 1;
		var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };

		renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );

	}

	this.renderTarget1 = renderTarget;
	this.renderTarget2 = renderTarget.clone();

	this.writeBuffer = this.renderTarget1;
	this.readBuffer = this.renderTarget2;

	this.passes = [];

	if ( THREE.CopyShader === undefined )
		console.error( "THREE.EffectComposer relies on THREE.CopyShader" );

	this.copyPass = new THREE.ShaderPass( THREE.CopyShader );

};

THREE.EffectComposer.prototype = {

	swapBuffers: function() {

		var tmp = this.readBuffer;
		this.readBuffer = this.writeBuffer;
		this.writeBuffer = tmp;

	},

	addPass: function ( pass ) {

		this.passes.push( pass );

	},

	insertPass: function ( pass, index ) {

		this.passes.splice( index, 0, pass );

	},

	render: function ( delta ) {

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

		var maskActive = false;

		var pass, i, il = this.passes.length;

		for ( i = 0; i < il; i ++ ) {

			pass = this.passes[ i ];

			if ( ! pass.enabled ) continue;

			pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive );

			if ( pass.needsSwap ) {

				if ( maskActive ) {

					var context = this.renderer.context;

					context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );

					this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta );

					context.stencilFunc( context.EQUAL, 1, 0xffffffff );

				}

				this.swapBuffers();

			}

			if ( pass instanceof THREE.MaskPass ) {

				maskActive = true;

			} else if ( pass instanceof THREE.ClearMaskPass ) {

				maskActive = false;

			}

		}

	},

	reset: function ( renderTarget ) {

		if ( renderTarget === undefined ) {

			renderTarget = this.renderTarget1.clone();

			var pixelRatio = this.renderer.getPixelRatio();

			renderTarget.setSize(
				Math.floor( this.renderer.context.canvas.width  / pixelRatio ),
				Math.floor( this.renderer.context.canvas.height / pixelRatio )
			);

		}

		this.renderTarget1.dispose();
		this.renderTarget1 = renderTarget;
		this.renderTarget2.dispose();
		this.renderTarget2 = renderTarget.clone();

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

	},

	setSize: function ( width, height ) {

		this.renderTarget1.setSize( width, height );
		this.renderTarget2.setSize( width, height );

	},

  getSize: function () {
    return this.renderer.getSize();
  },

  getPixelRatio: function () {
    return this.renderer.getPixelRatio();
  },
  setPixelRatio: function ( value ) {
    return this.renderer.setPixelRatio(value);
  },

  setScissor: function(x, y, width, height) {
    return this.renderer.setScissor(x, y, width, height);
  },
  setScissorTest: function( boolean ) {
    return this.renderer.setScissorTest( boolean );
  },
  setViewport: function( x, y, width, height ) {
    return this.renderer.setViewport( x, y, width, height );
  },
	clear: function ( color, depth, stencil ) {
    return this.renderer.clear( color, depth, stencil );
  }

};
<|endoftext|>


<commit_before>const Promise = require("bluebird")
const wrapp = require("./wrapp")
const boot = require("./boot")
const co = Promise.coroutine

function Task(fly) {
	// construct shape
	this._ = {files: [], globs: [], prevs: []}
	// attach parent fns to Task
	this.parallel = fly.parallel
	this.serial = fly.serial
	this.start = fly.start
	this.emit = fly.emit
	// attach `fly.plugins` to prototype
	for (const k in fly.plugins) {
		this[k] = fly.plugins[k].bind(this)
	}
	// return chained methods + shared
	return boot(this)
}

Task.prototype.exec = function(fn, opts, data) {
	// cache ref to `fly.tasks[].data` values
	this._ = data
	return fn.call(this, this, opts)
}

Task.prototype.run = co(function * (opts, func) {
	return yield wrapp(opts, func).call(this)
});

Task.prototype.source = require("./task/source");
Task.prototype.target = require("./task/target");

module.exports = Task
<commit_msg>add '$' utils to Task (shared with plugins)<commit_after>const Promise = require("bluebird")
const wrapp = require("./wrapp")
const util = require("./utils")
const boot = require("./boot")
const co = Promise.coroutine

function Task(fly) {
	// construct shape
	this.$ = util
	this._ = {files: [], globs: [], prevs: []}
	// attach parent fns to Task
	this.parallel = fly.parallel
	this.serial = fly.serial
	this.start = fly.start
	this.emit = fly.emit
	// attach `fly.plugins` to prototype
	for (const k in fly.plugins) {
		this[k] = fly.plugins[k].bind(this)
	}
	// return chained methods + shared
	return boot(this)
}

Task.prototype.exec = function(fn, opts, data) {
	// cache ref to `fly.tasks[].data` values
	this._ = data
	return fn.call(this, this, opts)
}

Task.prototype.run = co(function * (opts, func) {
	return yield wrapp(opts, func).call(this)
});

Task.prototype.source = require("./task/source");
Task.prototype.target = require("./task/target");

module.exports = Task
<|endoftext|>