<commit_before>import MultiModelExtensionBase from 'Viewer.MultiModelExtensionBase'
import DualExtensionId from 'Viewing.Extension.DualViewer'

import $ from 'jquery';
import 'jstree/dist/jstree.min';
import 'jstree/dist/themes/default/style.css';
import React from 'react'

class TreeExtension extends MultiModelExtensionBase {

  constructor(viewer, options) {

    super(viewer, options)

    this.state = {
      dualExtension: null
    }

    this.render = this.render.bind(this)

    this.react = options.react

    this.viewer = viewer

    this.launchViewer = this.launchViewer.bind(this)
  }

  static get ExtensionId() {

    return 'Viewing.Extension.Tree'
  }

  load() {

    this.react.setState({
      activeProperty: '',
      showLoader: true,
      disabled: true,
      items: [],
      data: []
    }).then(() => {

      this.react.pushRenderExtension(this)

      const model = this.viewer.activeModel ||
        this.viewer.model

      if (model) {

        this.loadTree(this.viewer)
      }

    })

    console.log('Viewing.Extension.Tree loaded')

    return true
  }

  unload() {

    console.log('Viewing.Extension.Tree unloaded')

    super.unload()

    return true
  }

  /////////////////////////////////////////////////////////
  //
  //
  /////////////////////////////////////////////////////////
  onModelActivated(event) {

    if (event.source !== 'model.loaded') {

      this.loadTree(event.model)
    }
  }

  /////////////////////////////////////////////////////////
  //
  //
  /////////////////////////////////////////////////////////
  onGeometryLoaded(event) {

    this.loadTree(event.target)
  }

  loadTree(viewer) {

    var haveBIM360Hub = false;

    $('#autodeskTree').jstree({
        'core': {
          'themes': {
            "icons": true
          },
          'multiple': false,
          'data': {
            "url": "api/tree",
            "dataType": "json",
            'multiple': true,
            'data': function(node) {
              $('#autodeskTree').jstree(true).toggle_node(node);
              return {
                "id": node.id
              };
            },
            "success": function(nodes) {
              nodes.forEach(function(n) {
                if (n.type === 'bim360Hubs' && n.id.indexOf('b.') > 0)
                  haveBIM360Hub = true;
              })
            },
          }
        },
        'types': {
          'default': {
            'icon': 'glyphicon glyphicon-question-sign'
          },
          '#': {
            'icon': 'glyphicon glyphicon-user'
          },
          'hubs': {
            'icon': '/resources//img/a360hub.png'
          },
          'personalHub': {
            'icon': '/resources//img/a360hub.png'
          },
          'bim360Hubs': {
            'icon': '/resources//img/bim360hub.png'
          },
          'bim360projects': {
            'icon': '/resources//img/bim360project.png'
          },
          'a360projects': {
            'icon': '/resources//img/a360project.png'
          },
          'items': {
            'icon': 'glyphicon glyphicon-file'
          },
          'folders': {
            'icon': 'glyphicon glyphicon-folder-open'
          },
          'versions': {
            'icon': 'glyphicon glyphicon-time'
          }
        },
        "plugins": ["types", "state", "sort"],
        "state": {
          "key": "autodeskTree"
        }
      })
      .bind("activate_node.jstree", (evt, data) => {
        if (data != null && data.node != null && data.node.type == 'versions') {

          if (data.node.id === 'not_available') {

            alert('No viewable available for this version');

            return;

          }

          this.launchViewer(data.node.id, viewer)

        }
      })
  }

  async launchViewer(urn, viewer) {

    const lmvProxy = 'lmv-proxy-3legged'

    var doc = await this.loadDocument(urn)

    var path = this.getViewablePath(doc)

    var dualExt = viewer.getExtension("Viewing.Extension.DualViewer");

    // Function to get DualViewer to load new Document.

    viewer.impl.unloadCurrentModel()

    Autodesk.Viewing.setEndpointAndApi(
      `${window.location.origin}/${lmvProxy}`,
      'modelDerivativeV2')

//    Autodesk.Viewing.Private.memoryOptimizedSvfLoading = true

    dualExt.newVersionModel(doc)

    viewer.loadModel(path)
  }

   /////////////////////////////////////////////////////////
    // Initialize viewer environment
    //
    /////////////////////////////////////////////////////////
    initialize(options) {

      return new Promise((resolve, reject) => {

        Autodesk.Viewing.Initializer(options, () => {

          resolve()

        }, (error) => {

          reject(error)
        })
      })
    }

  /////////////////////////////////////////////////////////
  // Load a document from URN
  //
  /////////////////////////////////////////////////////////
  loadDocument(urn) {

    return new Promise((resolve, reject) => {

      const paramUrn = !urn.startsWith('urn:') ? 'urn:' + urn : urn

      Autodesk.Viewing.Document.load(paramUrn, (doc) => {

        resolve(doc)

      }, (error) => {

        reject(error)
      })
    })
  }

  /////////////////////////////////////////////////////////
  // Return viewable path: first 3d or 2d item by default
  //
  /////////////////////////////////////////////////////////
  getViewablePath(doc, pathIdx = 0, roles = ['3d', '2d']) {

    const rootItem = doc.getRootItem()

    const roleArray = [...roles]

    let items = []

    roleArray.forEach((role) => {

      items = [...items,
        ...Autodesk.Viewing.Document.getSubItemsWithProperties(
          rootItem, {
            type: 'geometry',
            role
          }, true)
      ]
    })

    if (!items.length || pathIdx > items.length) {

      return null
    }

    return doc.getViewablePath(items[pathIdx])
  }

  render() {

    return (

      < div id = "autodeskTree" >
      < /div >

    )
  }
}

Autodesk.Viewing.theExtensionManager.registerExtension(
  TreeExtension.ExtensionId,
  TreeExtension)<commit_msg>clean up of tree extension<commit_after>import MultiModelExtensionBase from 'Viewer.MultiModelExtensionBase'
import DualExtensionId from 'Viewing.Extension.DualViewer'

import $ from 'jquery';
import 'jstree/dist/jstree.min';
import 'jstree/dist/themes/default/style.css';
import React from 'react'

class TreeExtension extends MultiModelExtensionBase {

  constructor(viewer, options) {

    super(viewer, options)

    this.state = {
      dualExtension: null
    }

    this.render = this.render.bind(this)

    this.react = options.react

    this.viewer = viewer

    this.launchViewer = this.launchViewer.bind(this)
  }

  static get ExtensionId() {

    return 'Viewing.Extension.Tree'
  }

  load() {

    this.react.setState({
      activeProperty: '',
      showLoader: true,
      disabled: true,
      items: [],
      data: []
    }).then(() => {

      this.react.pushRenderExtension(this)

      const model = this.viewer.activeModel ||
        this.viewer.model

      // if (model) {

        this.loadTree(this.viewer)
      // }

    })

    console.log('Viewing.Extension.Tree loaded')

    return true
  }

  unload() {

    console.log('Viewing.Extension.Tree unloaded')

    super.unload()

    return true
  }

  /////////////////////////////////////////////////////////
  //
  //
  /////////////////////////////////////////////////////////
  // onModelActivated(event) {

  //   if (event.source !== 'model.loaded') {

  //     this.loadTree(event.model)
  //   }
  // }

  // /////////////////////////////////////////////////////////
  // //
  // //
  // /////////////////////////////////////////////////////////
  // onGeometryLoaded(event) {

  //   this.loadTree(event.target)
  // }

  loadTree(viewer) {

    var haveBIM360Hub = false;

    $('#autodeskTree').jstree({
        'core': {
          'themes': {
            "icons": true
          },
          'multiple': false,
          'data': {
            "url": "api/tree",
            "dataType": "json",
            'multiple': true,
            'data': function(node) {
              $('#autodeskTree').jstree(true).toggle_node(node);
              return {
                "id": node.id
              };
            },
            "success": function(nodes) {
              nodes.forEach(function(n) {
                if (n.type === 'bim360Hubs' && n.id.indexOf('b.') > 0)
                  haveBIM360Hub = true;
              })
            },
          }
        },
        'types': {
          'default': {
            'icon': 'glyphicon glyphicon-question-sign'
          },
          '#': {
            'icon': 'glyphicon glyphicon-user'
          },
          'hubs': {
            'icon': '/resources//img/a360hub.png'
          },
          'personalHub': {
            'icon': '/resources//img/a360hub.png'
          },
          'bim360Hubs': {
            'icon': '/resources//img/bim360hub.png'
          },
          'bim360projects': {
            'icon': '/resources//img/bim360project.png'
          },
          'a360projects': {
            'icon': '/resources//img/a360project.png'
          },
          'items': {
            'icon': 'glyphicon glyphicon-file'
          },
          'folders': {
            'icon': 'glyphicon glyphicon-folder-open'
          },
          'versions': {
            'icon': 'glyphicon glyphicon-time'
          }
        },
        "plugins": ["types", "state", "sort"],
        "state": {
          "key": "autodeskTree"
        }
      })
      .bind("activate_node.jstree", (evt, data) => {
        if (data != null && data.node != null && data.node.type == 'versions') {

          if (data.node.id === 'not_available') {

            alert('No viewable available for this version');

            return;

          }

        Autodesk.Viewing.setEndpointAndApi(
          `${window.location.origin}/lmv-proxy-3legged`,
          'modelDerivativeV2')

        this.launchViewer(data.node.id, viewer)

        }
      })
  }

