<commit_before>/* global config */
import 'isomorphic-fetch';

/**
 * CONSTANTS
*/
const GET_STATIC_SUCCESS = 'static_pages/GET_STATIC_SUCCESS';
const GET_STATIC_ERROR = 'static_pages/GET_STATIC_ERROR';
const GET_STATIC_LOADING = 'static_pages/GET_STATIC_LOADING';

/**
 * REDUCER
*/
const initialState = {
  loading: false,
  error: false,
  about: {},
  getInvolved: {},
  apps: {},
  'submit-an-insight': {},
  'join-community': {},
  'develop-app': {},
  'contribute-data': {},
  topics: {}
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_STATIC_SUCCESS: {
      const staticData = {};
      staticData[action.payload.name] = action.payload.data;

      return Object.assign({}, state,
        {
          loading: false,
          error: false
        },
        staticData
      );
    }

    case GET_STATIC_ERROR: {
      return Object.assign({}, state, {
        loading: false,
        error: true
      });
    }

    case GET_STATIC_LOADING: {
      return Object.assign({}, state, {
        loading: true,
        error: false
      });
    }

    default:
      return state;
  }
}

/**
 * ACTIONS
 * - getStaticData
*/
export function getStaticData(slug) {
  return (dispatch) => {
    // Waiting for fetch from server -> Dispatch loading
    dispatch({ type: GET_STATIC_LOADING });
    return fetch(new Request(`${process.env.API_URL}/static_pages/${slug}`))
      .then((response) => {
        if (response.ok) return response.json();
        throw new Error(response.statusText);
      })
      .then((response) => {
        dispatch({
          type: GET_STATIC_SUCCESS,
          payload: { name: slug, data: response.data.attributes }
        });
      })
      .catch((err) => {
        // Fetch from server ko -> Dispatch error
        dispatch({
          type: GET_STATIC_ERROR,
          payload: err.message
        });
      });
  };
}
<commit_msg>Hotfix: forgot a static_page endpoint<commit_after>/* global config */
import 'isomorphic-fetch';

/**
 * CONSTANTS
*/
const GET_STATIC_SUCCESS = 'static_pages/GET_STATIC_SUCCESS';
const GET_STATIC_ERROR = 'static_pages/GET_STATIC_ERROR';
const GET_STATIC_LOADING = 'static_pages/GET_STATIC_LOADING';

/**
 * REDUCER
*/
const initialState = {
  loading: false,
  error: false,
  about: {},
  getInvolved: {},
  apps: {},
  'submit-an-insight': {},
  'join-community': {},
  'develop-app': {},
  'contribute-data': {},
  topics: {}
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_STATIC_SUCCESS: {
      const staticData = {};
      staticData[action.payload.name] = action.payload.data;

      return Object.assign({}, state,
        {
          loading: false,
          error: false
        },
        staticData
      );
    }

    case GET_STATIC_ERROR: {
      return Object.assign({}, state, {
        loading: false,
        error: true
      });
    }

    case GET_STATIC_LOADING: {
      return Object.assign({}, state, {
        loading: true,
        error: false
      });
    }

    default:
      return state;
  }
}

/**
 * ACTIONS
 * - getStaticData
*/
export function getStaticData(slug) {
  return (dispatch) => {
    // Waiting for fetch from server -> Dispatch loading
    dispatch({ type: GET_STATIC_LOADING });
    return fetch(new Request(`${process.env.API_URL}/static_page/${slug}`))
      .then((response) => {
        if (response.ok) return response.json();
        throw new Error(response.statusText);
      })
      .then((response) => {
        dispatch({
          type: GET_STATIC_SUCCESS,
          payload: { name: slug, data: response.data.attributes }
        });
      })
      .catch((err) => {
        // Fetch from server ko -> Dispatch error
        dispatch({
          type: GET_STATIC_ERROR,
          payload: err.message
        });
      });
  };
}
<|endoftext|>


<commit_before>javascript:(function() {

  /*
      AUTHOR:       NSF_Zebras

      Version:      1.0

      Description:  Quickly search cross posts (of highlighted link) on reddit
                    for any links posted as a comment, hoping to find the source!
                    In other words, it will show you every link that has been
                    posted as a response, including other postings.

      TODO:     1:  Progress bar for search status
                2:  Put results in a table instead of simple paragraph rows.
   */

  var globalVersion = "v1.0 - NSF_Zebras" ;

  /*Class definitions*/

  function Link( points, href, text ) {

      this.points = safelyParseInt( points, 0 ) ;
      this.href = href ;
      this.text = text ;

      this.occurrences = 1 ;

  }

  /*Script */

  function main() {

    importJQUI() ;

    var selectedLink = getSelectionLink() ;
    /*console.log( selectedLink ) ; */

    setTimeout( function(){
      run( selectedLink ) ;
    }, 0 ) ;

  }

  function run( selectedLink ) {

    jQuery.ajax({

      url: "http://www.reddit.com/submit?url=" + jQuery( selectedLink ).attr( "href" ),
      type: "GET"

    }).success( function( seenit ) {

      searchCrossPosts( seenit ) ;

    }) ;

  }

  function safelyParseInt( str, defaultVal ) {
    return parseInt( str ) || defaultVal ;
  }

  function reverseSort( a, b ) {
    return b.points - a.points ;
  }

  function searchCrossPosts( seenit ) {

    var links = new Array() ;
    var totalSubmissionsToSearch = jQuery( "a.comments", seenit ).length ;
    var submissionsSearched = 0 ;

    jQuery( "a.comments", seenit ).each( function( key, commentsUrl ) {

      /*console.debug( key + " -> " + value ) ; */
      searchSpecificPost( links, commentsUrl ) ;
      links.sort( reverseSort ) ;
      showModal( ++submissionsSearched, totalSubmissionsToSearch, links ) ;

    }) ;

  }

  function searchSpecificPost( links, commentsUrl ) {

    jQuery.ajax({

      url: commentsUrl,
      type: "GET",
      async: false

    }).success( function( data ){

      jQuery( "div.entry", data ).each( function( key, comment ) {

        var points = jQuery( "span.unvoted", comment ).text().split( " " )[ 0 ] ;
        jQuery( "div.usertext-body p a", comment ).each( function( key, commentLink ){

          if( commentLink ) {

            var link = new Link(
              points,
              jQuery( commentLink ).attr( "href" ),
              jQuery( commentLink ).text()
            ) ;

            if( link.href ) {
              links.push( link ) ;
            }

          }

        }) ;

      })  ;

    }) ;

  }

  function importJQUI(){

    if( !window.jQuery.ui ) {

      /*import jQueryUI js*/
      var fileref = document.createElement( 'script' ) ;

      fileref.setAttribute( "type", "text/javascript" ) ;
      fileref.setAttribute( "src", "//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js" ) ;

      document.getElementsByTagName( "head" )[0].appendChild( fileref ) ;

      /*import jQueryUI css (smoothness theme)*/
      var cssref = document.createElement( 'link' ) ;

      cssref.setAttribute( "rel", "stylesheet" ) ;
      cssref.setAttribute( "type", "text/css" ) ;
      cssref.setAttribute( "href", "//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" ) ;

      document.getElementsByTagName( "head" )[0].appendChild( cssref ) ;

    }

  }

  function showModal( submissionsSearched, totalSubmissionsToSearch, links ) {

    /*First remove all previously added modals*/
    jQuery( "div#ral-dialog" ).remove() ;

    var div = buildDiv( submissionsSearched, totalSubmissionsToSearch, links ) ;

    if( jQuery( "div#ral-dialog" )[0] ) {
      jQuery( "div#ral-dialog" ).html( jQuery( div ).html() ) ;
    } else {
      jQuery( "body" ).append( div ) ;
    }

    jQuery( "div#ral-dialog" ).dialog({
      width:'auto'
    }) ;

  }

  function collapseLinks( links ) {

    var linksCollapsed = new Array() ;
    var linksCollapsedIndex = new Array() ;

    for( var i = 0 ; i < links.length ; i++ ) {

      var indexOfLink = linksCollapsedIndex.indexOf( links[i].href ) ;
      if( indexOfLink == -1 ) {

        linksCollapsed.push( links[i] ) ;
        linksCollapsedIndex.push( links[i].href ) ;

      } else {

        var linkModified = linksCollapsed[ indexOfLink ] ;
        linkModified.occurrences++ ;
        linkModified.points += links[i].points ;

        linksCollapsed[ indexOfLink ] = linkModified ;

      }

    }

    return linksCollapsed ;

  }

  function buildDiv( submissionsSearched, totalSubmissionsToSearch, links ) {

    var div = "
" ;

    div += "Submissions Searched: " + submissionsSearched + "/" + totalSubmissionsToSearch + "
" ;
    div += "
Link Occurrences -> Combined Points -> Link
" ;

    links = collapseLinks( links ) ;
    for( var i = 0 ; i < links.length ; i++ ) {

      var link = links[i] ;

      if( link.href != "undefined" ) {
        div += "
" + link.occurrences + " -> " + link.points + " -> " + link.text + "
" ;
      }

    }

    div += "
" ;

    return div ;

  }

  function getSelectionLink() {

    var text = "";
    if (window.getSelection) {
      text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
      text = document.selection.createRange().text;
    }

    return $('a').filter(function(index) { return $(this).text() === text ; }) ;

  }

  main() ;

})();<commit_msg>Added known issue to comment header<commit_after>javascript:(function() {

  /*
      AUTHOR:       NSF_Zebras

      Version:      1.0

      Description:  Quickly search cross posts (of highlighted link) on reddit
                    for any links posted as a comment, hoping to find the source!
                    In other words, it will show you every link that has been
                    posted as a response, including other postings.

      TODO:     1:  Progress bar for search status
                2:  Put results in a table instead of simple paragraph rows.

      Issues:   1:  If not logged in, the search for existing posts seems to break
   */

  var globalVersion = "v1.0 - NSF_Zebras" ;

  /*Class definitions*/

  function Link( points, href, text ) {

      this.points = safelyParseInt( points, 0 ) ;
      this.href = href ;
      this.text = text ;

      this.occurrences = 1 ;

  }

  /*Script */

  function main() {

    importJQUI() ;

    var selectedLink = getSelectionLink() ;
    /*console.log( selectedLink ) ; */

    setTimeout( function(){
      run( selectedLink ) ;
    }, 0 ) ;

  }

  function run( selectedLink ) {

    jQuery.ajax({

      url: "http://www.reddit.com/submit?url=" + jQuery( selectedLink ).attr( "href" ),
      type: "GET"

    }).success( function( seenit ) {

      searchCrossPosts( seenit ) ;

    }) ;

  }

  function safelyParseInt( str, defaultVal ) {
    return parseInt( str ) || defaultVal ;
  }

  function reverseSort( a, b ) {
    return b.points - a.points ;
  }

  function searchCrossPosts( seenit ) {

    var links = new Array() ;
    var totalSubmissionsToSearch = jQuery( "a.comments", seenit ).length ;
    var submissionsSearched = 0 ;

    jQuery( "a.comments", seenit ).each( function( key, commentsUrl ) {

      /*console.debug( key + " -> " + value ) ; */
      searchSpecificPost( links, commentsUrl ) ;
      links.sort( reverseSort ) ;
      showModal( ++submissionsSearched, totalSubmissionsToSearch, links ) ;

    }) ;

  }

  function searchSpecificPost( links, commentsUrl ) {

    jQuery.ajax({

      url: commentsUrl,
      type: "GET",
      async: false

    }).success( function( data ){

      jQuery( "div.entry", data ).each( function( key, comment ) {

        var points = jQuery( "span.unvoted", comment ).text().split( " " )[ 0 ] ;
        jQuery( "div.usertext-body p a", comment ).each( function( key, commentLink ){

          if( commentLink ) {

            var link = new Link(
              points,
              jQuery( commentLink ).attr( "href" ),
              jQuery( commentLink ).text()
            ) ;

            if( link.href ) {
              links.push( link ) ;
            }

          }

        }) ;

      })  ;

    }) ;

  }

  function importJQUI(){

    if( !window.jQuery.ui ) {

      /*import jQueryUI js*/
      var fileref = document.createElement( 'script' ) ;

      fileref.setAttribute( "type", "text/javascript" ) ;
      fileref.setAttribute( "src", "//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js" ) ;

      document.getElementsByTagName( "head" )[0].appendChild( fileref ) ;

      /*import jQueryUI css (smoothness theme)*/
      var cssref = document.createElement( 'link' ) ;

      cssref.setAttribute( "rel", "stylesheet" ) ;
      cssref.setAttribute( "type", "text/css" ) ;
      cssref.setAttribute( "href", "//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" ) ;

      document.getElementsByTagName( "head" )[0].appendChild( cssref ) ;

    }

  }

  function showModal( submissionsSearched, totalSubmissionsToSearch, links ) {

    /*First remove all previously added modals*/
    jQuery( "div#ral-dialog" ).remove() ;

    var div = buildDiv( submissionsSearched, totalSubmissionsToSearch, links ) ;

    if( jQuery( "div#ral-dialog" )[0] ) {
      jQuery( "div#ral-dialog" ).html( jQuery( div ).html() ) ;
    } else {
      jQuery( "body" ).append( div ) ;
    }

    jQuery( "div#ral-dialog" ).dialog({
      width:'auto'
    }) ;

  }

  function collapseLinks( links ) {

    var linksCollapsed = new Array() ;
    var linksCollapsedIndex = new Array() ;

    for( var i = 0 ; i < links.length ; i++ ) {

      var indexOfLink = linksCollapsedIndex.indexOf( links[i].href ) ;
      if( indexOfLink == -1 ) {

        linksCollapsed.push( links[i] ) ;
        linksCollapsedIndex.push( links[i].href ) ;

      } else {

        var linkModified = linksCollapsed[ indexOfLink ] ;
        linkModified.occurrences++ ;
        linkModified.points += links[i].points ;

        linksCollapsed[ indexOfLink ] = linkModified ;

      }

    }

    return linksCollapsed ;

  }

  function buildDiv( submissionsSearched, totalSubmissionsToSearch, links ) {

    var div = "
" ;

    div += "Submissions Searched: " + submissionsSearched + "/" + totalSubmissionsToSearch + "
" ;
    div += "
Link Occurrences -> Combined Points -> Link
" ;

    links = collapseLinks( links ) ;
    for( var i = 0 ; i < links.length ; i++ ) {

      var link = links[i] ;

      if( link.href != "undefined" ) {
        div += "
" + link.occurrences + " -> " + link.points + " -> " + link.text + "
" ;
      }

    }

    div += "
" ;

    return div ;

  }

  function getSelectionLink() {

    var text = "";
    if (window.getSelection) {
      text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
      text = document.selection.createRange().text;
    }

    return $('a').filter(function(index) { return $(this).text() === text ; }) ;

  }

  main() ;

})();<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

Menubar.File = function ( editor ) {

	var container = new UI.Panel();
	container.setClass( 'menu' );

	var title = new UI.Panel();
	title.setClass( 'title' );
	title.setTextContent( 'File' );
	container.add( title );

	var options = new UI.Panel();
	options.setClass( 'options' );
	container.add( options );

	// New

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'New' );
	option.onClick( function () {

		if ( confirm( 'Any unsaved data will be lost. Are you sure?' ) ) {

			editor.clear();

		}

	} );
	options.add( option );

	//

	options.add( new UI.HorizontalRule() );

	// Import

	var fileInput = document.createElement( 'input' );
	fileInput.type = 'file';
	fileInput.addEventListener( 'change', function ( event ) {

		editor.loader.loadFile( fileInput.files[ 0 ] );

	} );

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Import' );
	option.onClick( function () {

		fileInput.click();

	} );
	options.add( option );

	//

	options.add( new UI.HorizontalRule() );

	// Export Geometry

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export Geometry' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object === null ) {

			alert( 'No object selected.' );
			return;

		}

		var geometry = object.geometry;

		if ( geometry === undefined ) {

			alert( 'The selected object doesn\'t have geometry.' );
			return;

		}

		var output = geometry.toJSON();
		output = JSON.stringify( output, null, '\t' );
		output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' );

		exportString( output, 'geometry.json' );

	} );
	options.add( option );

	// Export Object

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export Object' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object === null ) {

			alert( 'No object selected' );
			return;

		}

		var output = object.toJSON();
		output = JSON.stringify( output, null, '\t' );
		output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' );

		exportString( output, 'model.json' );

	} );
	options.add( option );

	// Export Scene

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export Scene' );
	option.onClick( function () {

		var output = editor.scene.toJSON();
		output = JSON.stringify( output, null, '\t' );
		output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' );

		exportString( output, 'scene.json' );

	} );
	options.add( option );

	// Export OBJ

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export OBJ' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object === null ) {

			alert( 'No object selected.' );
			return;

		}

		var exporter = new THREE.OBJExporter();

		exportString( exporter.parse( object ), 'model.obj' );

	} );
	options.add( option );

	// Export STL

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export STL' );
	option.onClick( function () {

		var exporter = new THREE.STLExporter();

		exportString( exporter.parse( editor.scene ), 'model.stl' );

	} );
	options.add( option );

	//

	options.add( new UI.HorizontalRule() );

	// Publish

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Publish' );
	option.onClick( function () {

		var camera = editor.camera;

		var zip = new JSZip();

		zip.file( 'index.html', [

			'<!DOCTYPE html>',
			'',
			'	',
			'		<title>three.js</title>',
			'		<meta charset="utf-8">',
			'		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">',
			'		',
			'	',
			'	',
			'		',
			'		',
			'		',
			'	',
			''

		].join( '\n' ) );

		//

		var output = editor.toJSON();
		output = JSON.stringify( output, null, '\t' );
		output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' );

		zip.file( 'app.json', output );

		//

		var manager = new THREE.LoadingManager( function () {

			location.href = 'data:application/zip;base64,' + zip.generate();

		} );

		var loader = new THREE.XHRLoader( manager );
		loader.load( 'js/libs/app.js', function ( content ) {

			zip.file( 'js/app.js', content );

		} );
		loader.load( '../build/three.min.js', function ( content ) {

			zip.file( 'js/three.min.js', content );

		} );

	} );
	options.add( option );

	/*
	// Test

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Test' );
	option.onClick( function () {

		var text = new UI.Text( 'blah' );
		editor.showDialog( text );

	} );
	options.add( option );
	*/

	//

	var exportString = function ( output, filename ) {

		var blob = new Blob( [ output ], { type: 'text/plain' } );
		var objectURL = URL.createObjectURL( blob );

		var link = document.createElement( 'a' );
		link.href = objectURL;
		link.download = filename || 'data.json';
		link.target = '_blank';
		link.click();

	};

	return container;

};
<commit_msg>Editor: Published project now listens to window resize.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