  async launchViewer(urn, viewer) {

    viewer.impl.unloadCurrentModel()

    var doc = await this.loadDocument(urn)

    var path = this.getViewablePath(doc)

    //var dualExt = viewer.getExtension("Viewing.Extension.DualViewer");

    // Function to get DualViewer to load new Document.

    //dualExt.newVersionModel(doc)

    viewer.loadModel(path)
  }

   /////////////////////////////////////////////////////////
    // Initialize viewer environment
    //
    /////////////////////////////////////////////////////////
    initialize(options) {

      return new Promise((resolve, reject) => {

        Autodesk.Viewing.Initializer(options, () => {

          resolve()

        }, (error) => {

          reject(error)
        })
      })
    }

  /////////////////////////////////////////////////////////
  // Load a document from URN
  //
  /////////////////////////////////////////////////////////
  loadDocument(urn) {

    return new Promise((resolve, reject) => {

      const paramUrn = !urn.startsWith('urn:') ? 'urn:' + urn : urn

      Autodesk.Viewing.Document.load(paramUrn, (doc) => {

        resolve(doc)

      }, (error) => {

        reject(error)
      })
    })
  }

  /////////////////////////////////////////////////////////
  // Return viewable path: first 3d or 2d item by default
  //
  /////////////////////////////////////////////////////////
  getViewablePath(doc, pathIdx = 0, roles = ['3d', '2d']) {

    const rootItem = doc.getRootItem()

    const roleArray = [...roles]

    let items = []

    roleArray.forEach((role) => {

      items = [...items,
        ...Autodesk.Viewing.Document.getSubItemsWithProperties(
          rootItem, {
            type: 'geometry',
            role
          }, true)
      ]
    })

    if (!items.length || pathIdx > items.length) {

      return null
    }

    return doc.getViewablePath(items[pathIdx])
  }

  render() {

    return (

      < div id = "autodeskTree" >
      < /div >

    )
  }
}

Autodesk.Viewing.theExtensionManager.registerExtension(
  TreeExtension.ExtensionId,
  TreeExtension)<|endoftext|>


<commit_before>/* Fleet.js
KC3改 Fleet Object

Contains summary information about a fleet and its 6 ships
{
	"api_member_id":18066975,
	"api_id":1,
	"api_name":"111",
	"api_name_id":"136558260",
	"api_mission":[ 0, 0, 0, 0 ],
	"api_flagship":"0",
	"api_ship":[ 76, -1, -1, -1, -1, -1 ]
}
*/
(function(){
	"use strict";

	window.KC3Fleet = function( data ){
		this.active = false;
		this.fastFleet = true;
		this.name = "";
		this.ships = [ -1, -1, -1, -1, -1, -1 ];
		this.mission = [ 0, 0, 0, 0 ];
	};

	KC3Fleet.prototype.update = function( data ){
		if(typeof data.api_member_id != "undefined"){
			this.active = true;
			this.name = data.api_name;
			this.ships = data.api_ship;
			this.mission = data.api_mission;
			if(data.api_id > 1){
				if(this.mission[0] > 0){
					KC3TimerManager.exped( data.api_id ).activate(
						this.mission[2],
						this.ship(0).masterId,
						this.mission[1]
					);
				}else{
					KC3TimerManager.exped( data.api_id ).deactivate();
				}
			}
		}
	};

	KC3Fleet.prototype.defineFormatted = function( data ){
		this.active = data.active;
		this.name = data.name;
		this.ships = data.ships;
		this.mission = data.mission;
		return this;
	};

	KC3Fleet.prototype.ship = function( slot ){
		return KC3ShipManager.get( this.ships[slot] );
	};

	KC3Fleet.prototype.countShips = function(){
		return $.grep(this.ships, function(shipId){ return shipId>-1; }).length;
	};

	KC3Fleet.prototype.resetAfterHp = function(){
		for(var i = 0; i < this.countShips(); i++) {
			this.ship(i).resetAfterHp();
		}
	};

	KC3Fleet.prototype.clearNonFlagShips = function(){
		this.ships[1] = this.ships[2] = this.ships[3] = this.ships[4] = this.ships[5] = -1;
	};

	KC3Fleet.prototype.totalLevel = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){return self.ship(x).level;})
			.reduce(function(x,y){return x+y;});
	};

	KC3Fleet.prototype.countDrums = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){return self.ship(x).countDrums();})
			.reduce(function(x,y){return x+y;});
	};

	KC3Fleet.prototype.countShipsWithDrums = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){return self.ship(x).countDrums()>0;})
			.reduce(function(x,y){return x+y;});
	};

	KC3Fleet.prototype.averageLevel = function(){
		return this.totalLevel() / this.countShips();
	};

	KC3Fleet.prototype.fighterPower = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){return self.ship(x).fighterPower();})
			.reduce(function(x,y){return x+y;});
	};

	KC3Fleet.prototype.speed = function(){
		this.fastFleet = true;
		var i = 0;
		while(this.fastFleet && i < 6) {
			if(this.ships[i] > -1) {
				this.fastFleet = this.fastFleet && this.ship(i).isFast();
			}
		}
		return (this.fastFleet) ? KC3Meta.term("SpeedFast") : KC3Meta.term("SpeedSlow");
	};

	KC3Fleet.prototype.qualifyingExpeditions = function(){

	};

	KC3Fleet.prototype.compileStats = function(){

	};

	KC3Fleet.prototype.canCombineCarrier = function(){

	};

	KC3Fleet.prototype.canCombineSurface = function(){

	};

	KC3Fleet.prototype.supportPower = function(){

	};

	KC3Fleet.prototype.eLoS = function(){
		switch(ConfigManager.elosFormula){
			case 1: return this.eLos1();
			case 2: return this.eLos2();
			default: return this.eLos3();
		}
	};

	/* LoS : Fitted
	Sum of all Ship LoS in the fleet WITH their equipment
	------------------------------------*/
	KC3Fleet.prototype.eLos1 = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){
				return (!self.ship(x).didFlee)? self.ship(x).ls[0] : 0;
			})
			.reduce(function(x,y){return x+y;});
	};

	/* LoS : "Old Formula"
	= Recon LoS×2 + Radar LoS + v(Fleet total LoS - Recon LoS - Radar LoS)
	------------------------------------*/
	KC3Fleet.prototype.eLos2 = function(){
		var PlaneLoS = 0;
		var RadarLoS = 0;

		function ConsiderShip(shipData){
			if(shipData.rosterId === 0) return false;
			if(shipData.didFlee) return false;
			Array.apply(null, {length: 4})
				.map(Number.call, Number)
				.forEach(function(x){ if(shipData.items[x]>-1) { ConsiderEquipment(shipData.equipment(x)); }});
		}

		function ConsiderEquipment(itemData){
			if(itemData.itemId === 0) return false;
			if( itemData.master().api_type[1] == 7){ PlaneLoS += itemData.master().api_saku; }
			if( itemData.master().api_type[1] == 8){ RadarLoS += itemData.master().api_saku; }
		}

		var self = this;
		Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.forEach(function(x){ConsiderShip(self.ship(x));});

		return (PlaneLoS*2) + RadarLoS + Math.sqrt( this.eLos1() -  PlaneLoS - RadarLoS );
	};

	/* LoS : "New Formula"
	= Dive Bomber LoS x (1.04) + Torpedo Bomber LoS x (1.37) + Carrier-based Recon Plane LoS x (1.66) + Recon Seaplane LoS x (2.00) + Seaplane Bomber LoS x (1.78) + Small Radar LoS x (1.00) + Large Radar LoS x (0.99) + Searchlight LoS x (0.91) + v(base LoS of each ship) x (1.69) + (HQ Lv. rounded up to the next multiple of 5) x (-0.61)
	------------------------------------*/
	KC3Fleet.prototype.eLos3 = function(){
		var dive = 0, torp = 0, cbrp = 0, rspl = 0, splb = 0, smrd = 0, lgrd = 0, srch = 0;
		var nakedLos = 0;

		function ConsiderShip(shipData){
			if(shipData.rosterId === 0) return false;
			if(shipData.didFlee) return false;
			nakedLos += Math.sqrt( shipData.nakedLoS() );
			Array.apply(null, {length: 4})
				.map(Number.call, Number)
				.forEach(function(x){ if(shipData.items[x]>-1) { ConsiderEquipment(shipData.equipment(x)); }});
		}

		function ConsiderEquipment(itemData){
			if(itemData.itemId === 0) return false;
			switch( itemData.master().api_type[2] ){
				case  7: dive += itemData.master().api_saku; break;
				case  8: torp += itemData.master().api_saku; break;
				case  9: cbrp += itemData.master().api_saku; break;
				case 10: rspl += itemData.master().api_saku; break;
				case 11: splb += itemData.master().api_saku; break;
				case 12: smrd += itemData.master().api_saku; break;
				case 13: lgrd += itemData.master().api_saku; break;
				case 29: srch += itemData.master().api_saku; break;
				default: break;
			}
		}

		var self = this;
		Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.forEach(function(x){ConsiderShip(self.ship(x));});

		var total = ( dive * 1.0376255 )
			+ ( torp * 1.3677954 )
			+ ( cbrp * 1.6592780 )
			+ ( rspl * 2.0000000 )
			+ ( splb * 1.7787282 )
			+ ( smrd * 1.0045358 )
			+ ( lgrd * 0.9906638 )
			+ ( srch * 0.9067950 )
			+ ( nakedLos * 1.6841056 )
			+ ( (Math.floor(( PlayerManager.hq.level + 4) / 5) * 5) * -0.6142467 );
		return total;
	};

	/* SORTIE JSON
	Used for recording sorties on indexedDB
	Generate fleet summary object without referential data (all masterId)
	Data must be recorded on the state of sortie execution, thus no reference
	------------------------------------*/
	KC3Fleet.prototype.sortieJson = function(){
		if(this.active){
			var ReturnObj = [];
			var self = this;
			$.each(this.ships, function(index, rosterId){
				if(rosterId > -1){
					ReturnObj.push({
						mst_id: self.ship(index).masterId,
						level: self.ship(index).level,
						kyouka: self.ship(index).mod,
						morale: self.ship(index).morale,
						equip: [
							self.ship(index).equipment(0).masterId,
							self.ship(index).equipment(1).masterId,
							self.ship(index).equipment(2).masterId,
							self.ship(index).equipment(3).masterId
						],
					});
				}
			});
			return ReturnObj;
		}else{
			return {};
		}
	};

})();<commit_msg>Infinite Loop mk.II<commit_after>/* Fleet.js
KC3改 Fleet Object

Contains summary information about a fleet and its 6 ships
{
	"api_member_id":18066975,
	"api_id":1,
	"api_name":"111",
	"api_name_id":"136558260",
	"api_mission":[ 0, 0, 0, 0 ],
	"api_flagship":"0",
	"api_ship":[ 76, -1, -1, -1, -1, -1 ]
}
*/
(function(){
	"use strict";

	window.KC3Fleet = function( data ){
		this.active = false;
		this.fastFleet = true;
		this.name = "";
		this.ships = [ -1, -1, -1, -1, -1, -1 ];
		this.mission = [ 0, 0, 0, 0 ];
	};

	KC3Fleet.prototype.update = function( data ){
		if(typeof data.api_member_id != "undefined"){
			this.active = true;
			this.name = data.api_name;
			this.ships = data.api_ship;
			this.mission = data.api_mission;
			if(data.api_id > 1){
				if(this.mission[0] > 0){
					KC3TimerManager.exped( data.api_id ).activate(
						this.mission[2],
						this.ship(0).masterId,
						this.mission[1]
					);
				}else{
					KC3TimerManager.exped( data.api_id ).deactivate();
				}
			}
		}
	};

	KC3Fleet.prototype.defineFormatted = function( data ){
		this.active = data.active;
		this.name = data.name;
		this.ships = data.ships;
		this.mission = data.mission;
		return this;
	};

	KC3Fleet.prototype.ship = function( slot ){
		return KC3ShipManager.get( this.ships[slot] );
	};

	KC3Fleet.prototype.countShips = function(){
		return $.grep(this.ships, function(shipId){ return shipId>-1; }).length;
	};

	KC3Fleet.prototype.resetAfterHp = function(){
		for(var i = 0; i < this.countShips(); i++) {
			this.ship(i).resetAfterHp();
		}
	};

	KC3Fleet.prototype.clearNonFlagShips = function(){
		this.ships[1] = this.ships[2] = this.ships[3] = this.ships[4] = this.ships[5] = -1;
	};

	KC3Fleet.prototype.totalLevel = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){return self.ship(x).level;})
			.reduce(function(x,y){return x+y;});
	};

	KC3Fleet.prototype.countDrums = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){return self.ship(x).countDrums();})
			.reduce(function(x,y){return x+y;});
	};

	KC3Fleet.prototype.countShipsWithDrums = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){return self.ship(x).countDrums()>0;})
			.reduce(function(x,y){return x+y;});
	};

	KC3Fleet.prototype.averageLevel = function(){
		return this.totalLevel() / this.countShips();
	};

	KC3Fleet.prototype.fighterPower = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){return self.ship(x).fighterPower();})
			.reduce(function(x,y){return x+y;});
	};

	KC3Fleet.prototype.speed = function(){
		this.fastFleet = true;
		var i = 0;
		while(this.fastFleet && i < 6) {
			if(this.ships[i] > -1) {
				this.fastFleet = this.fastFleet && this.ship(i).isFast();
			}
			i++;
		}
		return (this.fastFleet) ? KC3Meta.term("SpeedFast") : KC3Meta.term("SpeedSlow");
	};

	KC3Fleet.prototype.qualifyingExpeditions = function(){

	};

	KC3Fleet.prototype.compileStats = function(){

	};

	KC3Fleet.prototype.canCombineCarrier = function(){

	};

	KC3Fleet.prototype.canCombineSurface = function(){

	};

	KC3Fleet.prototype.supportPower = function(){

	};

	KC3Fleet.prototype.eLoS = function(){
		switch(ConfigManager.elosFormula){
			case 1: return this.eLos1();
			case 2: return this.eLos2();
			default: return this.eLos3();
		}
	};

	/* LoS : Fitted
	Sum of all Ship LoS in the fleet WITH their equipment
	------------------------------------*/
	KC3Fleet.prototype.eLos1 = function(){
		var self = this;
		return Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.map(function(x){
				return (!self.ship(x).didFlee)? self.ship(x).ls[0] : 0;
			})
			.reduce(function(x,y){return x+y;});
	};

	/* LoS : "Old Formula"
	= Recon LoS×2 + Radar LoS + v(Fleet total LoS - Recon LoS - Radar LoS)
	------------------------------------*/
	KC3Fleet.prototype.eLos2 = function(){
		var PlaneLoS = 0;
		var RadarLoS = 0;

		function ConsiderShip(shipData){
			if(shipData.rosterId === 0) return false;
			if(shipData.didFlee) return false;
			Array.apply(null, {length: 4})
				.map(Number.call, Number)
				.forEach(function(x){ if(shipData.items[x]>-1) { ConsiderEquipment(shipData.equipment(x)); }});
		}

		function ConsiderEquipment(itemData){
			if(itemData.itemId === 0) return false;
			if( itemData.master().api_type[1] == 7){ PlaneLoS += itemData.master().api_saku; }
			if( itemData.master().api_type[1] == 8){ RadarLoS += itemData.master().api_saku; }
		}

		var self = this;
		Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.forEach(function(x){ConsiderShip(self.ship(x));});

		return (PlaneLoS*2) + RadarLoS + Math.sqrt( this.eLos1() -  PlaneLoS - RadarLoS );
	};

	/* LoS : "New Formula"
	= Dive Bomber LoS x (1.04) + Torpedo Bomber LoS x (1.37) + Carrier-based Recon Plane LoS x (1.66) + Recon Seaplane LoS x (2.00) + Seaplane Bomber LoS x (1.78) + Small Radar LoS x (1.00) + Large Radar LoS x (0.99) + Searchlight LoS x (0.91) + v(base LoS of each ship) x (1.69) + (HQ Lv. rounded up to the next multiple of 5) x (-0.61)
	------------------------------------*/
	KC3Fleet.prototype.eLos3 = function(){
		var dive = 0, torp = 0, cbrp = 0, rspl = 0, splb = 0, smrd = 0, lgrd = 0, srch = 0;
		var nakedLos = 0;

		function ConsiderShip(shipData){
			if(shipData.rosterId === 0) return false;
			if(shipData.didFlee) return false;
			nakedLos += Math.sqrt( shipData.nakedLoS() );
			Array.apply(null, {length: 4})
				.map(Number.call, Number)
				.forEach(function(x){ if(shipData.items[x]>-1) { ConsiderEquipment(shipData.equipment(x)); }});
		}

		function ConsiderEquipment(itemData){
			if(itemData.itemId === 0) return false;
			switch( itemData.master().api_type[2] ){
				case  7: dive += itemData.master().api_saku; break;
				case  8: torp += itemData.master().api_saku; break;
				case  9: cbrp += itemData.master().api_saku; break;
				case 10: rspl += itemData.master().api_saku; break;
				case 11: splb += itemData.master().api_saku; break;
				case 12: smrd += itemData.master().api_saku; break;
				case 13: lgrd += itemData.master().api_saku; break;
				case 29: srch += itemData.master().api_saku; break;
				default: break;
			}
		}

		var self = this;
		Array.apply(null, {length: 6})
			.map(Number.call, Number)
			.forEach(function(x){ConsiderShip(self.ship(x));});

		var total = ( dive * 1.0376255 )
			+ ( torp * 1.3677954 )
			+ ( cbrp * 1.6592780 )
			+ ( rspl * 2.0000000 )
			+ ( splb * 1.7787282 )
			+ ( smrd * 1.0045358 )
			+ ( lgrd * 0.9906638 )
			+ ( srch * 0.9067950 )
			+ ( nakedLos * 1.6841056 )
			+ ( (Math.floor(( PlayerManager.hq.level + 4) / 5) * 5) * -0.6142467 );
		return total;
	};

	/* SORTIE JSON
	Used for recording sorties on indexedDB
	Generate fleet summary object without referential data (all masterId)
	Data must be recorded on the state of sortie execution, thus no reference
	------------------------------------*/
	KC3Fleet.prototype.sortieJson = function(){
		if(this.active){
			var ReturnObj = [];
			var self = this;
			$.each(this.ships, function(index, rosterId){
				if(rosterId > -1){
					ReturnObj.push({
						mst_id: self.ship(index).masterId,
						level: self.ship(index).level,
						kyouka: self.ship(index).mod,
						morale: self.ship(index).morale,
						equip: [
							self.ship(index).equipment(0).masterId,
							self.ship(index).equipment(1).masterId,
							self.ship(index).equipment(2).masterId,
							self.ship(index).equipment(3).masterId
						],
					});
				}
			});
			return ReturnObj;
		}else{
			return {};
		}
	};

})();<|endoftext|>