Menubar.File = function ( editor ) {

	var container = new UI.Panel();
	container.setClass( 'menu' );

	var title = new UI.Panel();
	title.setClass( 'title' );
	title.setTextContent( 'File' );
	container.add( title );

	var options = new UI.Panel();
	options.setClass( 'options' );
	container.add( options );

	// New

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'New' );
	option.onClick( function () {

		if ( confirm( 'Any unsaved data will be lost. Are you sure?' ) ) {

			editor.clear();

		}

	} );
	options.add( option );

	//

	options.add( new UI.HorizontalRule() );

	// Import

	var fileInput = document.createElement( 'input' );
	fileInput.type = 'file';
	fileInput.addEventListener( 'change', function ( event ) {

		editor.loader.loadFile( fileInput.files[ 0 ] );

	} );

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Import' );
	option.onClick( function () {

		fileInput.click();

	} );
	options.add( option );

	//

	options.add( new UI.HorizontalRule() );

	// Export Geometry

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export Geometry' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object === null ) {

			alert( 'No object selected.' );
			return;

		}

		var geometry = object.geometry;

		if ( geometry === undefined ) {

			alert( 'The selected object doesn\'t have geometry.' );
			return;

		}

		var output = geometry.toJSON();
		output = JSON.stringify( output, null, '\t' );
		output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' );

		exportString( output, 'geometry.json' );

	} );
	options.add( option );

	// Export Object

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export Object' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object === null ) {

			alert( 'No object selected' );
			return;

		}

		var output = object.toJSON();
		output = JSON.stringify( output, null, '\t' );
		output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' );

		exportString( output, 'model.json' );

	} );
	options.add( option );

	// Export Scene

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export Scene' );
	option.onClick( function () {

		var output = editor.scene.toJSON();
		output = JSON.stringify( output, null, '\t' );
		output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' );

		exportString( output, 'scene.json' );

	} );
	options.add( option );

	// Export OBJ

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export OBJ' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object === null ) {

			alert( 'No object selected.' );
			return;

		}

		var exporter = new THREE.OBJExporter();

		exportString( exporter.parse( object ), 'model.obj' );

	} );
	options.add( option );

	// Export STL

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Export STL' );
	option.onClick( function () {

		var exporter = new THREE.STLExporter();

		exportString( exporter.parse( editor.scene ), 'model.stl' );

	} );
	options.add( option );

	//

	options.add( new UI.HorizontalRule() );

	// Publish

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Publish' );
	option.onClick( function () {

		var camera = editor.camera;

		var zip = new JSZip();

		zip.file( 'index.html', [

			'<!DOCTYPE html>',
			'',
			'	',
			'		<title>three.js</title>',
			'		<meta charset="utf-8">',
			'		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">',
			'		',
			'	',
			'	',
			'		',
			'		',
			'		',
			'	',
			''

		].join( '\n' ) );

		//

		var output = editor.toJSON();
		output = JSON.stringify( output, null, '\t' );
		output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' );

		zip.file( 'app.json', output );

		//

		var manager = new THREE.LoadingManager( function () {

			location.href = 'data:application/zip;base64,' + zip.generate();

		} );

		var loader = new THREE.XHRLoader( manager );
		loader.load( 'js/libs/app.js', function ( content ) {

			zip.file( 'js/app.js', content );

		} );
		loader.load( '../build/three.min.js', function ( content ) {

			zip.file( 'js/three.min.js', content );

		} );

	} );
	options.add( option );

	/*
	// Test

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Test' );
	option.onClick( function () {

		var text = new UI.Text( 'blah' );
		editor.showDialog( text );

	} );
	options.add( option );
	*/

	//

	var exportString = function ( output, filename ) {

		var blob = new Blob( [ output ], { type: 'text/plain' } );
		var objectURL = URL.createObjectURL( blob );

		var link = document.createElement( 'a' );
		link.href = objectURL;
		link.download = filename || 'data.json';
		link.target = '_blank';
		link.click();

	};

	return container;

};
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2015 Tim Rozycki

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

*/

SafeProxy = {};

SafeProxy.safe = function(funcToProxy){
	var result = function(){
		try{
			funcToProxy.apply(undefined, arguments);
		}
		catch(err){
			handler = function(){
				throw err;
			};
			setTimeout(handler, 1);
		};
	};
	return result;
};

SafeProxy.safeParameters = function(funcToProxy){
	var result = function(){
		safeArguments = [];
		if(arguments && arguments.length){
			for(index=0; index < arguments.length; ++index){
				unsafeArg = arguments[index];
				if(typeof(unsafeArg)==="function"){
					safeArguments.push(SafeProxy.safe(unsafeArg))
				}
				else{
					safeArguments.push(unsafeArg);
				}
			};
		}
		//TODO: write a test that fails when we pass undefined rather than this, as the first argument to apply().
		// For example, wrapping jQuery's .on() method will cause errors.
		//Get a full understanding of what's happening here and make the right fix if just passing "this" is not always correct.
		funcToProxy.apply(this, safeArguments);
	};
	return result;
}<commit_msg>added TODO for testing correct use of "this" parameter when calling .apply for proxied function.<commit_after>/*
The MIT License (MIT)

Copyright (c) 2015 Tim Rozycki

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

*/

SafeProxy = {};

SafeProxy.safe = function(funcToProxy){
	var result = function(){
		try{
			//TODO: write a test to prove that passing "this" through is necessary and correct
			funcToProxy.apply(this, arguments);
		}
		catch(err){
			handler = function(){
				throw err;
			};
			setTimeout(handler, 1);
		};
	};
	return result;
};

SafeProxy.safeParameters = function(funcToProxy){
	var result = function(){
		safeArguments = [];
		if(arguments && arguments.length){
			for(index=0; index < arguments.length; ++index){
				unsafeArg = arguments[index];
				if(typeof(unsafeArg)==="function"){
					safeArguments.push(SafeProxy.safe(unsafeArg))
				}
				else{
					safeArguments.push(unsafeArg);
				}
			};
		}
		//TODO: write a test to prove that passing "this" through is necessary and correct
		funcToProxy.apply(this, safeArguments);
	};
	return result;
}<|endoftext|>