<commit_before>$(document).ready(function() {
    function GetQueryStringParams(sParam) {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) {
                return sParameterName[1];
            }
        }
    }
    var tiled = false;
    var tiledQuery = GetQueryStringParams('tiled');
    if (tiledQuery) {
        tiled = true;
    }
    var da_image_content;
    var query = GetQueryStringParams('query');
    var q = GetQueryStringParams('q');
    var savedUrl;
    var slug;
    var getSlug;
    var imgPath;
    var h1_query
    var slugFromUrl = GetQueryStringParams('slug');
    if (slugFromUrl) {
        imgPath = 'http://i.giphy.com/' + slugFromUrl + '.gif';
        h1_query = decodeURIComponent(q).replace(/\+/g, ' ');
        if (h1_query.length >= 24) {
            h1_query = h1_query.substring(0, 24) + '...';
        };
        $("h1#your_query_search").text(h1_query);
        $('#gifmaster_it_up').css('background-image', 'url(' + imgPath + ')');
        $('.saved').html("
Saved
");
        if ($('#saved').hasClass('hidden')) {
            $('#saved').removeClass('hidden');
            $('#save').addClass('hidden');
        };
} else {
    if (query) {
        // var request = 'http://api.giphy.com/v1/gifs/search?q=' + query + '&api_key=dc6zaTOxFJmzC';
        var request = 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=' + query;
        $.getJSON(request, function(data) {
            getSlug = function() {
                var index = data.data.image_original_url.split('/');
                return index[4];
            };
            // console.log(data.data);
            if (data.data.image_original_url) {
                if ($('#twitt').hasClass('un-hidden')) {
                    /* todo: clean this up */
                } else {
                    $('#twitt').removeClass('un-hidden')
                };
                slug = getSlug(data.data.image_original_url);
                console.log(slug);
                $('#save').click(function() {
                    savedUrl = '?slug=' + slug + '&q=' + query;
                    $(location).attr("href", savedUrl);
                    $('#saved').removeClass('hidden');
                });
                imgPath = 'http://i.giphy.com/' + slug + '.gif';
                $('#gifmaster_it_up').css('background-image', 'url(' + imgPath + ')');
                h1_query = decodeURIComponent(query).replace(/\+/g, ' ');
                if (h1_query.length >= 24) {
                    h1_query = h1_query.substring(0, 24) + '...';
                };
                $("h1#your_query_search").text(h1_query);
                // da_image_content = '<meta property="og:image" content="' + imgPath + '"/>' +
                //     '<meta property="og:url" content="' + imgPath + '"/>' +
                //     '<meta property="og:title" content="' + h1_query + '">' +
                //     '<meta property="og:description" content="' + h1_query + '">' +
                //     '<meta property="twitter:image" content="' + imgPath + '">';
                // $('head').append(da_image_content);
            } else {
                $('#gifmaster_it_up').css('background-image', 'url(http://i.giphy.com/i8HONP9VaTV6w.gif)');
                $("h1#your_query_search").text('I got nuthin');
            }
        });
    } else {
        var request = 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=';
        $.getJSON(request, function(data) {
            getSlug = function() {
                var index = data.data.image_original_url.split('/');
                return index[4];
            };
            slug = getSlug(data.data.image_original_url);
            imgPath = 'http://i.giphy.com/' + slug + '.gif';
            console.log(data.data);
            $('#gifmaster_it_up').css('background-image', 'url(' + imgPath + ')');
            slug = getSlug(data.data.image_original_url);
            console.log(slug);
            $('#save').click(function() {
                savedUrl = '?slug=' + slug + '&q=gr8';
                $(location).attr("href", savedUrl);
            });
        });
    }
};
if ($('#gifmaster_it_up').hasClass("tiled")) {
    tiled = true;
} else {
    tiled = false;
}
$('#tile').click(function() {
    if (tiled) {
        tiled = false;
        $('#gifmaster_it_up').removeClass("tiled");
    } else {
        tiled = true;
        $('#gifmaster_it_up').addClass("tiled");
    }
});
});
<commit_msg>secret tiled for joe<commit_after>$(document).ready(function() {
    function GetQueryStringParams(sParam) {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) {
                return sParameterName[1];
            }
        }
    }
    var tiled;
    var tiledQuery = GetQueryStringParams('tiled');
    if (tiledQuery) {
        $('#gifmaster_it_up').addClass("tiled");
    };
    var da_image_content;
    var query = GetQueryStringParams('query');
    var q = GetQueryStringParams('q');
    var savedUrl;
    var slug;
    var getSlug;
    var imgPath;
    var h1_query
    var slugFromUrl = GetQueryStringParams('slug');
    if (slugFromUrl) {
        imgPath = 'http://i.giphy.com/' + slugFromUrl + '.gif';
        h1_query = decodeURIComponent(q).replace(/\+/g, ' ');
        if (h1_query.length >= 24) {
            h1_query = h1_query.substring(0, 24) + '...';
        };
        $("h1#your_query_search").text(h1_query);
        $('#gifmaster_it_up').css('background-image', 'url(' + imgPath + ')');
        $('.saved').html("
Saved
");
        if ($('#saved').hasClass('hidden')) {
            $('#saved').removeClass('hidden');
            $('#save').addClass('hidden');
        };
} else {
    if (query) {
        // var request = 'http://api.giphy.com/v1/gifs/search?q=' + query + '&api_key=dc6zaTOxFJmzC';
        var request = 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=' + query;
        $.getJSON(request, function(data) {
            getSlug = function() {
                var index = data.data.image_original_url.split('/');
                return index[4];
            };
            // console.log(data.data);
            if (data.data.image_original_url) {
                if ($('#twitt').hasClass('un-hidden')) {
                    /* todo: clean this up */
                } else {
                    $('#twitt').removeClass('un-hidden')
                };
                slug = getSlug(data.data.image_original_url);
                console.log(slug);
                $('#save').click(function() {
                    savedUrl = '?slug=' + slug + '&q=' + query;
                    $(location).attr("href", savedUrl);
                    $('#saved').removeClass('hidden');
                });
                imgPath = 'http://i.giphy.com/' + slug + '.gif';
                $('#gifmaster_it_up').css('background-image', 'url(' + imgPath + ')');
                h1_query = decodeURIComponent(query).replace(/\+/g, ' ');
                if (h1_query.length >= 24) {
                    h1_query = h1_query.substring(0, 24) + '...';
                };
                $("h1#your_query_search").text(h1_query);
                // da_image_content = '<meta property="og:image" content="' + imgPath + '"/>' +
                //     '<meta property="og:url" content="' + imgPath + '"/>' +
                //     '<meta property="og:title" content="' + h1_query + '">' +
                //     '<meta property="og:description" content="' + h1_query + '">' +
                //     '<meta property="twitter:image" content="' + imgPath + '">';
                // $('head').append(da_image_content);
            } else {
                $('#gifmaster_it_up').css('background-image', 'url(http://i.giphy.com/i8HONP9VaTV6w.gif)');
                $("h1#your_query_search").text('I got nuthin');
            }
        });
    } else {
        var request = 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=';
        $.getJSON(request, function(data) {
            getSlug = function() {
                var index = data.data.image_original_url.split('/');
                return index[4];
            };
            slug = getSlug(data.data.image_original_url);
            imgPath = 'http://i.giphy.com/' + slug + '.gif';
            console.log(data.data);
            $('#gifmaster_it_up').css('background-image', 'url(' + imgPath + ')');
            slug = getSlug(data.data.image_original_url);
            console.log(slug);
            $('#save').click(function() {
                savedUrl = '?slug=' + slug + '&q=gr8';
                $(location).attr("href", savedUrl);
            });
        });
    }
};
// if ($('#gifmaster_it_up').hasClass("tiled")) {
//     tiled = true;
// } else {
//     tiled = false;
// }
$('#tile').click(function() {
    if (tiled) {
        tiled = false;
        $('#gifmaster_it_up').removeClass("tiled");
    } else {
        tiled = true;
        $('#gifmaster_it_up').addClass("tiled");
    }
});
});
<|endoftext|>


<commit_before>(function(){

	var fitb = function() {

		var success = function($this, msg){
			$this.find('button').addClass('disabled');
			$this.append('

'+msg+'
');
			$this.children('.alert').hide().show('slow');
		}

		$('.para').each(function(){
			var qid = $(this).data('id');
			if(Cookies.get(qid)){

				var answer = $(this).data('answer');
				$(this).find('input').each(function(i){
					$(this).val(answer[i]);
					$(this).prop('readonly', true);
				});

				success($(this),'You had already answered this question.');
			}
		});

		$('.but').click(function(){

			var answer = $(this).parent('.para').data('answer');
			var all_corret = 1;

			$(this).siblings('.ans').each(function(i){
				var input = $(this).children('input').val();
				if(answer[i]==input)
					$(this).children('input').addClass('correct').removeClass('add').prop("readonly", true);
				else {
					$(this).children('input').addClass('add');
					all_corret = 0;
				}
			});

			var qid = $(this).parent('.para').data('id');

			if(all_corret){
				Cookies.set(qid, true);
				success($(this).parents('.para'),'Correct!');
			}
		});

		$('.ans > input').click(function(){
			$(this).removeClass('add');
		});
		$('.ans > input').keypress(function(){
			$(this).removeClass('add');
		});
	}

	require(["gitbook"], function(gitbook) {
	    gitbook.events.bind("page.change", function() {
	        fitb();
	    });

	});

})();<commit_msg>changed function name<commit_after>(function(){

	var init = function() {

		var success = function($this, msg){
			$this.find('button').addClass('disabled');
			$this.append('

'+msg+'
');
			$this.children('.alert').hide().show('slow');
		}

		$('.para').each(function(){
			var qid = $(this).data('id');
			if(Cookies.get(qid)){

				var answer = $(this).data('answer');
				$(this).find('input').each(function(i){
					$(this).val(answer[i]);
					$(this).prop('readonly', true);
				});

				success($(this),'You had already answered this question.');
			}
		});

		$('.but').click(function(){

			var answer = $(this).parent('.para').data('answer');
			var all_corret = 1;

			$(this).siblings('.ans').each(function(i){
				var input = $(this).children('input').val();
				if(answer[i]==input)
					$(this).children('input').addClass('correct').removeClass('add').prop("readonly", true);
				else {
					$(this).children('input').addClass('add');
					all_corret = 0;
				}
			});

			var qid = $(this).parent('.para').data('id');

			if(all_corret){
				Cookies.set(qid, true);
				success($(this).parents('.para'),'Correct!');
			}
		});

		$('.ans > input').click(function(){
			$(this).removeClass('add');
		});
		$('.ans > input').keypress(function(){
			$(this).removeClass('add');
		});
	}

	require(["gitbook"], function(gitbook) {
	    gitbook.events.bind("page.change", function() {
	        init();
	    });

	});

})();<|endoftext|>


<commit_before>export default {
  registerUser({Meteor,LocalState},data){
	  console.log(data);
		Meteor.call('users.add', data, (error, data)=>{
			if(error){
				LocalState.set('REGISTER_ERROR', error)
			} else {
				//FlowRouter.go('')
				console.log(data,error)
			}
		})
  }
}
<commit_msg>validation in register<commit_after>export default {
  registerUser({Meteor,LocalState},data){
	  console.log(data);
		Meteor.call('users.add', data, (error, data)=>{
			if(error){
				LocalState.set('REGISTER_ERROR', error.reason)
			} else {
				//FlowRouter.go('')
				console.log(data)
			}
		})
  }
}
<|endoftext|>


<commit_before>/////////////////////
// Project JS      //
/////////////////////
(function($){

window.NodeActions = {};  // Namespace for NodeActions

// TODO: move me to the NodeControl or separate module
NodeActions.beforeForkNode = function(url, done) {
    $.ajax({
        url: url,
        contentType: 'application/json'
    }).success(function(response) {
        bootbox.confirm(
             $.osf.joinPrompts(response.prompts, 'Are you sure you want to fork this project?'),
             function(result) {
                 if (result) {
                     done && done();
                 }
             }
         );
    });
};

NodeActions.forkNode = function() {
    NodeActions.beforeForkNode(nodeApiUrl + 'fork/before/', function() {
        // Block page
        $.osf.block();
        // Fork node
        $.ajax({
            url: nodeApiUrl + 'fork/',
            type: 'POST'
        }).success(function(response) {
            window.location = response;
        }).error(function() {
            $.osf.unblock();
            bootbox.alert('Forking failed');
        });
    });
};

NodeActions.forkPointer = function(pointerId, nodeId) {
    bootbox.confirm('Are you sure you want to fork this project?',
        function(result) {
            if (result) {
                // Block page
                $.osf.block();

                // Fork pointer
                $.ajax({
                    type: 'post',
                    url: nodeApiUrl + 'pointer/fork/',
                    data: JSON.stringify({'pointerId': pointerId}),
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function(response) {
                        window.location.reload();
                    },
                    error: function() {
                        $.osf.unblock();
                        bootbox.alert('Could not fork link.');
                    }
                });
            }
        }
    )
};

NodeActions.addonFileRedirect = function(item) {
    window.location.href = item.params.urls.view;
    return false;
};

NodeActions.useAsTemplate = function() {
    $.osf.block();

    $.ajax({
        url: '/api/v1/project/new/' + nodeId + '/',
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            window.location = data['url']
        },
        error: function(response) {
            $.osf.unblock();
            $.osf.handleJSONError(response);
        }
    });
};

$(function(){

    $(".remove-private-link").on("click",function(){
        var me = $(this);
        var data_to_send={
            'private_link': me.attr("data-link")
        };
        bootbox.confirm('Are you sure to remove this private link?', function(result) {
            if (result) {
                $.ajax({
                    type: "delete",
                    url: nodeApiUrl + "private_link/",
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(data_to_send)
                }).done(function(response) {
                    window.location.reload();
                });
            }
         });
    });

    $('#newComponent form').on('submit', function(e) {

          $("#add-component-submit")
              .attr("disabled", "disabled")
              .text("Adding");

          if ($.trim($("#title").val())==''){

              $("#alert").text("The new component title cannot be empty");

              $("#add-component-submit")
                      .removeAttr("disabled","disabled")
                      .text("OK");

              e.preventDefault();
          }
          else if ($(e.target).find("#title").val().length>200){
              $("#alert").text("The new component title cannot be more than 200 characters.");

              $("#add-component-submit")
                      .removeAttr("disabled","disabled")
                      .text("OK");

              e.preventDefault();

          }
//          else{
//              $.ajax({
//                   url: $(e.target).attr("action"),
//                   type:"POST",
//                   timeout:60000,
//                   data:$(e.target).serialize()
//              }).success(function(){
//                  location.reload();
//              }).fail(function(jqXHR, textStatus, errorThrown){
//                    if(textStatus==="timeout") {
//                        $("#alert").text("Add component timed out"); //Handle the timeout
//                    }else{
//                        $("#alert").text('Add component failed');
//                    }
//                    $("#add-component-submit")
//                      .removeAttr("disabled","disabled")
//                      .text("OK");
//              });
//          }

     });
});

NodeActions._openCloseNode = function(nodeId) {

    var icon = $('#icon-' + nodeId);
    var body = $('#body-' + nodeId);

    body.toggleClass('hide');

    if ( body.hasClass('hide') ) {
        icon.removeClass('icon-minus');
        icon.addClass('icon-plus');
        icon.attr('title', 'More');
    } else {
        icon.removeClass('icon-plus');
        icon.addClass('icon-minus');
        icon.attr('title', 'Less');
    }

    // Refresh tooltip text
    icon.tooltip('destroy');
    icon.tooltip();

};

NodeActions.reorderChildren = function(idList, elm) {
    $.ajax({
        type: 'POST',
        url: nodeApiUrl + 'reorder_components/',
        data: JSON.stringify({'new_list': idList}),
        contentType: 'application/json',
        dataType: 'json',
        error: function(response) {
            $(elm).sortable('cancel');
            $.osf.handleJSONError(response);
        }
    });
};

NodeActions.removePointer = function(pointerId, pointerElm) {
    $.ajax({
        type: 'DELETE',
        url: nodeApiUrl + 'pointer/',
        data: JSON.stringify({pointerId: pointerId}),
        contentType: 'application/json',
        dataType: 'json',
        success: function(response) {
            pointerElm.remove();
        }
    })
};

/*
refresh rendered file through mfr
*/

window.FileRenderer = {
    start: function(url, selector){
        this.url = url;
        this.element = $(selector);
        this.tries = 0;
        this.refreshContent = window.setInterval(this.getCachedFromServer.bind(this), 1000);
    },

    getCachedFromServer: function() {
        var self = this;
        $.get( self.url, function(data) {
            if (data) {
                self.element.html(data);
                clearInterval(self.refreshContent);
            } else {
                self.tries += 1;
                if(self.tries > 10){
                    clearInterval(self.refreshContent);
                    self.element.html("Timeout occurred while loading, please refresh the page")
                }
            }
        });
     }
};

/*
Display recent logs for for a node on the project view page.
*/
NodeActions.openCloseNode = function(nodeId){
    var $logs = $('#logs-' + nodeId);
    if (!$logs.hasClass('active')) {
        if (!$logs.hasClass('served')) {
            $.getJSON(
                $logs.attr('data-uri'),
                {count: 3},
                function(response) {
                    $script(['/static/js/logFeed.js'], function() {
                        var log = new LogFeed($logs, response.logs);
                    });
                    $logs.addClass('served');
                }
            );
        }
        $logs.addClass('active');
    } else {
        $logs.removeClass('active');
    }
    // Hide/show the html
    NodeActions._openCloseNode(nodeId);
};

$(document).ready(function() {

    ko.punches.enableAll();

    var permissionInfoHtml = '
' +
            '
Read: View project content and comment
' +
            '
Read + Write: Read privileges plus add and configure components; add and edit content
' +
            '
Administrator: Read and write privileges; manage contributors; delete and register project; public-private settings
' +
        '
';

    $('.permission-info').attr(
        'data-content', permissionInfoHtml
    ).popover();

    ////////////////////
    // Event Handlers //
    ////////////////////

    $('.remove-pointer').on('click', function() {
        var $this = $(this);
        bootbox.confirm(
            'Are you sure you want to remove this link? This will not ' +
            'remove the project this link refers to.',
            function(result) {
                if (result) {
                    var pointerId = $this.attr('data-id');
                    var pointerElm = $this.closest('.list-group-item');
                    NodeActions.removePointer(pointerId, pointerElm);
                }
            }
        )
    });

    $('body').on('click', '.tagsinput .tag > span', function(e) {
        window.location = "/search/?q=" + $(e.target).text().toString().trim();
    })

    $('.citation-toggle').on('click', function(evt) {
        $(this).closest('.citations').find('.citation-list').slideToggle();
        return false;
    });

});

}).call(this, jQuery);
<commit_msg>Make project.js AMD compatible<commit_after>/////////////////////
// Project JS      //
/////////////////////
(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'js/logFeed', 'osfutils'], factory);
    } else {
        factory(jQuery, global.LogFeed);
    }
}(this, function($, LogFeed) {

window.NodeActions = {};  // Namespace for NodeActions

// TODO: move me to the NodeControl or separate module
NodeActions.beforeForkNode = function(url, done) {
    $.ajax({
        url: url,
        contentType: 'application/json'
    }).success(function(response) {
        bootbox.confirm(
             $.osf.joinPrompts(response.prompts, 'Are you sure you want to fork this project?'),
             function(result) {
                 if (result) {
                     done && done();
                 }
             }
         );
    });
};

NodeActions.forkNode = function() {
    NodeActions.beforeForkNode(nodeApiUrl + 'fork/before/', function() {
        // Block page
        $.osf.block();
        // Fork node
        $.ajax({
            url: nodeApiUrl + 'fork/',
            type: 'POST'
        }).success(function(response) {
            window.location = response;
        }).error(function() {
            $.osf.unblock();
            bootbox.alert('Forking failed');
        });
    });
};

NodeActions.forkPointer = function(pointerId, nodeId) {
    bootbox.confirm('Are you sure you want to fork this project?',
        function(result) {
            if (result) {
                // Block page
                $.osf.block();

                // Fork pointer
                $.ajax({
                    type: 'post',
                    url: nodeApiUrl + 'pointer/fork/',
                    data: JSON.stringify({'pointerId': pointerId}),
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function(response) {
                        window.location.reload();
                    },
                    error: function() {
                        $.osf.unblock();
                        bootbox.alert('Could not fork link.');
                    }
                });
            }
        }
    )
};

NodeActions.addonFileRedirect = function(item) {
    window.location.href = item.params.urls.view;
    return false;
};

NodeActions.useAsTemplate = function() {
    $.osf.block();

    $.ajax({
        url: '/api/v1/project/new/' + nodeId + '/',
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            window.location = data['url']
        },
        error: function(response) {
            $.osf.unblock();
            $.osf.handleJSONError(response);
        }
    });
};

$(function(){

    $(".remove-private-link").on("click",function(){
        var me = $(this);
        var data_to_send={
            'private_link': me.attr("data-link")
        };
        bootbox.confirm('Are you sure to remove this private link?', function(result) {
            if (result) {
                $.ajax({
                    type: "delete",
                    url: nodeApiUrl + "private_link/",
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(data_to_send)
                }).done(function(response) {
                    window.location.reload();
                });
            }
         });
    });

    $('#newComponent form').on('submit', function(e) {

          $("#add-component-submit")
              .attr("disabled", "disabled")
              .text("Adding");

          if ($.trim($("#title").val())==''){

              $("#alert").text("The new component title cannot be empty");

              $("#add-component-submit")
                      .removeAttr("disabled","disabled")
                      .text("OK");

              e.preventDefault();
          }
          else if ($(e.target).find("#title").val().length>200){
              $("#alert").text("The new component title cannot be more than 200 characters.");

              $("#add-component-submit")
                      .removeAttr("disabled","disabled")
                      .text("OK");

              e.preventDefault();

          }
     });
});

NodeActions._openCloseNode = function(nodeId) {

    var icon = $('#icon-' + nodeId);
    var body = $('#body-' + nodeId);

    body.toggleClass('hide');

    if ( body.hasClass('hide') ) {
        icon.removeClass('icon-minus');
        icon.addClass('icon-plus');
        icon.attr('title', 'More');
    } else {
        icon.removeClass('icon-plus');
        icon.addClass('icon-minus');
        icon.attr('title', 'Less');
    }

    // Refresh tooltip text
    icon.tooltip('destroy');
    icon.tooltip();

};

NodeActions.reorderChildren = function(idList, elm) {
    $.ajax({
        type: 'POST',
        url: nodeApiUrl + 'reorder_components/',
        data: JSON.stringify({'new_list': idList}),
        contentType: 'application/json',
        dataType: 'json',
        error: function(response) {
            $(elm).sortable('cancel');
            $.osf.handleJSONError(response);
        }
    });
};

NodeActions.removePointer = function(pointerId, pointerElm) {
    $.ajax({
        type: 'DELETE',
        url: nodeApiUrl + 'pointer/',
        data: JSON.stringify({pointerId: pointerId}),
        contentType: 'application/json',
        dataType: 'json',
        success: function(response) {
            pointerElm.remove();
        }
    })
};

/*
refresh rendered file through mfr
*/

window.FileRenderer = {
    start: function(url, selector){
        this.url = url;
        this.element = $(selector);
        this.tries = 0;
        this.refreshContent = window.setInterval(this.getCachedFromServer.bind(this), 1000);
    },

    getCachedFromServer: function() {
        var self = this;
        $.get( self.url, function(data) {
            if (data) {
                self.element.html(data);
                clearInterval(self.refreshContent);
            } else {
                self.tries += 1;
                if(self.tries > 10){
                    clearInterval(self.refreshContent);
                    self.element.html("Timeout occurred while loading, please refresh the page")
                }
            }
        });
     }
};

/*
Display recent logs for for a node on the project view page.
*/
NodeActions.openCloseNode = function(nodeId){
    var $logs = $('#logs-' + nodeId);
    if (!$logs.hasClass('active')) {
        if (!$logs.hasClass('served')) {
            $.getJSON(
                $logs.attr('data-uri'),
                {count: 3},
                function(response) {
                    var log = new LogFeed($logs, response.logs);
                    $logs.addClass('served');
                }
            );
        }
        $logs.addClass('active');
    } else {
        $logs.removeClass('active');
    }
    // Hide/show the html
    NodeActions._openCloseNode(nodeId);
};

$(document).ready(function() {

    ko.punches.enableAll();

    var permissionInfoHtml = '
' +
            '
Read: View project content and comment
' +
            '
Read + Write: Read privileges plus add and configure components; add and edit content
' +
            '
Administrator: Read and write privileges; manage contributors; delete and register project; public-private settings
' +
        '
';

    $('.permission-info').attr(
        'data-content', permissionInfoHtml
    ).popover();

    ////////////////////
    // Event Handlers //
    ////////////////////

    $('.remove-pointer').on('click', function() {
        var $this = $(this);
        bootbox.confirm(
            'Are you sure you want to remove this link? This will not ' +
            'remove the project this link refers to.',
            function(result) {
                if (result) {
                    var pointerId = $this.attr('data-id');
                    var pointerElm = $this.closest('.list-group-item');
                    NodeActions.removePointer(pointerId, pointerElm);
                }
            }
        )
    });

    $('body').on('click', '.tagsinput .tag > span', function(e) {
        window.location = "/search/?q=" + $(e.target).text().toString().trim();
    });

    $('.citation-toggle').on('click', function(evt) {
        $(this).closest('.citations').find('.citation-list').slideToggle();
        return false;
    });

});

}));
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Steam Flash Sale
// @namespace   com.natemara.flash-sale
// @description Quickly sell your steam items
// @include     /https?://(www\.)?steamcommunity\.com/market/.*/
// @version     3
// @grant       none
// ==/UserScript==