<commit_before>;(function() {

    // EXT
    // (obj notation)
    var buildElement = function buildElement (parentConfig) {

        var temp = document.createElement(parentConfig[0]);
        if( parentConfig[1] ) temp.setAttribute('class', parentConfig[1]);
        if( parentConfig[2] ) temp.setAttribute('style', parentConfig[2]);

        if ( parentConfig.length > 3 ) {
            var i = 3, l = parentConfig.length;
            for(; i < l; i++) {
                temp.appendChild(buildElement(parentConfig[i]));
            }
        }

        return temp;

    };

    // Listen for share button clicks
    var share = {};
    $('body').on('click', 'a.share_action_link', function (e) {
        var $parent = $(this).closest('.genericStreamStory, .fbTimelineUnit');

		// reset share object on every 'share' button click
		share = {};

		// find the name of the person that shared the attachment
		share.via = $('.passiveName', $parent).first().text() || $('.actorName', $parent).first().text();

		// find the message for this attachment, or if none use the attachment caption
		// .tlTxFe is used on new timeline
		share.text = $('.messageBody, .tlTxFe', $parent).first().text() || $('.caption', $parent).text();

		var thumb = $('.uiPhotoThumb img, .photoUnit img', $parent).attr('src');
		var url = $('.uiAttachmentTitle a, a.externalShareUnit', $parent).attr('href');

		// find picture status
		if( thumb ) {
			// convert the thumbnail link to a link to the fullsize image
			share.picture = thumb.replace(/s[0-9]+x[0-9]+\//, '');

			// we pass the source of the image for the 'found at' text
			share.url = $('a.uiPhotoThumb, a.photo', $parent).attr('href');

			share.placement = 'facebook-share-picture';
		}

		// find link status
		else if (url) {
			if( url[0] == "/" ) url = "https://facebook.com" + url;
			share.url = url;
			share.placement = 'facebook-share-link';
		}

		// standard text status
		else
		{
			share.placement = 'facebook-share-status';
		}
    });

    var config = {};
    config.base = "https://facebook.com";
    config.time = {
        reload: 800
    };
    config.buttons = [
        {
            name: "status",
            text: "Buffer",
            container: 'ul.uiComposerBarRightArea',
            after: '.privacyWidget',
            className: 'buffer-facebook-button',
            selector: '.buffer-facebook-button',
            elements:
                    ['li', 'pls uiListItem uiListHorizontalItemBorder uiListHorizontalItem', '',
                        ['label', '', '',
                            ['a', 'buffer-facebook-button']
                        ]
                    ],
            default: 'background: hsl(116, 39%, 45%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); border: 1px solid #40873B; color: white !important;padding: 3px 10px;margin-top: 0px;display: block;',
            style:   'background: hsl(116, 39%, 45%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); border: 1px solid #40873B; color: white !important;padding: 3px 10px;margin-top: 0px;display: block;',
            hover:   'background: hsl(116, 39%, 42%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 42%) 95%, hsl(116, 39%, 55%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 42%) 95%, hsl(116, 39%, 55%) 96%); text-decoration: none;',
            active:  'background: hsl(116, 39%, 40%); text-decoration: none;',
            create: function (btnConfig) {

                var temp = buildElement(btnConfig.elements);

                var a = $(temp).find(btnConfig.selector)[0];
                a.setAttribute('style', btnConfig.default);
                a.setAttribute('href', '#');
                $(a).text(btnConfig.text);

                $(a).hover(function () {
                    if( $(this).hasClass("disabled") ) {
                        $(this).attr('style', btnConfig.default);
                        return;
                    }
                    $(this).attr('style', btnConfig.style + btnConfig.hover);
                }, function() {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style);
                });

                $(a).mousedown(function () {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style + btnConfig.active);
                });

                $(a).mouseup(function () {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style + btnConfig.hover);
                });

                return temp;

            },
            data: function (elem) {
                return {
                    text: $(elem).closest('.uiMetaComposerMessageBox').find('textarea.textInput').val(),
                    placement: 'facebook-composer'
                }
            },
            clear: function (elem) {
                $(elem).closest('.uiMetaComposerMessageBox').find('textarea.textInput').val('');
            }
        },
        {
            name: "share",
            text: "Buffer",
            container: 'div.uiOverlayFooter',
            before: '.uiButtonConfirm',
            className: 'buffer-facebook-button',
            selector: '.buffer-facebook-button',
            elements: ['a', 'buffer-facebook-button uiOverlayButton uiButton uiButtonLarge'],
            default: 'background: hsl(116, 39%, 45%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); border: 1px solid #40873B; color: white !important;padding: 3px 6px 4px;',
            style:   'background: hsl(116, 39%, 45%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); border: 1px solid #40873B; color: white !important;padding: 3px 6px 4px;',
            hover:   'background: hsl(116, 39%, 42%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 42%) 95%, hsl(116, 39%, 55%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 42%) 95%, hsl(116, 39%, 55%) 96%); text-decoration: none;',
            active:  'background: hsl(116, 39%, 40%); text-decoration: none;',
            create: function (btnConfig) {

                var temp = buildElement(btnConfig.elements);

                var a = $(temp).find(btnConfig.selector)[0];
                if( ! a ) a = temp; // EXT
                a.setAttribute('style', btnConfig.default);
                a.setAttribute('href', '#');
                $(a).text(btnConfig.text); // EXT

                $(a).hover(function () {
                    if( $(this).hasClass("disabled") ) {
                        $(this).attr('style', btnConfig.default);
                        return;
                    }
                    $(this).attr('style', btnConfig.style + btnConfig.hover);
                }, function() {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style);
                });

                $(a).mousedown(function () {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style + btnConfig.active);
                });

                $(a).mouseup(function () {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style + btnConfig.hover);
                });

                return temp;

            },
            data: function (elem) {

                var $parent = $(elem).closest('.modalWrapper');

				// if the user has written a message, allow this to override the default text
                var text = $('div.textInput textarea', $parent).val();
                if( text === "Write something" ) text = undefined;
                if( text ) share.text = text;

				// fallback placement when we don't know if the attachment is a picture, link or status
				if( !share.placement ) share.placement = 'facebook-share';

				return share;
            },
            clear: function (elem) {
                share = {};
            }
        }
    ];

    ;(function bufferEmbed() {

        var insertButtons = function () {

            var i, l=config.buttons.length;
            for ( i=0 ; i < l; i++ ) {

                var btnConfig = config.buttons[i];

                $(btnConfig.container).each(function () {

                    var container = $(this);

                    if ( $(container).hasClass('buffer-inserted') ) return;

                    $(container).addClass('buffer-inserted');

                    var btn = btnConfig.create(btnConfig);

                    // EXT
                    if ( btnConfig.after ) $(container).find(btnConfig.after).after(btn);
                    else if ( btnConfig.before ) $(container).find(btnConfig.before).before(btn);
                    else $(container).append(btn);

                    if ( !! btnConfig.activator ) btnConfig.activator(btn, btnConfig);

                    if ( !! btnConfig.lastly ) btnConfig.lastly(btn, btnConfig);

                    var getData = btnConfig.data;
                    var clearData = btnConfig.clear;

                    var clearcb = function () {};

                    $(btn).click(function (e) {
                        clearcb = function () { // allow clear to be called for this button
                            if ( !! clearData ) clearData(btn);
                        };
                        xt.port.emit("buffer_click", getData(btn));
                        e.preventDefault();
                    });

                    xt.port.on("buffer_embed_clear", function () {
                        clearcb();
                        clearcb = function () {}; // prevent clear from being called again, until the button is clicked again
                    });

                });

            }

        };

        insertButtons();

        setTimeout(bufferEmbed, config.time.reload);

    }());

}());<commit_msg>Fixed: Facebook share message & popping up in weird places.<commit_after>;(function() {

    // EXT
    // (obj notation)
    var buildElement = function buildElement (parentConfig) {

        var temp = document.createElement(parentConfig[0]);
        if( parentConfig[1] ) temp.setAttribute('class', parentConfig[1]);
        if( parentConfig[2] ) temp.setAttribute('style', parentConfig[2]);

        if ( parentConfig.length > 3 ) {
            var i = 3, l = parentConfig.length;
            for(; i < l; i++) {
                temp.appendChild(buildElement(parentConfig[i]));
            }
        }

        return temp;

    };

    // Listen for share button clicks
    var share = {};
    $('body').on('click', 'a.share_action_link', function (e) {
        var $parent = $(this).closest('.genericStreamStory, .fbTimelineUnit');

		// reset share object on every 'share' button click
		share = {};

		// find the name of the person that shared the attachment
		share.via = $('.passiveName', $parent).first().text() || $('.actorName', $parent).first().text();

		// find the message for this attachment, or if none use the attachment caption
		// .tlTxFe is used on new timeline
		share.text = $('.messageBody, .tlTxFe', $parent).first().text() || $('.caption', $parent).text();

		var thumb = $('.uiPhotoThumb img, .photoUnit img', $parent).attr('src');
		var url = $('.uiAttachmentTitle a, a.externalShareUnit', $parent).attr('href');

		// find picture status
		if( thumb ) {
			// convert the thumbnail link to a link to the fullsize image
			share.picture = thumb.replace(/s[0-9]+x[0-9]+\//, '');

			// we pass the source of the image for the 'found at' text
			share.url = $('a.uiPhotoThumb, a.photo', $parent).attr('href');

			share.placement = 'facebook-share-picture';
		}

		// find link status
		else if (url) {
			if( url[0] == "/" ) url = "https://facebook.com" + url;
			share.url = url;
			share.placement = 'facebook-share-link';
		}

		// standard text status
		else
		{
			share.placement = 'facebook-share-status';
		}
    });

    var config = {};
    config.base = "https://facebook.com";
    config.time = {
        reload: 800
    };
    config.buttons = [
        {
            name: "status",
            text: "Buffer",
            container: 'ul.uiComposerBarRightArea',
            after: '.privacyWidget',
            className: 'buffer-facebook-button',
            selector: '.buffer-facebook-button',
            elements:
                    ['li', 'pls uiListItem uiListHorizontalItemBorder uiListHorizontalItem', '',
                        ['label', '', '',
                            ['a', 'buffer-facebook-button']
                        ]
                    ],
            default: 'background: hsl(116, 39%, 45%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); border: 1px solid #40873B; color: white !important;padding: 3px 10px;margin-top: 0px;display: block;',
            style:   'background: hsl(116, 39%, 45%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); border: 1px solid #40873B; color: white !important;padding: 3px 10px;margin-top: 0px;display: block;',
            hover:   'background: hsl(116, 39%, 42%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 42%) 95%, hsl(116, 39%, 55%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 42%) 95%, hsl(116, 39%, 55%) 96%); text-decoration: none;',
            active:  'background: hsl(116, 39%, 40%); text-decoration: none;',
            create: function (btnConfig) {

                var temp = buildElement(btnConfig.elements);

                var a = $(temp).find(btnConfig.selector)[0];
                a.setAttribute('style', btnConfig.default);
                a.setAttribute('href', '#');
                $(a).text(btnConfig.text);

                $(a).hover(function () {
                    if( $(this).hasClass("disabled") ) {
                        $(this).attr('style', btnConfig.default);
                        return;
                    }
                    $(this).attr('style', btnConfig.style + btnConfig.hover);
                }, function() {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style);
                });

                $(a).mousedown(function () {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style + btnConfig.active);
                });

                $(a).mouseup(function () {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style + btnConfig.hover);
                });

                return temp;

            },
            data: function (elem) {
                return {
                    text: $(elem).closest('.uiMetaComposerMessageBox').find('textarea.textInput').val(),
                    placement: 'facebook-composer'
                }
            },
            clear: function (elem) {
                $(elem).closest('.uiMetaComposerMessageBox').find('textarea.textInput').val('');
            }
        },
        {
            name: "share",
            text: "Buffer",
            container: 'form[action="/ajax/sharer/submit/"] div.uiOverlayFooter',
            before: '.uiButtonConfirm',
            className: 'buffer-facebook-button',
            selector: '.buffer-facebook-button',
            elements: ['a', 'buffer-facebook-button uiOverlayButton uiButton uiButtonLarge'],
            default: 'background: hsl(116, 39%, 45%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); border: 1px solid #40873B; color: white !important;padding: 3px 6px 4px;',
            style:   'background: hsl(116, 39%, 45%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 45%) 95%, hsl(116, 39%, 60%) 96%); border: 1px solid #40873B; color: white !important;padding: 3px 6px 4px;',
            hover:   'background: hsl(116, 39%, 42%); background: -webkit-linear-gradient(bottom, hsl(116, 39%, 42%) 95%, hsl(116, 39%, 55%) 96%); background: -moz-linear-gradient(bottom, hsl(116, 39%, 42%) 95%, hsl(116, 39%, 55%) 96%); text-decoration: none;',
            active:  'background: hsl(116, 39%, 40%); text-decoration: none;',
            create: function (btnConfig) {

                var temp = buildElement(btnConfig.elements);

                var a = $(temp).find(btnConfig.selector)[0];
                if( ! a ) a = temp; // EXT
                a.setAttribute('style', btnConfig.default);
                a.setAttribute('href', '#');
                $(a).text(btnConfig.text); // EXT

                $(a).hover(function () {
                    if( $(this).hasClass("disabled") ) {
                        $(this).attr('style', btnConfig.default);
                        return;
                    }
                    $(this).attr('style', btnConfig.style + btnConfig.hover);
                }, function() {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style);
                });

                $(a).mousedown(function () {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style + btnConfig.active);
                });

                $(a).mouseup(function () {
                    if( $(this).hasClass("disabled") ) return;
                    $(this).attr('style', btnConfig.style + btnConfig.hover);
                });

                return temp;

            },
            data: function (elem) {

                var $parent = $(elem).closest('.modalWrapper');

				// if the user has written a message, allow this to override the default text
                var text = $('textarea[name="message_text"]', $parent).val();
                if( text === "Write something" ) text = undefined;
                if( text ) share.text = text;

				// fallback placement when we don't know if the attachment is a picture, link or status
				if( !share.placement ) share.placement = 'facebook-share';

				return share;
            },
            clear: function (elem) {
                share = {};
            }
        }
    ];

    ;(function bufferEmbed() {

        var insertButtons = function () {

            var i, l=config.buttons.length;
            for ( i=0 ; i < l; i++ ) {

                var btnConfig = config.buttons[i];

                $(btnConfig.container).each(function () {

                    var container = $(this);

                    if ( $(container).hasClass('buffer-inserted') ) return;

                    $(container).addClass('buffer-inserted');

                    var btn = btnConfig.create(btnConfig);

                    // EXT
                    if ( btnConfig.after ) $(container).find(btnConfig.after).after(btn);
                    else if ( btnConfig.before ) $(container).find(btnConfig.before).before(btn);
                    else $(container).append(btn);

                    if ( !! btnConfig.activator ) btnConfig.activator(btn, btnConfig);

                    if ( !! btnConfig.lastly ) btnConfig.lastly(btn, btnConfig);

                    var getData = btnConfig.data;
                    var clearData = btnConfig.clear;

                    var clearcb = function () {};

                    $(btn).click(function (e) {
                        clearcb = function () { // allow clear to be called for this button
                            if ( !! clearData ) clearData(btn);
                        };
                        xt.port.emit("buffer_click", getData(btn));
                        e.preventDefault();
                    });

                    xt.port.on("buffer_embed_clear", function () {
                        clearcb();
                        clearcb = function () {}; // prevent clear from being called again, until the button is clicked again
                    });

                });

            }

        };

        insertButtons();

        setTimeout(bufferEmbed, config.time.reload);

    }());

}());<|endoftext|>