var itemPattern = /Starting at: $[0-9.]+/;

function getPrice() {
	var matches = document.documentElement.innerHTML.match(itemPattern);
	var itemPrice = document.getElementById("iteminfo1_item_market_actions");
	window.alert(matches);
}

setInterval(function() {
	getPrice();
}, 5000);
<commit_msg>change alert to console log<commit_after>// ==UserScript==
// @name        Steam Flash Sale
// @namespace   com.natemara.flash-sale
// @description Quickly sell your steam items
// @include     /https?://(www\.)?steamcommunity\.com/market/.*/
// @version     3
// @grant       none
// ==/UserScript==

var itemPattern = /Starting at: $[0-9.]+/;

function getPrice() {
	var matches = document.documentElement.innerHTML.match(itemPattern);
	var itemPrice = document.getElementById("iteminfo1_item_market_actions");
	console.log(matches);
}

setInterval(function() {
	getPrice();
}, 5000);
<|endoftext|>


<commit_before>
function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        loginUserIntoApplication();
    } else if (response.status === 'not_authorized') {
        logout();
    } else {
        logout();
    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    if(localStorage.getItem("id")){
        checkLoginState();
    }else{
        performLogoutActions();
    }

};

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function loginUserIntoApplication() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'id, name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email+" "+response.id);
        makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (responseText) {
            var userIdByEmail = null;
            var alreadyExists = false;
            if(responseText){
                var users = JSON.parse(responseText);
                alreadyExists = checkIfUserAlreadyExists(users, response.email);
            }
            if(!alreadyExists){
                var data = "name="+response.name+"&email="+response.email+"&fbid="+response.id;
                makeCorsRequest("POST", "https://ivebeenthereapi-matyapav.rhcloud.com/users", data, function (responseText) {
                    console.log(JSON.parse(responseText).message);
                    userIdByEmail = JSON.parse(responseText).id;
                    saveUserIdInLocalStorage(userIdByEmail);
                    performLoginActions();
                });
            }else{
                userIdByEmail = users[id]._id;
                saveUserIdInLocalStorage(userIdByEmail);
            }

            console.log(localStorage.getItem("id"));
            performLoginActions();
            document.getElementById('status').innerHTML =
                'Přihlášen jako,  ' + response.name + '!';

        });

    });
}