<commit_before>/*
 * goTo - smooth, non-expensive way for scrolling elements using rAF
 * https://github.com/pjetrucha/goTo
 *
 * @author Piotr Chrobak
 * @license MIT
 */
(function($, window, document){
	"use strict";

	var defaults = {
		el: window,
		to: 0,
		speed: 500,
		calculate: false,
		callback: null,
		listen: true,
		easing: function easeOutCubic(currentIteration, startValue, changeInValue, totalIterations){
			return changeInValue * (Math.pow(currentIteration / totalIterations - 1, 3) + 1) + startValue;
		}
	};

	function goTo(opts){

		var config = $.extend({}, defaults, opts);

		/* if `to` equals 0 there's no need to calculate */
		if(config.to !== 0 && config.calculate){
			config.to = Math.min(Math.max(0, config.to), config.el === window ?
				document.documentElement.scrollHeight - window.innerHeight :
				config.el.scrollHeight - config.el.offsetHeight
			);
		}

		var step = 0,
			max = Math.round(Math.max(1, (config.speed / 16.666))),
			from = getPos(),
			stopped = false,
			setPos = config.el === window ? function(pos){
				window.scrollTo(0, pos);
			} : function(pos){
				config.el.scrollTop = pos;
			};

		/* if distance is empty just skip */
		if(from === config.to){
			step = max + 1;
		}
		else if(config.listen){
			$(config.el).one('mousewheel.goTo DOMMouseScroll.goTo', stop);
		}

		function stop(){
			stopped = true;
		}

		function getPos(){
			if(config.el === window){
				if(document.documentElement.scrollTop == 0){
					return document.body.scrollTop;
				}
				else{
					return document.documentElement.scrollTop;
				}
			}
			else return config.el.scrollTop;
		}

		void function loop(){
			if(!stopped && step <= max){
				requestAnimationFrame(loop);
				setPos(config.easing(step, from, -from + config.to, max));
				step++;
			}
			else{
				if(config.listen) $(config.el).off('mousewheel.goTo DOMMouseScroll.goTo');
				if(typeof config.callback == 'function') config.callback.call(config.el, stopped);
			}
		}();

	}

	window.goTo = function(opts){
		new goTo(opts);
	}

	$.fn.goTo = function(opts){
		return this.each(function(){
			new goTo($.extend({}, opts, {el: this}));
		});
	}

})(jQuery, window, document);
<commit_msg>added X and Y dir support<commit_after>/*
 * goTo - smooth, non-expensive way for scrolling elements using rAF
 * https://github.com/pjetrucha/goTo
 *
 * @author Piotr Chrobak
 * @license MIT
 */