function checkIfUserAlreadyExists(users, email){
    for (id in users){
        if(users[id].email == email){
            return true;
        };
    }
    return false;
}

function  showUserInfo() {
    var userid = localStorage.getItem('id');
    if(userid){
        makeCorsRequest('GET', 'https://ivebeenthereapi-matyapav.rhcloud.com/users/'+userid, null, function (responseText) {
            initModal();
            var modalInfo = document.getElementById("modal-info");
            modalInfo.innerHTML = "Name: "+JSON.parse(responseText).name+"
 Email: "+JSON.parse(responseText).email;
        })
    }

}

function saveUserIdInLocalStorage(user_id){
    // Check browser support
    if (typeof(Storage) !== "undefined") {
        // Store
        localStorage.setItem("id", user_id);

    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
    }
}

function fblogin() {
    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: ['email', 'user_friends'] });
}

function logout(){
    if(confirm("Do you really want to logout?")){
        localStorage.removeItem("id");
        performLogoutActions();
    }
}

function getFriendsWhichVisitedPlace(placeName, placeAddress){
    makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (response) {
        var users = JSON.parse(response);
        FB.api('me/friends', { fields: 'id, first_name,picture', limit: 6 },function(response){
            console.log(response);
            var data = response.data;
            data.forEach(function (friend) {
                users.forEach(function (user) {
                    if(user.fbid == friend.id){
                        user.places.forEach(function (place) {
                            if(place.name == placeName && place.address == placeAddress){
                                var photoUrl = friend.picture.data.url;
                                document.getElementById("place-friends").innerText = "";
                                document.getElementById("place-friends").innerHTML+= ""
                            }
                        })

                    }
                })
            })

        });
    })
}

function performLoginActions() {
    document.getElementById('login_btn').style = "display: none";
    document.getElementById('logout_btn').style = "display: block";
    if(somePlaceIsSelected){
        document.getElementById('actions').style = "display: block";
    }
    document.getElementById('radius-input').addEventListener('change', getNearbyLocations);
    getNearbyLocations();
}

function performLogoutActions(){
    document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
    document.getElementById('login_btn').style = "display: block";
    document.getElementById('logout_btn').style = "display: none";
    document.getElementById('actions').style = "display: none";
    //clear previous markers
    clearMap();
    //unselect selected place
    clearTable();
}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}
<commit_msg>perform login actions even if user was created during fb login<commit_after>
function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        loginUserIntoApplication();
    } else if (response.status === 'not_authorized') {
        logout();
    } else {
        logout();
    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    if(localStorage.getItem("id")){
        checkLoginState();
    }else{
        performLogoutActions();
    }

};

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function loginUserIntoApplication() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'id, name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email+" "+response.id);
        makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (responseText) {
            var userIdByEmail = null;
            var alreadyExists = false;
            if(responseText){
                var users = JSON.parse(responseText);
                alreadyExists = checkIfUserAlreadyExists(users, response.email);
            }
            if(!alreadyExists){
                var data = "name="+response.name+"&email="+response.email+"&fbid="+response.id;
                makeCorsRequest("POST", "https://ivebeenthereapi-matyapav.rhcloud.com/users", data, function (responseText) {
                    console.log(JSON.parse(responseText).message);
                    userIdByEmail = JSON.parse(responseText).id;
                    saveUserIdInLocalStorage(userIdByEmail);
                    console.log(localStorage.getItem("id"));
                    performLoginActions();
                    document.getElementById('status').innerHTML =
                        'Přihlášen jako,  ' + response.name + '!';
                });
            }else{
                userIdByEmail = users[id]._id;
                saveUserIdInLocalStorage(userIdByEmail);
                console.log(localStorage.getItem("id"));
                performLoginActions();
                document.getElementById('status').innerHTML =
                    'Přihlášen jako,  ' + response.name + '!';
            }
        });

    });
}

function checkIfUserAlreadyExists(users, email){
    for (id in users){
        if(users[id].email == email){
            return true;
        };
    }
    return false;
}

function  showUserInfo() {
    var userid = localStorage.getItem('id');
    if(userid){
        makeCorsRequest('GET', 'https://ivebeenthereapi-matyapav.rhcloud.com/users/'+userid, null, function (responseText) {
            initModal();
            var modalInfo = document.getElementById("modal-info");
            modalInfo.innerHTML = "Name: "+JSON.parse(responseText).name+"
 Email: "+JSON.parse(responseText).email;
        })
    }

}

function saveUserIdInLocalStorage(user_id){
    // Check browser support
    if (typeof(Storage) !== "undefined") {
        // Store
        localStorage.setItem("id", user_id);

    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
    }
}

function fblogin() {
    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: ['email', 'user_friends'] });
}

function logout(){
    if(confirm("Do you really want to logout?")){
        localStorage.removeItem("id");
        performLogoutActions();
    }
}

function getFriendsWhichVisitedPlace(placeName, placeAddress){
    makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (response) {
        var users = JSON.parse(response);
        FB.api('me/friends', { fields: 'id, first_name,picture', limit: 6 },function(response){
            console.log(response);
            var data = response.data;
            data.forEach(function (friend) {
                users.forEach(function (user) {
                    if(user.fbid == friend.id){
                        user.places.forEach(function (place) {
                            if(place.name == placeName && place.address == placeAddress){
                                var photoUrl = friend.picture.data.url;
                                document.getElementById("place-friends").innerText = "";
                                document.getElementById("place-friends").innerHTML+= ""
                            }
                        })

                    }
                })
            })

        });
    })
}

function performLoginActions() {
    document.getElementById('login_btn').style = "display: none";
    document.getElementById('logout_btn').style = "display: block";
    if(somePlaceIsSelected){
        document.getElementById('actions').style = "display: block";
    }
    document.getElementById('radius-input').addEventListener('change', getNearbyLocations);
    getNearbyLocations();
}

function performLogoutActions(){
    document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
    document.getElementById('login_btn').style = "display: block";
    document.getElementById('logout_btn').style = "display: none";
    document.getElementById('actions').style = "display: none";
    //clear previous markers
    clearMap();
    //unselect selected place
    clearTable();
}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}
<|endoftext|>


<commit_before>(function (global) {
	var segments
		,i;

	function getStyle(el, style) {
		return window.getComputedStyle(el).getPropertyCSSValue(style).cssText;
	}

	function cycle (el, callback) {
		var tweenable
			,originalLeft

		function toTheLeftToTheLeft (callback) {
			tweenable.queue({
				'to': {
					'left': '300px'
				}

				,'duration': 1500

				,'easing': 'easeInOutSine'

				,'step': function step () {
					el.style.left = this['left'];
				}

				,'callback': callback
			}).queue({
				'to': {
					'left': originalLeft
				}

				,'duration': 1500

				,'easing': 'easeInOutSine'

				,'step': function step () {
					el.style.left = this['left'];
				}

				,'callback': callback
			})
		}

		originalLeft = getStyle(el, 'left');

		tweenable = new Tweenable({
			'initialState': {
				'left': originalLeft
			}
			,'fps': 30
		});

		toTheLeftToTheLeft();
	}

	segments = document.getElementsByClassName('segment');

	for (i = 0; i < segments.length; i++) {
		(function (i) {
			setTimeout(function () {
				cycle(segments[i]);
			}, (30 * i));
		} (i));
	}

} (this));<commit_msg>Fixed some Helix demo jankiness.<commit_after>(function (global) {
	var STEP_STATE_LIMIT = 8
		,CYCLE_SPEED = 2500
		,segments
		,stepStateLists
		,i;

	function getStyle(el, style) {
		return window.getComputedStyle(el).getPropertyCSSValue(style).cssText;
	}

	function updateStepStateList (newState, stepStateList) {
		if (stepStateList.length === STEP_STATE_LIMIT) {
			stepStateList.shift();
		}

		stepStateList.push(newState);
	}

	function updateSegment (index, tweenState) {
		var segment
			,stepStateList
			,guideStateList;

		segment = segments[index];
		stepStateList = stepStateLists[index];

		if (typeof tweenState === 'undefined') {
			guideStateList = stepStateLists[index - 1];
			tweenState = guideStateList[0];
		}

		updateStepStateList(tweenState, stepStateList);
		segment.style.left = tweenState;

		if (index < segments.length - 1) {
			updateSegment (index + 1);
		}
	}

	function cycle (el, callback) {
		var tweenable
			,originalLeft

		function toTheLeftToTheLeft (callback) {

			tweenable.queue({
				'to': {
					'left': '300px'
				}

				,'duration': CYCLE_SPEED / 2

				,'easing': 'easeInOutSine'

				,'step': function step () {
					updateSegment (0, this.left);
				}

				,'callback': callback
			}).queue({
				'to': {
					'left': originalLeft
				}

				,'duration': CYCLE_SPEED / 2

				,'easing': 'easeInOutSine'

				,'step': function step () {
					updateSegment (0, this.left);
				}

				,'callback': callback
			})
		}

		originalLeft = getStyle(el, 'left');

		tweenable = new Tweenable({
			'initialState': {
				'left': originalLeft
			}
			,'fps': 30
		});

		function loop () {
			toTheLeftToTheLeft(loop);
		}

		loop();
	}

	segments = document.getElementsByClassName('segment');
	stepStateLists = [];

	for (i = 0; i < segments.length; i++) {
		stepStateLists.push([]);
	}

	cycle(segments[0]);

} (this));<|endoftext|>


<commit_before>const connectionString = `postgres://${process.env.USER}@localhost:5432/jobdata`
const pgp = require('pg-promise')()
const db = pgp(connectionString)

const deleteAll = () => {
    return db.oneOrNone("DELETE FROM job")
}

const insert = (input) => {
    db.oneOrNone("INSERT INTO job(title, company, location, datepost, URL) VALUES ($1, $2, $3, $4, $5)", input)
}

const getAllJobs = () => {
    return db.any("SELECT * FROM job")
}

module.exports = {
    deleteAll,
    insert,
    getAllJobs
}<commit_msg>Minor fixes on database.js<commit_after>const connectionString = process.env.DATABASE_URL || `postgres://${process.env.USER}@localhost:5432/jobdata`
const pgp = require('pg-promise')()
const db = pgp(connectionString)

const deleteAll = () => {
    return db.oneOrNone("DELETE FROM job")
}

const insert = (input) => {
    db.oneOrNone("INSERT INTO job(title, company, location, datepost, URL) VALUES ($1, $2, $3, $4, $5)", input)
}

const getAllJobs = () => {
    return db.any("SELECT * FROM job")
}

module.exports = {
    deleteAll,
    insert,
    getAllJobs
}<|endoftext|>


<commit_before>var Block = require('../lib/block');
var BufferReader = require('../lib/bufferreader');
var BufferWriter = require('../lib/bufferwriter');

//This example will parse the blocks in a block file.
//To use, pipe in a blk*****.dat file. e.g.:
//cat blk00000.dat | node blockreader.js

var head = null;
var body = null;

process.stdin.on('readable', function() {
  if (!head) {
    head = process.stdin.read(8);
    if (!head)
      return;
  }
  var body = process.stdin.read(head.slice(4).readUInt32LE(0));
  if (!body)
    return;
  var blockbuf = BufferWriter().write(head).write(body).concat();
  var block = Block().fromBuffer(blockbuf);
  console.log(block.toJSON());
  head = null;
  body = null;
  process.stdin.unshift(process.stdin.read());
});
<commit_msg>body is actually defined in the function<commit_after>var Block = require('../lib/block');
var BufferReader = require('../lib/bufferreader');
var BufferWriter = require('../lib/bufferwriter');

//This example will parse the blocks in a block file.
//To use, pipe in a blk*****.dat file. e.g.:
//cat blk00000.dat | node blockreader.js

var head = null;

process.stdin.on('readable', function() {
  if (!head) {
    head = process.stdin.read(8);
    if (!head)
      return;
  }
  var body = process.stdin.read(head.slice(4).readUInt32LE(0));
  if (!body)
    return;
  var blockbuf = BufferWriter().write(head).write(body).concat();
  var block = Block().fromBuffer(blockbuf);
  console.log(block.toJSON());
  head = null;
  process.stdin.unshift(process.stdin.read());
});
<|endoftext|>