(function($, window, document){
	"use strict";

	var defaults = {
		el: window,
		to: {x: null, y: null},
		speed: 500,
		calculate: false,
		callback: null,
		listen: true,
		easing: function easeOutCubic(currentIteration, startValue, changeInValue, totalIterations){
			return changeInValue * (Math.pow(currentIteration / totalIterations - 1, 3) + 1) + startValue;
		}
	};

	function goTo(opts){

		var config = $.extend(true, {}, defaults, opts);

		/* backward compatibility */
		if(typeof config.to === "number"){
			config.to = $.extend({}, defaults.to, {y: config.to});
		}

		if(config.calculate){
			/* if `to` equals 0 || null there's no need to calculate */
			if(config.to.x){
				config.to.x = Math.min(Math.max(0, config.to.x), config.el === window ?
					document.documentElement.scrollWidth - window.innerWidth :
					config.el.scrollWidth - config.el.offsetWidth
				);
			}
			if(config.to.y){
				config.to.y = Math.min(Math.max(0, config.to.y), config.el === window ?
					document.documentElement.scrollHeight - window.innerHeight :
					config.el.scrollHeight - config.el.offsetHeight
				);
			}
		}

		var step = 0,
			max = Math.round(Math.max(1, (config.speed / 16.666))),
			from = getPos(),
			stopped = false,
			setPos = config.el === window ? window.scrollTo : function(x, y){
				config.el.scrollLeft = x;
				config.el.scrollTop = y;
			},
			skip = {
				x: config.to.x === null,
				y: config.to.y === null
			};

		/* if distance is empty just skip */
		if(from.x === config.to.x && from.y === config.to.y){
			step = max + 1;
		}
		else if(config.listen){
			$(config.el).one('mousewheel.goTo DOMMouseScroll.goTo', stop);
		}

		function stop(){
			stopped = true;
		}

		function getElement(){
			if(config.el === window){
				if(document.documentElement.scrollTop == 0){
					return document.body;
				}
				else{
					return document.documentElement;
				}
			}
			else return config.el;
		}

		function getPos(){
			var el = getElement();
			return {
				x: el.scrollLeft,
				y: el.scrollTop
			};
		}

		void function loop(){
			if(!stopped && step <= max){
				requestAnimationFrame(loop);
				setPos(
					skip.x ? from.x : config.easing(step, from.x, -from.x + config.to.x, max),
					skip.y ? from.y : config.easing(step, from.y, -from.y + config.to.y, max)
				);
				step++;
			}
			else{
				if(config.listen) $(config.el).off('mousewheel.goTo DOMMouseScroll.goTo');
				if(typeof config.callback == 'function') config.callback.call(config.el, stopped);
			}
		}();

	}

	window.goTo = function(opts){
		new goTo(opts);
	}

	$.fn.goTo = function(opts){
		return this.each(function(){
			new goTo($.extend({}, opts, {el: this}));
		});
	}

})(jQuery, window, document);
<|endoftext|>


<commit_before>/*
 * A node.js script to rename a ebook file by given isdn.

 * Google Book API:
 * https://www.googleapis.com/books/v1/volumes?q=isbn:<your_isbn_here>
 * https://www.googleapis.com/books/v1/volumes?q=isbn:1617290572
 */
'use strict'; //strict mode
var util = require('util');
var request = require('request');
var fs = require('fs');
var path = require('path');
var cheerio = require('cheerio');
var child_process = require('child_process');
var echo = console.log;

/* Consts*/
var homedir = (process.platform === 'win32') ? process.env.USERPROFILE : process.env.HOME;
//echo (homedir)
//var BOOK_SAVE_PATH="C:\\Users\\yidwu\\Downloads\\_Un"
var BOOK_SAVE_PATH=path.join(homedir,"Downloads","_Un"); //cross-platform path
/* Regxp */
var DATE_REGXP=/(January|February|March|April|May|June|July|August|September|October|November|December).*/
var ISBN10_REGXP=/^\d{9}[\d|X]/
var ISBN13_REGXP=/^(978|979)(?:-|)\d{9}[\d|X]/
var EDTION_REGXP=/^\d{1}$/
var ASIN_REGXP=/^[A-Z0-9]{10}/

function requestByGoogleBook(changeNameJob,isbn){
    var reqBody = {
        method:'GET',
        uri: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn
    };
    request(reqBody,function(err,rep,body){
        if(rep.statusCode == 200){

            var jsObject = JSON.parse(body);
            echo("------------------------------------------------------------")
            echo(reqBody.uri)
            var newName = [];
            if (jsObject.items == undefined) {
                echo ('Error :'+isbn+", no result found!")
                return
            }
            var title=jsObject.items[0].volumeInfo.title.trim();
            var subtitle=jsObject.items[0].volumeInfo.subtitle;
            var date=jsObject.items[0].volumeInfo.publishedDate.trim();

            if (subtitle != undefined) title = title+" - "+subtitle.trim();
            newName.push(title);
            newName.push(date.substr(0,7));
            newName.push(isbn);
            newName = newName.join(", ");

            echo("Title    :",title);
            echo("Pub Date :",date);
            echo("New Name :",newName)

            changeNameJob.changeName(newName);
        }else{
            echo('error :',rep.statusCode);
            echo(body);

        }
    });
}

//requestByIsbn(doBookName,'1617290572');

function requestByAmazon(changeNameJob,ASIN){
    var reqBody = {
        method:'GET',
        uri: 'http://www.amazon.com/dp/' + ASIN
    };
    request(reqBody,function(err,rep,body){
        if(rep.statusCode == 200){
            echo("------------------------------------------------------------")
            echo(reqBody.uri)
            var $ = cheerio.load(body);
            var newName = [];
            var title="";
            var type ="";
            if ($('#btAsinTitle').children().get(0)!==undefined){
                title = $('#btAsinTitle').children().get(0).prev.data.trim();
                type  = $('#btAsinTitle').children().text().trim();
            }else if($('#productTitle').text()!==undefined){
                title = $('#productTitle').text();
            }
            title = title.replace(/:/g," -");
            title = title.replace(/\//g,"&")

            var date
            var pubdate = $('#pubdate').val();

            if (pubdate === undefined) {
                $('div[class=buying]').find('span[style="font-weight: bold;"]').each(function() {
                    //echo("----------------")
                    var text = $(this).text().trim();
                    //echo(text);
                    if (DATE_REGXP.test(text)){
                        echo("Pub Date :",text);
                        pubdate = Date.parse(text);
                    }else if (ISBN13_REGXP.test(text)){
                        echo("ISDN_13  :",text);
                    }
                    else if(ISBN10_REGXP.test(text)){
                        echo("ISDN_10  :",text);
                    }else if(EDTION_REGXP.test(text)){
                        echo("Edtion   :",text);
                    }

                });
            }
            if (pubdate !== undefined) {
                date = new Date(pubdate);
                //Notice, getMonth return 0 to 11
                date = (date.getMonth()<10) ? date.getFullYear()+"-0"+(date.getMonth()+1)
                                            : date.getFullYear()+"-"+(date.getMonth()+1);
            }

            newName.push(title);
            newName.push(date);
            newName.push(ASIN);
            newName = newName.join(", ")

            echo("Type     :",type)
            echo("Title    :",title);
            echo("New Name :",newName)

            changeNameJob.changeName(newName);
        }else{
            echo("------------------------------------------------------------")
            echo("Fail to query",reqBody.uri);
            echo("Error :",rep.statusCode);
            echo("Try to use googlebook API");
            requestByGoogleBook(changeNameJob,ASIN);
        }
    });
}

function ChangeNameJob(parentDir,orginalFileName,fileExt){
    this.parentDir=parentDir;
    this.fileName=orginalFileName;
    this.fileExt=fileExt;
}
ChangeNameJob.prototype.changeName = function (newName){
    //check existed
    echo(this.fileName,"->",newName+this.fileExt);
    if (fs.existsSync(path.join(this.parentDir,newName+this.fileExt))) {
        newName = newName+"_"+Date.now();;
        echo("WARNING:","File exists!","->",newName+this.fileExt);

    }
    fs.rename(
        path.join(this.parentDir,this.fileName),
        path.join(this.parentDir,newName+this.fileExt),
        function (err) {
            if (err) echo('rename callback ', err);
        });
}

function parseISBN(name){
    //echo("parseISBN",name)
    var isbn
    if (ISBN13_REGXP.test(name)) {
        isbn=ISBN13_REGXP.exec(name)[0];
    }
    else if (ISBN10_REGXP.test(name)){
        isbn = ISBN10_REGXP.exec(name)[0];
    }
    else if (ASIN_REGXP.test(name)) {
        isbn=ASIN_REGXP.exec(name)[0];
    }
    return isbn;
}

function renameBook(parentDir,file){
    //echo("enter",parentDir,file);
    if (!fs.statSync(path.join(parentDir,file)).isDirectory()){
        var fileName=file;
        var fileExt=path.extname(fileName);
        var fileBaseName=path.basename(fileName,fileExt);

        var isbn = parseISBN(fileBaseName);
        if (isbn === undefined){
            isbn = parseISBN(path.basename(parentDir));
        }
        if (isbn === undefined){
            echo("WARNING :","Can't parse a isdn or asin from given name : [",fileName,"]");
            return;
        }
        if (fileExt===".rar"){
            //uncompressRarFile(fileName,isbn);

        }else{
            echo("ChangeNameJob",parentDir,fileName,fileExt);
            var job = new ChangeNameJob(parentDir,fileName,fileExt);
            requestByAmazon(job,isbn);
        }

    }else{
        echo("folder",file);
        var isbn = parseISBN(file);
        if (isbn === undefined){
            echo("WARNING :","Can't parse a isdn or asin from given name : [",fileName,"]");
            return;
        }
        echo(isbn)
        fs.readdir(path.join(parentDir,isbn),
                function(err,unzipfiles){
                    unzipfiles.forEach(function(unzipfile){
                        echo("unzipfile",unzipfile);
                        renameBook(path.join(parentDir,isbn),unzipfile)})});
    }
}

function uncompressRarFile(rarfile,isbn){
    if (fs.statSync(path.join(BOOK_SAVE_PATH,rarfile)).isDirectory()) return;
    var fileExt=path.extname(rarfile);
    if (fileExt === ".rar") {
        var outputDir=path.join(BOOK_SAVE_PATH,isbn);
        var rarfilePath = path.join(BOOK_SAVE_PATH,rarfile);
        var _7zCmd = "7z x -o"+outputDir+" "+rarfilePath+" -y";
        echo(_7zCmd);
        child_process.exec(_7zCmd, function (error, stdout, stderr) {
                if (stdout !== null && stdout !== "") {
                    echo('stdout: ',stdout);
                }
                if (error !== null) {
                    echo("Execute:",_7zCmd,"Failed!");
                    console.error( error.stack );
                }else{
                    echo("Execute:",_7zCmd,"Done!");
                    echo("Removed the rar file.")
                    fs.unlinkSync(rarfilePath);
                    waitFor.count();
                }
        });
    }
}

var numberOfRarFiles=0;
fs.readdirSync(BOOK_SAVE_PATH).forEach(function(file){
    if (path.extname(file)===".rar"){
        var isbn = parseISBN(file);
        if (isbn !== undefined){
            numberOfRarFiles++;
        }
    }
});

function WaitForFinished(number){
    this.counter = number;
}

WaitForFinished.prototype.count = function () {
    if (this.counter !==0) this.counter --;
    if (this.counter == 0) {
        echo("------------------------------------------------------------------Starting renaming...")
        fs.readdir(BOOK_SAVE_PATH,function(err,files){files.forEach(function(file){renameBook(BOOK_SAVE_PATH,file)})})
    }
}
//echo(numberOfRarFiles)

var waitFor = new WaitForFinished(numberOfRarFiles);
if (numberOfRarFiles === 0) waitFor.count();

fs.readdir(BOOK_SAVE_PATH,function(err,files){files.forEach(function(file){
    if (path.extname(file)===".rar"){
        var isbn = parseISBN(file);
        if (isbn !== undefined){
            uncompressRarFile(file,isbn);
        }
    }
})});

<commit_msg>also change file date when do rename.<commit_after>/*
 * A node.js script to rename a ebook file by given isdn.

 * Google Book API:
 * https://www.googleapis.com/books/v1/volumes?q=isbn:<your_isbn_here>
 * https://www.googleapis.com/books/v1/volumes?q=isbn:1617290572
 */
'use strict'; //strict mode
var util = require('util');
var request = require('request');
var fs = require('fs');
var path = require('path');
var cheerio = require('cheerio');
var child_process = require('child_process');
var echo = console.log;

/* Consts*/
var homedir = (process.platform === 'win32') ? process.env.USERPROFILE : process.env.HOME;
//echo (homedir)
//var BOOK_SAVE_PATH="C:\\Users\\yidwu\\Downloads\\_Un"
var BOOK_SAVE_PATH=path.join(homedir,"Downloads","_Un"); //cross-platform path
/* Regxp */
var DATE_REGXP=/(January|February|March|April|May|June|July|August|September|October|November|December).*/
var ISBN10_REGXP=/^\d{9}[\d|X]/
var ISBN13_REGXP=/^(978|979)(?:-|)\d{9}[\d|X]/
var EDTION_REGXP=/^\d{1}$/
var ASIN_REGXP=/^[A-Z0-9]{10}/

function requestByGoogleBook(changeNameJob,isbn){
    var reqBody = {
        method:'GET',
        uri: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn
    };
    request(reqBody,function(err,rep,body){
        if(rep.statusCode == 200){

            var jsObject = JSON.parse(body);
            echo("------------------------------------------------------------")
            echo(reqBody.uri)
            var newName = [];
            if (jsObject.items == undefined) {
                echo ('Error :'+isbn+", no result found!")
                return
            }
            var title=jsObject.items[0].volumeInfo.title.trim();
            var subtitle=jsObject.items[0].volumeInfo.subtitle;
            var date=jsObject.items[0].volumeInfo.publishedDate.trim();

            if (subtitle != undefined) title = title+" - "+subtitle.trim();
            newName.push(title);
            newName.push(date.substr(0,7));
            newName.push(isbn);
            newName = newName.join(", ");

            echo("Title    :",title);
            echo("Pub Date :",date);
            echo("New Name :",newName)

            if (date !== undefined) {
                changeNameJob.pubdate = new Date(Date.parse(date));
            }
            changeNameJob.changeName(newName);
        }else{
            echo('error :',rep.statusCode);
            echo(body);

        }
    });
}

//requestByIsbn(doBookName,'1617290572');

function requestByAmazon(changeNameJob,ASIN){
    var reqBody = {
        method:'GET',
        uri: 'http://www.amazon.com/dp/' + ASIN
    };
    request(reqBody,function(err,rep,body){
        if(rep.statusCode == 200){
            echo("------------------------------------------------------------")
            echo(reqBody.uri)
            var $ = cheerio.load(body);
            var newName = [];
            var title="";
            var type ="";
            if ($('#btAsinTitle').children().get(0)!==undefined){
                title = $('#btAsinTitle').children().get(0).prev.data.trim();
                type  = $('#btAsinTitle').children().text().trim();
            }else if($('#productTitle').text()!==undefined){
                title = $('#productTitle').text();
            }
            title = title.replace(/:/g," -");
            title = title.replace(/\//g,"&")

            var date
            var pubdate = $('#pubdate').val();

            if (pubdate === undefined) {
                $('div[class=buying]').find('span[style="font-weight: bold;"]').each(function() {
                    //echo("----------------")
                    var text = $(this).text().trim();
                    //echo(text);
                    if (DATE_REGXP.test(text)){
                        echo("Pub Date :",text);
                        pubdate = Date.parse(text);
                    }else if (ISBN13_REGXP.test(text)){
                        echo("ISDN_13  :",text);
                    }
                    else if(ISBN10_REGXP.test(text)){
                        echo("ISDN_10  :",text);
                    }else if(EDTION_REGXP.test(text)){
                        echo("Edtion   :",text);
                    }

                });
            }
            if (pubdate !== undefined) {
                date = new Date(pubdate);
                //Notice, getMonth return 0 to 11
                var month= date.getMonth()+1
                date = (month<10) ? date.getFullYear()+"-0"+month
                                            : date.getFullYear()+"-"+month;
            }

            newName.push(title);
            newName.push(date);
            newName.push(ASIN);
            newName = newName.join(", ")

            echo("Type     :",type)
            echo("Title    :",title);
            echo("New Name :",newName)

            if (pubdate !== undefined) {
                changeNameJob.pubdate = pubdate
            }
            changeNameJob.changeName(newName);
        }else{
            echo("------------------------------------------------------------")
            echo("Fail to query",reqBody.uri);
            echo("Error :",rep.statusCode);
            echo("Try to use googlebook API");
            requestByGoogleBook(changeNameJob,ASIN);
        }
    });
}

function ChangeNameJob(parentDir,orginalFileName,fileExt){
    this.parentDir=parentDir;
    this.fileName=orginalFileName;
    this.fileExt=fileExt;
}
ChangeNameJob.prototype.changeName = function (newName){
    //check existed
    if (fs.existsSync(path.join(this.parentDir,newName+this.fileExt))) {
        newName = newName+"_"+Date.now();;
        echo("WARNING:","File exists!","->",newName+this.fileExt);

    }
    if(this.pubdate !== undefined){
        echo("Change file date to","->",new Date(this.pubdate).toDateString());
        fs.utimesSync(path.join(this.parentDir,this.fileName), this.pubdate/1000, this.pubdate/1000);
    }
    if(this.fileExt === ".zip"){ // code
        newName = newName+"[Source_Code]"
    }
    echo("Change file name ",this.fileName,"->",newName+this.fileExt);
    fs.rename(
        path.join(this.parentDir,this.fileName),
        path.join(this.parentDir,newName+this.fileExt),
        function (err) {
            if (err) echo('rename callback ', err);
        });

}

function parseISBN(name){
    //echo("parseISBN",name)
    var isbn
    if (ISBN13_REGXP.test(name)) {
        isbn=ISBN13_REGXP.exec(name)[0];
    }
    else if (ISBN10_REGXP.test(name)){
        isbn = ISBN10_REGXP.exec(name)[0];
    }
    else if (ASIN_REGXP.test(name)) {
        isbn=ASIN_REGXP.exec(name)[0];
    }
    return isbn;
}

function renameBook(parentDir,file){
    //echo("enter",parentDir,file);
    if (!fs.statSync(path.join(parentDir,file)).isDirectory()){
        var fileName=file;
        var fileExt=path.extname(fileName);
        var fileBaseName=path.basename(fileName,fileExt);

        var isbn = parseISBN(fileBaseName);
        if (isbn === undefined){
            isbn = parseISBN(path.basename(parentDir));
        }
        if (isbn === undefined){
            echo("WARNING :","Can't parse a isdn or asin from given name : [",fileName,"]");
            return;
        }
        if (fileExt===".rar"){
            //uncompressRarFile(fileName,isbn);

        }else{
            echo("ChangeNameJob [","dir:'",parentDir,"'; file:'",fileName,"'; file-ext:'",fileExt,"'']");
            var job = new ChangeNameJob(parentDir,fileName,fileExt);
            requestByAmazon(job,isbn);
        }

    }else{
        //echo("folder",file);
        var isbn = parseISBN(file);
        if (isbn === undefined){
            echo("WARNING :","Can't parse a isdn or asin from given name : [",fileName,"]");
            return;
        }
        //echo("isbn",isbn)
        fs.readdir(path.join(parentDir,isbn),
                function(err,unzipfiles){
                    unzipfiles.forEach(function(unzipfile){
                        //echo("In isbn folder file",unzipfile);
                        renameBook(path.join(parentDir,isbn),unzipfile)})});
    }
}

function uncompressRarFile(rarfile,isbn){
    if (fs.statSync(path.join(BOOK_SAVE_PATH,rarfile)).isDirectory()) return;
    var fileExt=path.extname(rarfile);
    if (fileExt === ".rar") {
        var outputDir=path.join(BOOK_SAVE_PATH,isbn);
        var rarfilePath = path.join(BOOK_SAVE_PATH,rarfile);
        var _7zCmd = "7z x -o"+outputDir+" "+rarfilePath+" -y";
        echo(_7zCmd);
        child_process.exec(_7zCmd, function (error, stdout, stderr) {
                if (stdout !== null && stdout !== "") {
                    echo('stdout: ',stdout);
                }
                if (error !== null) {
                    echo("Execute:",_7zCmd,"Failed!");
                    console.error( error.stack );
                }else{
                    echo("Execute:",_7zCmd,"Done!");
                    echo("Removed the rar file.")
                    fs.unlinkSync(rarfilePath);
                    waitFor.count();
                }
        });
    }
}

function WaitForFinished(number){
    this.counter = number;
}

WaitForFinished.prototype.count = function () {
    if (this.counter !==0) this.counter --;
    if (this.counter == 0) {
        echo("------------------------------------------------------------------Starting renaming...")
        fs.readdir(BOOK_SAVE_PATH,function(err,files){files.forEach(function(file){renameBook(BOOK_SAVE_PATH,file)})})
    }
}

function doRealRename() {

    var numberOfRarFiles=0;
    fs.readdirSync(BOOK_SAVE_PATH).forEach(function(file){
        if (path.extname(file)===".rar"){
            var isbn = parseISBN(file);
            if (isbn !== undefined){
                numberOfRarFiles++;
            }
        }
    });
    //echo(numberOfRarFiles)

    var waitFor = new WaitForFinished(numberOfRarFiles);
    if (numberOfRarFiles === 0) waitFor.count();

    fs.readdir(BOOK_SAVE_PATH,function(err,files){files.forEach(function(file){
        if (path.extname(file)===".rar"){
            var isbn = parseISBN(file);
            if (isbn !== undefined){
                uncompressRarFile(file,isbn);
            }
        }
    })});

}

function main() {
    doRealRename();
}

main();<|endoftext|>


<commit_before>import restler from 'restler';
const API_SERVICE_RETRY_COUNT = process.env.API_SERVICE_RETRY_COUNT || 20;
const API_SERVICE_RETRY_TIMEOUT = process.env.API_SERVICE_RETRY_TIMEOUT || 5000;
export default class CheckAndGetApi {
    constructor(url, callback) {
        console.log('Connecting to ', url);
        this.retry = 0;
        restler.get(url, {
            timeout: API_SERVICE_RETRY_TIMEOUT
        }).on('success', function (data) {
            callback(undefined, data);
        }).on('error', function (reason) {
            if (retry === RETRY_COUNT) {
                callback(reason);
            }
            retry++;
            this.retry(API_SERVICE_RETRY_TIMEOUT);
        }).on('fail', function (reason) {
            if (retry === RETRY_COUNT) {
                callback(reason);
            }
            retry++;
            this.retry(API_SERVICE_RETRY_TIMEOUT);
        }).on('timeout', function (reason) {
            if (retry === RETRY_COUNT) {
                callback(reason);
            }
            retry++;
            this.retry(API_SERVICE_RETRY_TIMEOUT);
        });
    }
}<commit_msg>updates<commit_after>import restler from 'restler';
const API_SERVICE_RETRY_COUNT = process.env.API_SERVICE_RETRY_COUNT || 20;
const API_SERVICE_RETRY_TIMEOUT = process.env.API_SERVICE_RETRY_TIMEOUT || 5000;
export default class CheckAndGetApi {
    constructor(url, callback) {
        console.log('Connecting to ', url);
        let retry = 0;
        restler.get(url, {
            timeout: API_SERVICE_RETRY_TIMEOUT
        }).on('success', function (data) {
            callback(undefined, data);
        }).on('error', function (reason) {
            if (retry === API_SERVICE_RETRY_COUNT) {
                callback(reason);
            }
            retry++;
            this.retry(API_SERVICE_RETRY_TIMEOUT);
        }).on('fail', function (reason) {
            if (retry === API_SERVICE_RETRY_COUNT) {
                callback(reason);
            }
            retry++;
            this.retry(API_SERVICE_RETRY_TIMEOUT);
        }).on('timeout', function (reason) {
            if (retry === API_SERVICE_RETRY_COUNT) {
                callback(reason);
            }
            retry++;
            this.retry(API_SERVICE_RETRY_TIMEOUT);
        });
    }
}<|endoftext|>