<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('../../beaker.po.js');
var path = require('path');
var beakerPO;

describe('Groovy Plotting', function () {

    beforeAll(function(done){
        beakerPO = new BeakerPageObject();
        browser.get(beakerPO.baseURL + "beaker/#/open?uri=file:config%2Ftutorials%2FlevelsOfDetail.bkr&readOnly=true").then(done);
        beakerPO.waitUntilLoadingCellOutput();
    });

    afterAll(function(done){
        beakerPO.createScreenshot('levelsOfDetailTutorial');
        done();
    });

    it('Levels of Detail', function () {
        var idCell = "coden9MEmJ";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.getBkCellByIdCell(idCell).element(by.css('div[ng-click="toggleCellInput()"]')).click();
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Text');

        idCell = "codeDyDWm8";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Plot');
        expect(beakerPO.getPlotMaingByIdCell(idCell).isPresent()).toBe(true);

        expect(beakerPO.getCodeCellOutputByIdCell(idCell).element(by.id("plotTitle")).getText()).toBe("Drunken Sailor Walks");
        beakerPO.checkSaveAsSvgPngByIdCell(idCell, "Drunken Sailor Walks");
    });

});<commit_msg>text cells should have a show/hide toggle #4265. test fix<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('../../beaker.po.js');
var path = require('path');
var beakerPO;

describe('Groovy Plotting', function () {

    beforeAll(function(done){
        beakerPO = new BeakerPageObject();
        browser.get(beakerPO.baseURL + "beaker/#/open?uri=file:config%2Ftutorials%2FlevelsOfDetail.bkr&readOnly=true").then(done);
        beakerPO.waitUntilLoadingCellOutput();
    });

    afterAll(function(done){
        beakerPO.createScreenshot('levelsOfDetailTutorial');
        done();
    });

    it('Levels of Detail', function () {
        var idCell = "coden9MEmJ";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.getBkCellByIdCell(idCell).element(by.css('div[ng-click="collapseCellMenu[cellmodel.type].click()"]')).click();
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Text');

        idCell = "codeDyDWm8";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Plot');
        expect(beakerPO.getPlotMaingByIdCell(idCell).isPresent()).toBe(true);

        expect(beakerPO.getCodeCellOutputByIdCell(idCell).element(by.id("plotTitle")).getText()).toBe("Drunken Sailor Walks");
        beakerPO.checkSaveAsSvgPngByIdCell(idCell, "Drunken Sailor Walks");
    });

});<|endoftext|>


<commit_before>'use strict';

var tape = require('../../../lib/thaliTape');
if (!tape.coordinated) {
  return;
}

var assert = require('assert');
var Promise = require('lie');

var logger = require('thali/thaliLogger')('testThaliMobileNativeComplex');

var testUtils = require('../../../lib/testUtils');

var QuitSignal  = require('./QuitSignal');
var ServerRound = require('./ServerRound');
var ClientRound = require('./ClientRound');

var autostop = {
  serverQuitSignal: null,
  serverRound: null
};
var test = tape({
  setup: function (t) {
    t.end();
  },
  teardown: function (t) {
    if (autostop.serverRound) {
      assert(
        autostop.serverQuitSignal,
        '\'autostop.serverQuitSignal\' should exist'
      );
      autostop.serverQuitSignal.raise();
      autostop.serverRound.stop()
      .catch(function (error) {
        // Ignoring any error
        logger.error('teardown error %s', error);
      })
      .then(function () {
        t.end();
      });
    } else {
      t.end();
    }
  }
});

var TEST_TIMEOUT = 1 * 60 * 1000;
var CONNECT_TIMEOUT = 3 * 1000;
var CONNECT_RETRY_TIMEOUT = 3.5 * 1000;
var CONNECT_RETRIES = 10;

test('Simple test with single round', function (t) {
  var serverQuitSignal = new QuitSignal();
  var clientQuitSignal = new QuitSignal();

  testUtils.testTimeout(t, TEST_TIMEOUT, function () {
    // serverQuitSignal.raise();
    clientQuitSignal.raise();
  });

  var serverRound = new ServerRound(t, 0, serverQuitSignal, {
    connectTimeout: CONNECT_TIMEOUT
  });
  var clientRound = new ClientRound(t, 0, clientQuitSignal, {
    connectRetries: CONNECT_RETRIES,
    connectRetryTimeout: CONNECT_RETRY_TIMEOUT,
    connectTimeout: CONNECT_TIMEOUT
  });

  autostop.serverQuitSignal = serverQuitSignal;
  autostop.serverRound = serverRound;

  serverRound.once('finished', function () {
    // We should have server up and running.
    // serverRound.stop();
  });
  clientRound.once('finished', function () {
    clientRound.stop();
  });

  serverRound.start()
  .then(function () {
    return Promise.all([
      // serverRound.waitUntilStopped(),
      clientRound.waitUntilStopped()
    ]);
  })
  .catch(function (error) {
    t.fail('Got error: ' + error);
  })
  .then(function () {
    t.end();
  });
});

test('Complex test with two rounds', function (t) {
  var serverQuitSignal = new QuitSignal();
  var clientQuitSignal = new QuitSignal();

  testUtils.testTimeout(t, TEST_TIMEOUT, function () {
    // serverQuitSignal.raise();
    clientQuitSignal.raise();
  });

  var serverRound = new ServerRound(t, 0, serverQuitSignal, {
    connectTimeout: CONNECT_TIMEOUT
  });
  var clientRound = new ClientRound(t, 0, clientQuitSignal, {
    connectRetries: CONNECT_RETRIES,
    connectRetryTimeout: CONNECT_RETRY_TIMEOUT,
    connectTimeout: CONNECT_TIMEOUT
  });

  autostop.serverQuitSignal = serverQuitSignal;
  autostop.serverRound = serverRound;

  serverRound.on('finished', function () {
    // We should have server up and running.
    // serverRound.stop();
  });
  clientRound.on('finished', function () {
    clientRound.stop();
  });

  serverRound.start()
  .then(function () {
    return Promise.all([
      // serverRound.waitUntilStopped(),
      clientRound.waitUntilStopped()
    ]);
  })
  .then(function () {
    serverRound.setRoundNumber(1);
    clientRound.setRoundNumber(1);
    clientRound.bind();
    return serverRound.start();
  })
  .then(function () {
    return Promise.all([
      // serverRound.waitUntilStopped(),
      clientRound.waitUntilStopped()
    ]);
  })
  .catch(function (error) {
    t.fail('Got error: ' + error);
  })
  .then(function () {
    t.end();
  });
});
<commit_msg>cosmetics<commit_after>'use strict';

var tape = require('../../../lib/thaliTape');
if (!tape.coordinated) {
  return;
}

var assert = require('assert');
var Promise = require('lie');

var logger = require('thali/thaliLogger')('testThaliMobileNativeComplex');

var testUtils = require('../../../lib/testUtils');

var QuitSignal  = require('./QuitSignal');
var ServerRound = require('./ServerRound');
var ClientRound = require('./ClientRound');

var autostop = {};
var test = tape({
  setup: function (t) {
    autostop = {
      serverQuitSignal: null,
      serverRound: null
    };
    t.end();
  },
  teardown: function (t) {
    if (autostop.serverRound) {
      assert(
        autostop.serverQuitSignal,
        '\'autostop.serverQuitSignal\' should exist'
      );
      autostop.serverQuitSignal.raise();
      autostop.serverRound.stop()
      .catch(function (error) {
        // Ignoring any error
        logger.error('teardown error %s', error);
      })
      .then(function () {
        t.end();
      });
    } else {
      t.end();
    }
  }
});

var TEST_TIMEOUT = 1 * 60 * 1000;
var CONNECT_TIMEOUT = 3 * 1000;
var CONNECT_RETRY_TIMEOUT = 3.5 * 1000;
var CONNECT_RETRIES = 10;

test('Simple test with single round', function (t) {
  var serverQuitSignal = new QuitSignal();
  var clientQuitSignal = new QuitSignal();

  testUtils.testTimeout(t, TEST_TIMEOUT, function () {
    // serverQuitSignal.raise();
    clientQuitSignal.raise();
  });

  var serverRound = new ServerRound(t, 0, serverQuitSignal, {
    connectTimeout: CONNECT_TIMEOUT
  });
  var clientRound = new ClientRound(t, 0, clientQuitSignal, {
    connectRetries: CONNECT_RETRIES,
    connectRetryTimeout: CONNECT_RETRY_TIMEOUT,
    connectTimeout: CONNECT_TIMEOUT
  });

  autostop.serverQuitSignal = serverQuitSignal;
  autostop.serverRound = serverRound;

  serverRound.once('finished', function () {
    // We should have server up and running.
    // serverRound.stop();
  });
  clientRound.once('finished', function () {
    clientRound.stop();
  });

  serverRound.start()
  .then(function () {
    return Promise.all([
      // serverRound.waitUntilStopped(),
      clientRound.waitUntilStopped()
    ]);
  })
  .catch(function (error) {
    t.fail('Got error: ' + error);
  })
  .then(function () {
    t.end();
  });
});

test('Complex test with two rounds', function (t) {
  var serverQuitSignal = new QuitSignal();
  var clientQuitSignal = new QuitSignal();

  testUtils.testTimeout(t, TEST_TIMEOUT, function () {
    // serverQuitSignal.raise();
    clientQuitSignal.raise();
  });

  var serverRound = new ServerRound(t, 0, serverQuitSignal, {
    connectTimeout: CONNECT_TIMEOUT
  });
  var clientRound = new ClientRound(t, 0, clientQuitSignal, {
    connectRetries: CONNECT_RETRIES,
    connectRetryTimeout: CONNECT_RETRY_TIMEOUT,
    connectTimeout: CONNECT_TIMEOUT
  });

  autostop.serverQuitSignal = serverQuitSignal;
  autostop.serverRound = serverRound;

  serverRound.on('finished', function () {
    // We should have server up and running.
    // serverRound.stop();
  });
  clientRound.on('finished', function () {
    clientRound.stop();
  });

  serverRound.start()
  .then(function () {
    return Promise.all([
      // serverRound.waitUntilStopped(),
      clientRound.waitUntilStopped()
    ]);
  })
  .then(function () {
    serverRound.setRoundNumber(1);
    clientRound.setRoundNumber(1);
    clientRound.bind();
    return serverRound.start();
  })
  .then(function () {
    return Promise.all([
      // serverRound.waitUntilStopped(),
      clientRound.waitUntilStopped()
    ]);
  })
  .catch(function (error) {
    t.fail('Got error: ' + error);
  })
  .then(function () {
    t.end();
  });
});
<|endoftext|>


<commit_before>/**
 * @overview ccm component for table generating
 * @see https://github.com/mozilla/pdf.js/
 * @author Tea Kless <tea.kless@web.de>, 2018
 * @license The MIT License (MIT)
 */

{
  var component = {

    /**
     * unique component name
     * @type {string}
     */
    name: 'table',

    /**
     * recommended used framework version
     * @type {string}
     */
    ccm: 'https://akless.github.io/ccm/ccm.js',

    /**
     * default instance configuration
     * @type {object}
     */
    config: {
      html: {
        "table": {
          "id": "container",
          "inner": {
            "class": "table-responsive",
            "inner": {
              "tag": "table",
              "class": "table table-striped table-responsive",
              "inner":[
                { "tag": "thead" },
                { "tag": "tbody" }
              ]
            }
          }
        },

        "table_row": { "tag": "tr" },

        "table_col": { "tag": "td" },

        "table_head": { "tag": "th" },

        "input": {
          "tag": "input",
          "type": "text"
        },

        "textarea": {
          "tag": "textarea"
        },

        "add": {
          "tag": "button",
          "class": "btn btn-default",
          "typ": "button",
          "onclick": "%add%",
          "inner": [
            {
              "tag": "span",
              "class": "glyphicon glyphicon-plus"
            },
            " Row"
          ]
        },

        "submit": {
          "tag": "button",
          "class": "btn btn-default pull-right",
          "typ": "button",
          "inner": "Submit",
          "onclick": "%submit%"
        }
      },
      //add_row: true,
      table_row: 0,
      //table_col: 3,
      //table_head: [ "header-1", "header-2", "header-3" ],
      //col_settings: [
      //  { "type": "number", "placeholder": "Tel: 049..." },
      //  { "disabled": "true", "inner": "max.musterman@mail.com" },
      //  { "type": "date", "foo": "bar" }
      //],
      //data: [ "ccm.get", "resources/configs.js", "demo" ],
      //submit: true,
      //onfinish
      css: [ "ccm.load", "https://tkless.github.io/ccm-components/libs/bootstrap/css/bootstrap.css",
        { "context": "head", "url": "https://tkless.github.io/ccm-components/libs/bootstrap/css/font-face.css" }
      ]
    },

    Instance: function () {
      /**
       * own reference for inner functions
       * @type {Instance}
       */
      const self = this;

      /**
       * privatized instance members
       * @type {object}
       */
      let my;

      /**
       * shortcut to help functions
       * @type {Object.<string,function>}
       */
      let $;

      this.init = callback => {

        callback();
      };

      this.ready = callback => {
        // set shortcut to help functions
        $ = self.ccm.helper;

        // privatize all possible instance members
        my = $.privatize( self );

        callback();

      };

      /**
       * starts the instance
       * @param {function} [callback] - called after all synchronous and asynchronous operations are complete
       */
      this.start = callback => {

        $.dataset( my.data, data => {

          if ( !generateTable() ) return $.setContent( self.element, "Nothig to display" );

          else {
            $.setContent( self.element, generateTable() );

            if ( my.submit ) {
              const submit_button = $.html ( my.html.submit, {
                submit: function () { $.onFinish( self ); }
              } );
              self.element.querySelector( '#container' ).appendChild( submit_button );
            }

            if ( callback ) callback();
          }

          function generateTable() {
            const table = $.html ( my.html.table );
            let row;

            if ( my.table_row ) {
              row = my.data && ( my.data.values.length > my.table_row) ? my.data.values.length : my.table_row;

              for ( let i = 0 ; i < row; i++ ) {
                const table_row = $.html ( my.html.table_row );
                if ( my.table_col ) {
                  for ( let j = 0 ; j < my.table_col; j++ ) {
                    const table_col = $.html ( my.html.table_col );

                    if ( !my.col_settings ) {

                      if ( data ) $.setContent( table_col, i < data.values.length && data.values[ i ][ j ] ? data.values[ i ][ j ] : '' );

                    }
                    else {

                      const input = $.clone( my.html[ my.col_settings && my.col_settings[ j ] && my.col_settings[ j ].type === 'textarea' ? 'textarea' : 'input' ] );
                      input.name = ( i + 1 ) + '-' + ( j + 1 );

                      // consider column properties
                      if ( my.col_settings ) considerColSettings( j, input );

                      // set values of input fields
                      if ( data ) ( i < data.values.length ) && data.values[ i ][ j ] ? input.value = data.values[ i ][ j ] : input.value = '';

                      table_col.appendChild( $.html( input ) );

                    }

                    table_row.appendChild( table_col );

                  }
                }
                table.querySelector( 'tbody' ).appendChild( table_row );
              }

              if ( my.table_head ) {
                table.querySelector( 'thead' ).appendChild( getTableHead() );
              }
            }

            // add new row via button
            if ( my.add_row ) table.appendChild(  $.html( my.html.add, {
              add: function ( event ) {
                if ( event ) event.preventDefault();
                my.table_row = ++row;
                my.data = self.getValue();
                self.start();
              }
            } ) );
            return table;
          }

          function getTableHead() {
            const table_row = $.html(my.html.table_row);

            for ( let j = 0 ; j < my.table_col; j++ ) {
              const table_head = $.html( my.html.table_head );
              $.setContent( table_head, my.table_head[ j ] );
              table_row.appendChild( table_head );
            }

            return table_row;
          }

          function considerColSettings( col, input ) {
            // set input tag property for each input => each input tag of one column has same properties
            for ( const key in my.col_settings[ col ] ) {
              switch ( key ) {
                case 'type':
                  if ( my.col_settings[ col ][ key ] !== 'textarea' )
                    input.type = my.col_settings[ col ][ key ];
                  break;
                case 'placeholder':
                  input.placeholder = my.col_settings[ col ][ key ];
                  break;
                default:
                  input[ key ] =  my.col_settings[ col ][ key ];
                  break;
              }

            }
          }

        } );

      };

      this.getValue = () => {

        return prepareFormData();

        // reads the table values and transform it to result data
        function prepareFormData() {

          let form_data = $.formData( self.element.querySelector( 'table' ) );

          const result = [];

          for( const key in form_data ) {
            const coord = key.split( '-' );
            const row = coord[ 0 ] - 1;
            const col = coord[ 1 ] - 1;
            if ( !result[ row ] ) result[ row ] = [];
            result[ row ][ col ] = form_data[ key ];
          }

          return { values: result };
        }
      };

    }

  };

  function p(){window.ccm[v].component(component)}const f="ccm."+component.name+(component.version?"-"+component.version.join("."):"")+".js";if(window.ccm&&null===window.ccm.files[f])window.ccm.files[f]=component;else{const n=window.ccm&&window.ccm.components[component.name];n&&n.ccm&&(component.ccm=n.ccm),"string"==typeof component.ccm&&(component.ccm={url:component.ccm});var v=component.ccm.url.split("/").pop().split("-");if(v.length>1?(v=v[1].split("."),v.pop(),"min"===v[v.length-1]&&v.pop(),v=v.join(".")):v="latest",window.ccm&&window.ccm[v])p();else{const e=document.createElement("script");document.head.appendChild(e),component.ccm.integrity&&e.setAttribute("integrity",component.ccm.integrity),component.ccm.crossorigin&&e.setAttribute("crossorigin",component.ccm.crossorigin),e.onload=function(){p(),document.head.removeChild(e)},e.src=component.ccm.url}}
}<commit_msg>minor change<commit_after>/**
 * @overview ccm component for table generating
 * @see https://github.com/mozilla/pdf.js/
 * @author Tea Kless <tea.kless@web.de>, 2018
 * @license The MIT License (MIT)
 */

{
  var component = {

    /**
     * unique component name
     * @type {string}
     */
    name: 'table',

    /**
     * recommended used framework version
     * @type {string}
     */
    ccm: 'https://akless.github.io/ccm/ccm.js',

    /**
     * default instance configuration
     * @type {object}
     */
    config: {
      html: {
        "table": {
          "id": "container",
          "inner": {
            "class": "table-responsive",
            "inner": {
              "tag": "table",
              "class": "table table-striped table-responsive",
              "inner":[
                { "tag": "thead" },
                { "tag": "tbody" }
              ]
            }
          }
        },

        "table_row": { "tag": "tr" },

        "table_col": { "tag": "td" },

        "table_head": { "tag": "th" },

        "input": {
          "tag": "input",
          "type": "text"
        },

        "textarea": {
          "tag": "textarea"
        },

        "add": {
          "tag": "button",
          "class": "btn btn-default",
          "typ": "button",
          "onclick": "%add%",
          "inner": [
            {
              "tag": "span",
              "class": "glyphicon glyphicon-plus"
            },
            " Row"
          ]
        },

        "submit": {
          "tag": "button",
          "class": "btn btn-default pull-right",
          "typ": "button",
          "inner": "Submit",
          "onclick": "%submit%"
        }
      },
      //add_row: true,
      table_row: 0,
      //table_col: 3,
      //table_head: [ "header-1", "header-2", "header-3" ],
      //col_settings: [
      //  { "type": "number", "placeholder": "Tel: 049..." },
      //  { "disabled": "true", "inner": "max.musterman@mail.com" },
      //  { "type": "date", "foo": "bar" }
      //],
      //data: [ "ccm.get", "resources/configs.js", "demo" ],
      //submit: true,
      //onfinish
      css: [ "ccm.load", "https://tkless.github.io/ccm-components/libs/bootstrap/css/bootstrap.css",
        { "context": "head", "url": "https://tkless.github.io/ccm-components/libs/bootstrap/css/font-face.css" }
      ]
    },

    Instance: function () {
      /**
       * own reference for inner functions
       * @type {Instance}
       */
      const self = this;

      /**
       * privatized instance members
       * @type {object}
       */
      let my;

      /**
       * shortcut to help functions
       * @type {Object.<string,function>}
       */
      let $;

      this.init = callback => {

        callback();
      };

      this.ready = callback => {
        // set shortcut to help functions
        $ = self.ccm.helper;

        // privatize all possible instance members
        my = $.privatize( self );

        callback();

      };

      /**
       * starts the instance
       * @param {function} [callback] - called after all synchronous and asynchronous operations are complete
       */
      this.start = callback => {

        $.dataset( my.data, data => {

          if ( !generateTable() ) return $.setContent( self.element, "Nothig to display" );

          else {
            $.setContent( self.element, generateTable() );

            if ( my.submit ) {
              const submit_button = $.html ( my.html.submit, {
                submit: function () { $.onFinish( self ); }
              } );
              self.element.querySelector( '#container' ).appendChild( submit_button );
            }

            if ( callback ) callback();
          }

          function generateTable() {
            const table = $.html ( my.html.table );
            let row;

            if ( my.table_row ) {
              row = my.data.values && ( my.data.values.length > my.table_row) ? my.data.values.length : my.table_row;

              for ( let i = 0 ; i < row; i++ ) {
                const table_row = $.html ( my.html.table_row );
                if ( my.table_col ) {
                  for ( let j = 0 ; j < my.table_col; j++ ) {
                    const table_col = $.html ( my.html.table_col );

                    if ( !my.col_settings ) {

                      if ( data ) $.setContent( table_col, i < data.values.length && data.values[ i ][ j ] ? data.values[ i ][ j ] : '' );

                    }
                    else {

                      const input = $.clone( my.html[ my.col_settings && my.col_settings[ j ] && my.col_settings[ j ].type === 'textarea' ? 'textarea' : 'input' ] );
                      input.name = ( i + 1 ) + '-' + ( j + 1 );

                      // consider column properties
                      if ( my.col_settings ) considerColSettings( j, input );

                      // set values of input fields
                      if ( data ) ( i < data.values.length ) && data.values[ i ][ j ] ? input.value = data.values[ i ][ j ] : input.value = '';

                      table_col.appendChild( $.html( input ) );

                    }

                    table_row.appendChild( table_col );

                  }
                }
                table.querySelector( 'tbody' ).appendChild( table_row );
              }

              if ( my.table_head ) {
                table.querySelector( 'thead' ).appendChild( getTableHead() );
              }
            }

            // add new row via button
            if ( my.add_row ) table.appendChild(  $.html( my.html.add, {
              add: function ( event ) {
                if ( event ) event.preventDefault();
                my.table_row = ++row;
                my.data = self.getValue();
                self.start();
              }
            } ) );
            return table;
          }

          function getTableHead() {
            const table_row = $.html(my.html.table_row);

            for ( let j = 0 ; j < my.table_col; j++ ) {
              const table_head = $.html( my.html.table_head );
              $.setContent( table_head, my.table_head[ j ] );
              table_row.appendChild( table_head );
            }

            return table_row;
          }

          function considerColSettings( col, input ) {
            // set input tag property for each input => each input tag of one column has same properties
            for ( const key in my.col_settings[ col ] ) {
              switch ( key ) {
                case 'type':
                  if ( my.col_settings[ col ][ key ] !== 'textarea' )
                    input.type = my.col_settings[ col ][ key ];
                  break;
                case 'placeholder':
                  input.placeholder = my.col_settings[ col ][ key ];
                  break;
                default:
                  input[ key ] =  my.col_settings[ col ][ key ];
                  break;
              }

            }
          }

        } );

      };

      this.getValue = () => {

        return prepareFormData();

        // reads the table values and transform it to result data
        function prepareFormData() {

          let form_data = $.formData( self.element.querySelector( 'table' ) );

          const result = [];

          for( const key in form_data ) {
            const coord = key.split( '-' );
            const row = coord[ 0 ] - 1;
            const col = coord[ 1 ] - 1;
            if ( !result[ row ] ) result[ row ] = [];
            result[ row ][ col ] = form_data[ key ];
          }

          return { values: result };
        }
      };

    }

  };

  function p(){window.ccm[v].component(component)}const f="ccm."+component.name+(component.version?"-"+component.version.join("."):"")+".js";if(window.ccm&&null===window.ccm.files[f])window.ccm.files[f]=component;else{const n=window.ccm&&window.ccm.components[component.name];n&&n.ccm&&(component.ccm=n.ccm),"string"==typeof component.ccm&&(component.ccm={url:component.ccm});var v=component.ccm.url.split("/").pop().split("-");if(v.length>1?(v=v[1].split("."),v.pop(),"min"===v[v.length-1]&&v.pop(),v=v.join(".")):v="latest",window.ccm&&window.ccm[v])p();else{const e=document.createElement("script");document.head.appendChild(e),component.ccm.integrity&&e.setAttribute("integrity",component.ccm.integrity),component.ccm.crossorigin&&e.setAttribute("crossorigin",component.ccm.crossorigin),e.onload=function(){p(),document.head.removeChild(e)},e.src=component.ccm.url}}
}<|endoftext|>


<commit_before>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['vegalite'], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(
      require('vegalite')
    );
  } else {
    // Browser globals (root is window)
    root.visrank = factory(root.vl);
  }
}(this, function (vl) {
  var vrank = {};

  //TODO lower score if we use G as O?
  var ENCODING_SCORE = {
    Q: {
      x: 1,
      y: 1,
      size: 0.6, //FIXME SIZE for Bar is horrible!
      color: 0.4,
      alpha: 0.4
    },
    O: {
      x: 0.99, // harder to read axis
      y: 1,
      row: 0.7,
      col: 0.7,
      color: 0.8,
      shape: 0.6
    }
  };

  // bad score not specified in the table above
  var BAD_ENCODING_SCORE = 0.01,
    UNUSED_POSITION = 0.5;

  var MARK_SCORE = {
    line: 0.99,
    area: 0.98,
    bar: 0.97,
    point: 0.96,
    circle: 0.95,
    square: 0.95,
    text: 0.8
  };

  vrank.encodingScore = function(encoding){
    var features = {},
      encTypes = vl.keys(encoding.enc);
    encTypes.forEach(function(encType){
      var field = encoding.enc[encType];
      features[field.name] = {
        value: field.type+":"+encType,
        score: ENCODING_SCORE[field.type][encType] || BAD_ENCODING_SCORE
      };
    });

    // penalize not using positional
    if(encTypes.length > 1){
      if((!encoding.enc.x || !encoding.enc.y) && !encoding.enc.geo) {
        features.unusedPosition = {score: UNUSED_POSITION};
      }
    }

    features.markType = {
      value: encoding.marktype,
      score: MARK_SCORE[encoding.marktype]
    }

    return {
      score: vl.keys(features).reduce(function(p, s){ return p * features[s].score}, 1),
      features: features
    };
  };
  };

  return vrank;
}));<commit_msg>fix bad commit<commit_after>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['vegalite'], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(
      require('vegalite')
    );
  } else {
    // Browser globals (root is window)
    root.visrank = factory(root.vl);
  }
}(this, function (vl) {
  var vrank = {};

  //TODO lower score if we use G as O?
  var ENCODING_SCORE = {
    Q: {
      x: 1,
      y: 1,
      size: 0.6, //FIXME SIZE for Bar is horrible!
      color: 0.4,
      alpha: 0.4
    },
    O: { // TODO need to take cardinality into account
      x: 0.99, // harder to read axis
      y: 1,
      row: 0.7,
      col: 0.7,
      color: 0.8,
      shape: 0.6
    }
  };

  // bad score not specified in the table above
  var BAD_ENCODING_SCORE = 0.01,
    UNUSED_POSITION = 0.5;

  var MARK_SCORE = {
    line: 0.99,
    area: 0.98,
    bar: 0.97,
    point: 0.96,
    circle: 0.95,
    square: 0.95,
    text: 0.8
  };

  vrank.encodingScore = function(encoding){
    var features = {},
      encTypes = vl.keys(encoding.enc);
    encTypes.forEach(function(encType){
      var field = encoding.enc[encType];
      features[field.name] = {
        value: field.type+":"+encType,
        score: ENCODING_SCORE[field.type][encType] || BAD_ENCODING_SCORE
      };
    });

    // penalize not using positional
    if(encTypes.length > 1){
      if((!encoding.enc.x || !encoding.enc.y) && !encoding.enc.geo) {
        features.unusedPosition = {score: UNUSED_POSITION};
      }
    }

    features.markType = {
      value: encoding.marktype,
      score: MARK_SCORE[encoding.marktype]
    }

    return {
      score: vl.keys(features).reduce(function(p, s){ return p * features[s].score}, 1),
      features: features
    };
  };

  return vrank;
}));<|endoftext|>


<commit_before>(function e(t, n, r) {
  function s(o, u) {
    if (!n[o]) {
      if (!t[o]) {
        var a = typeof require == "function" && require;
        if (!u && a)
          return a(o, !0);
        if (i)
          return i(o, !0);
        var f = new Error("Cannot find module '" + o + "'");
        throw f.code = "MODULE_NOT_FOUND", f
      }
      var l = n[o] = {
        exports : {}
      };
      t[o][0].call(l.exports, function(e) {
        var n = t[o][1][e];
        return s(n ? n : e)
      }, l, l.exports, e, t, n, r)
    }
    return n[o].exports
  }
  var i = typeof require == "function" && require;
  for (var o = 0; o < r.length; o++)
    s(r[o]);
  return s
})({
  1 : [ function(require, module, exports) {

    function corslite(rrshape, callback, cors) {
      var sent = false;

      if (typeof window.XMLHttpRequest === 'undefined') {
        return callback(Error('Browser not supported'));
      }

      if (typeof cors === 'undefined') {
        var m = url.match(/^\s*https?:\/\/[^\/]*/);
        cors = m && (m[0] !== location.protocol + '//' + location.domain + (location.port ? ':' + location.port : ''));
      }

      function isSuccessful(status) {
        return status >= 200 && status < 300 || status === 304;
      }

      function loaded() {
        if (
        // ajax POST request
        resp.status === undefined ||
        // modern browsers
        isSuccessful(resp.status)) {
          callback.call(resp, null, resp);
        } else
          callback.call(resp, resp, null);
      }

      // reset service url & access token if environment has changed
      (typeof this.elevServiceUrl != 'undefined' || this.elevServiceUrl != null) ? this.options.serviceUrl = this.elevServiceUrl : this.options.serviceUrl = this.elevationServer.dev;
      (typeof this.elevToken != "undefined" || this.elevToken != null) ? this._accessToken = this.elevToken : this._accessToken = this.elevAccessToken.dev;

      var params = JSON.stringify({
        encoded_polyline : rrshape,
        range : true
      });

      var resp = $.ajax({
        crossDomain : true,
        type : "POST",
        url : this.elevServiceUrl + 'height?api_key=' + this.elevToken,
        data : params,
        success : "success",
        dataType : 'json'
      });

      resp.done(function() {
        if (resp.readyState === 4) {
          if (resp.status >= 200 && resp.status < 400) {
            loaded();
            sent = true;
            console.log("Elevation POST Request :: " + this.elevServiceUrl + 'height?api_key=' + this.elevToken + " ,POST DATA :: " + params);
          } else {
            errback(new Error('Response returned with non-OK status'));
          }
        }
      });

      return resp;
    };

    if (typeof module !== 'undefined')
      module.exports = corslite;
  }, {} ],
  2 : [ function(require, module, exports) {
  }, {} ],
  3 : [ function(require, module, exports) {
    (function(global) {
      (function() {
        'use strict';

        var L = (typeof window !== "undefined" ? window.L : typeof global !== "undefined" ? global.L : null);
        var corslite = require('corslite');
        var polyline = require('polyline');

        L.Elevation = L.Elevation || {};

        L.Elevation = L.Class.extend({
          options : {
            serviceUrl : (typeof serviceUrl != "undefined" || serviceUrl != null) ? serviceUrl : elevationServer.dev,
            timeout : 30 * 1000
          },

          initialize : function(accessToken, rrshape, options) {
            L.Util.setOptions(this, options);
            this._accessToken = accessToken;
            this._rrshape = rrshape;
            this._graphdata = [];
            this._graphoptions = {
              axislabels : {
                show : true
              },
              threshold : {
                below : 0,
                color : "#c00000"
              },
              legend : {
                show : false
              },
              grid : {
                borderWidth : 1,
                minBorderMargin : 20,
                labelMargin : 10,
                backgroundColor : {
                  colors : [ "#fff", "#e4f4f4" ]
                },
                margin : {
                  top : 8,
                  bottom : 25,
                  left : 20
                }
              },
              xaxis : {
                min : 0,
                // axisLabel : 'Range',
                labelWidth : 30,
                axisLabelUseCanvas : true,
                axisLabelFontSizePixels : 14,
                axisLabelFontFamily : 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
                axisLabelPadding : 10
              },
              yaxis : {
                // axisLabel : 'Height',
                labelWidth : 30,
                axisLabelUseCanvas : true,
                axisLabelFontSizePixels : 14,
                axisLabelFontFamily : 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
                axisLabelPadding : 10
              },
              series : {
                stack : true,
                lines : {
                  show : true,
                  fill : true
                },
                points : {
                  radius : 0,
                  show : true,
                  fill : true,
                  fillColor : '#83ce16'
                },
              },
              legend : {
                labelBoxBorderColor : "none",
                position : "right"
              },
              lines : {
                fill : true,
                lineWidth : 3,
              }
            };
            // initilizing placeholder graph so that user knows there is graph
            $.plot($('#graph'), this._graphdata, this._graphoptions);
            var xaxisLabel = $("

").text("Range (m)").appendTo($('#graph'));
            var yaxisLabel = $("

").text("Height (m)").appendTo($('#graph'));
            yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20);
          },
          resetChart : function() {
            var plot = $.plot($('#graph'), this._graphdata, this._graphoptions);
            plot.destroy();
            $('#graph').empty();
          },

          profile : function(rrshape, callback, context, options) {
            var timedOut = false, options = options || {};

            var timer = setTimeout(function() {
              timedOut = true;
              callback.call(context || callback, {
                status : -1,
                message : 'request timed out.'
              });
            }, this.options.timeout);

            corslite(rrshape, L.bind(function(err, resp) {
              var elevresult;
              clearTimeout(timer);
              if (!timedOut) {
                if (!err) {
                  elevresult = JSON.parse(resp.responseText);
                  this._graphdata = [ {
                    "label" : "Elevation",
                    "data" : elevresult.range_height,
                    "points" : {
                      "symbol" : "circle",
                      "fillColor" : "#2E2EFE"
                    },
                    "color" : '#2E2EFE'
                  } ];
                  $.plot($('#graph'), this._graphdata, this._graphoptions);
                  var xaxisLabel = $("

").text("Range (m)").appendTo($('#graph'));
                  var yaxisLabel = $("

").text("Height (m)").appendTo($('#graph'));
                  yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20);
                }
              }
            }, this), true);

            return this;
          },

          getDataPoints : function(elevresult) {
            var dataPoints = [];
            for (var xy = 0; xy < elevresult.range_height.length; xy++) {
              dataPoints.push({
                x : elevresult.range_height[xy][0] != null ? elevresult.range_height[xy][0] : 0,
                y : elevresult.range_height[xy][1] != null ? elevresult.range_height[xy][1] : 0
              });
            }
            return dataPoints;
          },

          showTooltip : function(x, y, contents, z) {
            $('
' + contents + '
').css({
              position : 'absolute',
              display : 'none',
              'font-weight' : 'bold',
              border : '1px solid rgb(255, 221, 221)',
              padding : '2px',
              'background-color' : z,
              opacity : '0.8'
            }).appendTo("body").show();
          },

          bindEvents : function(plot) {
            $('#graph').on('plothover', function(event, pos, item) {
              if (item) {
                if ((previousPoint != item.dataIndex) || (previousLabel != item.series.label)) {
                  previousPoint = item.dataIndex;
                  previousLabel = item.series.label;

                  $("#flot-tooltip").remove();

                  var x = getDataPoints(item.dataPoints[0]), y = item.dataPoints[1];
                  z = item.series.color;

                  showTooltip(item.pageX, item.pageY, "" + item.series.label + "
 " + x + " = " + y + "mm", z);
                }
              } else {
                $("#flot-tooltip").remove();
                previousPoint = null;
              }
            });
          },

          _locationKey : function(location) {
            return location[0] + ',' + location[1];
          }
        });

        L.elevation = function(accessToken, shape, options) {
          return new L.Elevation(accessToken, shape, options);
        };

        module.exports = L.Elevation;
      })();

    }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  }, {
    "corslite" : 1,
    "polyline" : 2
  } ]
}, {}, [ 3 ]);<commit_msg>refactored<commit_after>(function e(t, n, r) {
  function s(o, u) {
    if (!n[o]) {
      if (!t[o]) {
        var a = typeof require == "function" && require;
        if (!u && a)
          return a(o, !0);
        if (i)
          return i(o, !0);
        var f = new Error("Cannot find module '" + o + "'");
        throw f.code = "MODULE_NOT_FOUND", f
      }
      var l = n[o] = {
        exports : {}
      };
      t[o][0].call(l.exports, function(e) {
        var n = t[o][1][e];
        return s(n ? n : e)
      }, l, l.exports, e, t, n, r)
    }
    return n[o].exports
  }
  var i = typeof require == "function" && require;
  for (var o = 0; o < r.length; o++)
    s(r[o]);
  return s
})({
  1 : [ function(require, module, exports) {

    function corslite(rrshape, callback, cors) {
      var sent = false;

      if (typeof window.XMLHttpRequest === 'undefined') {
        return callback(Error('Browser not supported'));
      }

      if (typeof cors === 'undefined') {
        var m = url.match(/^\s*https?:\/\/[^\/]*/);
        cors = m && (m[0] !== location.protocol + '//' + location.domain + (location.port ? ':' + location.port : ''));
      }

      function isSuccessful(status) {
        return status >= 200 && status < 300 || status === 304;
      }

      function loaded() {
        if (
        // ajax POST request
        resp.status === undefined ||
        // modern browsers
        isSuccessful(resp.status)) {
          callback.call(resp, null, resp);
        } else
          callback.call(resp, resp, null);
      }

      // reset service url & access token if environment has changed
      (typeof this.elevServiceUrl != 'undefined' || this.elevServiceUrl != null) ? this.options.serviceUrl = this.elevServiceUrl : this.options.serviceUrl = this.elevationServer.dev;
      (typeof this.elevToken != "undefined" || this.elevToken != null) ? this._accessToken = this.elevToken : this._accessToken = this.elevAccessToken.dev;

      var params = JSON.stringify({
        encoded_polyline : rrshape,
        range : true
      });

      var resp = $.ajax({
        crossDomain : true,
        type : "POST",
        url : this.elevServiceUrl + 'height?api_key=' + this.elevToken,
        data : params,
        success : "success",
        dataType : 'json'
      });

      resp.done(function() {
        if (resp.readyState === 4) {
          if (resp.status >= 200 && resp.status < 400) {
            loaded();
            sent = true;
          } else {
            errback(new Error('Response returned with non-OK status'));
          }
        }
      });
      console.log("Elevation POST Request :: " + this.elevServiceUrl + 'height?api_key=' + this.elevToken + " ,POST DATA :: " + params);
      return resp;
    };

    if (typeof module !== 'undefined')
      module.exports = corslite;
  }, {} ],
  2 : [ function(require, module, exports) {
  }, {} ],
  3 : [ function(require, module, exports) {
    (function(global) {
      (function() {
        'use strict';

        var L = (typeof window !== "undefined" ? window.L : typeof global !== "undefined" ? global.L : null);
        var corslite = require('corslite');
        var polyline = require('polyline');

        L.Elevation = L.Elevation || {};

        L.Elevation = L.Class.extend({
          options : {
            serviceUrl : (typeof serviceUrl != "undefined" || serviceUrl != null) ? serviceUrl : elevationServer.dev,
            timeout : 30 * 1000
          },

          initialize : function(accessToken, rrshape, options) {
            L.Util.setOptions(this, options);
            this._accessToken = accessToken;
            this._rrshape = rrshape;
            this._graphdata = [];
            this._graphoptions = {
              axislabels : {
                show : true
              },
              threshold : {
                below : 0,
                color : "#c00000"
              },
              legend : {
                show : false
              },
              grid : {
                borderWidth : 1,
                minBorderMargin : 20,
                labelMargin : 10,
                backgroundColor : {
                  colors : [ "#fff", "#e4f4f4" ]
                },
                margin : {
                  top : 8,
                  bottom : 25,
                  left : 20
                }
              },
              xaxis : {
                min : 0,
                // axisLabel : 'Range',
                labelWidth : 30,
                axisLabelUseCanvas : true,
                axisLabelFontSizePixels : 14,
                axisLabelFontFamily : 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
                axisLabelPadding : 10
              },
              yaxis : {
                // axisLabel : 'Height',
                labelWidth : 30,
                axisLabelUseCanvas : true,
                axisLabelFontSizePixels : 14,
                axisLabelFontFamily : 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
                axisLabelPadding : 10
              },
              series : {
                stack : true,
                lines : {
                  show : true,
                  fill : true
                },
                points : {
                  radius : 0,
                  show : true,
                  fill : true,
                  fillColor : '#83ce16'
                },
              },
              legend : {
                labelBoxBorderColor : "none",
                position : "right"
              },
              lines : {
                fill : true,
                lineWidth : 3,
              }
            };
            // initilizing placeholder graph so that user knows there is graph
            $.plot($('#graph'), this._graphdata, this._graphoptions);
            var xaxisLabel = $("

").text("Range (m)").appendTo($('#graph'));
            var yaxisLabel = $("

").text("Height (m)").appendTo($('#graph'));
            yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20);
          },
          resetChart : function() {
            var plot = $.plot($('#graph'), this._graphdata, this._graphoptions);
            plot.destroy();
            $('#graph').empty();
          },

          profile : function(rrshape, callback, context, options) {
            var timedOut = false, options = options || {};

            var timer = setTimeout(function() {
              timedOut = true;
              callback.call(context || callback, {
                status : -1,
                message : 'request timed out.'
              });
            }, this.options.timeout);

            corslite(rrshape, L.bind(function(err, resp) {
              var elevresult;
              clearTimeout(timer);
              if (!timedOut) {
                if (!err) {
                  elevresult = JSON.parse(resp.responseText);
                  this._graphdata = [ {
                    "label" : "Elevation",
                    "data" : elevresult.range_height,
                    "points" : {
                      "symbol" : "circle",
                      "fillColor" : "#2E2EFE"
                    },
                    "color" : '#2E2EFE'
                  } ];
                  $.plot($('#graph'), this._graphdata, this._graphoptions);
                  var xaxisLabel = $("

").text("Range (m)").appendTo($('#graph'));
                  var yaxisLabel = $("

").text("Height (m)").appendTo($('#graph'));
                  yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20);
                }
              }
            }, this), true);

            return this;
          },

          getDataPoints : function(elevresult) {
            var dataPoints = [];
            for (var xy = 0; xy < elevresult.range_height.length; xy++) {
              dataPoints.push({
                x : elevresult.range_height[xy][0] != null ? elevresult.range_height[xy][0] : 0,
                y : elevresult.range_height[xy][1] != null ? elevresult.range_height[xy][1] : 0
              });
            }
            return dataPoints;
          },

          showTooltip : function(x, y, contents, z) {
            $('
' + contents + '
').css({
              position : 'absolute',
              display : 'none',
              'font-weight' : 'bold',
              border : '1px solid rgb(255, 221, 221)',
              padding : '2px',
              'background-color' : z,
              opacity : '0.8'
            }).appendTo("body").show();
          },

          bindEvents : function(plot) {
            $('#graph').on('plothover', function(event, pos, item) {
              if (item) {
                if ((previousPoint != item.dataIndex) || (previousLabel != item.series.label)) {
                  previousPoint = item.dataIndex;
                  previousLabel = item.series.label;

                  $("#flot-tooltip").remove();

                  var x = getDataPoints(item.dataPoints[0]), y = item.dataPoints[1];
                  z = item.series.color;

                  showTooltip(item.pageX, item.pageY, "" + item.series.label + "
 " + x + " = " + y + "mm", z);
                }
              } else {
                $("#flot-tooltip").remove();
                previousPoint = null;
              }
            });
          },

          _locationKey : function(location) {
            return location[0] + ',' + location[1];
          }
        });

        L.elevation = function(accessToken, shape, options) {
          return new L.Elevation(accessToken, shape, options);
        };

        module.exports = L.Elevation;
      })();

    }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  }, {
    "corslite" : 1,
    "polyline" : 2
  } ]
}, {}, [ 3 ]);<|endoftext|>


<commit_before>'use strict'

const query = `
  create (spender:Transaction {id: {id}})
  with spender, range(0, size({outputs})) as outputsRange
  unwind outputsRange as i
  with spender, toString(i) as outputPosition, {outputs}[i] as output
  match (address:Address)-[:Outputs]->(outputsIndex)
    -[pointer:Unspent]->(spendee:Transaction)
  where address.id=output.address and
    (spendee.id + '::' + pointer.id) in output.previous
  create (spender)-[:Spends {id: pointer.id}]->(spendee)
  create (spender)<-[:Points {id: outputPosition}]-(outputsIndex)
  create (spender)<-[:Unspent {id: outputPosition}]-(outputsIndex)
  delete pointer
  with address.id as address, output.previous as previous
  return address, previous
`

module.exports = {
  string: query.replace(/\n/g, '').trim(),
  parser(result) {
    return {
      address: result.get('address'),
      previous: result.get('previous')
    }
  }
}
<commit_msg>feat(queries): optimized flow and fixed recursivity bug<commit_after>'use strict'

const query = `
  create (spender:Transaction {id: {id}})
  with spender, range(0, size({outputs})) as outputsRange
  unwind outputsRange as i
  with spender, toString(i) as outputPosition, {outputs}[i] as output
  match (address:Address)-[index:Outputs]->(outputsIndex)
  where address.id=output.address and index.id=output.currency
  merge (spender)<-[:Points {id: outputPosition}]-(outputsIndex)
  merge (spender)<-[:Unspent {id: outputPosition}]-(outputsIndex)
  with address, spender, outputsIndex, output
  match (outputsIndex)-[pointer:Unspent]->(spendee:Transaction)
  where (spendee.id + '::' + pointer.id) in output.previous
  create (spender)-[:Spends {id: pointer.id}]->(spendee)
  delete pointer
  return address.id as address, output.previous as previous
`

module.exports = {
  string: query.replace(/\n/g, '').trim(),
  parser(result) {
    return {
      address: result.get('address'),
      previous: result.get('previous')
    }
  }
}
<|endoftext|>


<commit_before>var fs = require("fs");
if(fs.existsSync("./.env")) {
  require('dotenv').config();
}

var Promise = require("promise");
var discord = require("discord.js");
var settings = require("./settings.json");
var convert = require("./convert.json").read2form;

// Imports all modules flagged as true in settings.json into modules object
var modules = { help: {} }
Object.keys(settings.modules).forEach(function(key) {
  if(settings.modules[key]) {
    modules[key] = require("./modules/" + key + ".js");
  }
});
Object.keys(settings.help).forEach(function(key) {
  if(settings.help[key]) {
    modules.help[key] = null;
  }
});
var bot = new discord.Client();

bot.on("ready", function() {
  console.log(pluralCheck("Module", "", "s", modules) + " loaded: " + Object.keys(modules).join(", "));
  console.log("Logged in as " + bot.user.username + "#" + bot.user.discriminator);
});

bot.on("disconnect", function() { });

// Command syntax goes as follows[e.g.]: module[dex], command[moves], subcommand[tm], item[nidoking]
bot.on("message", function(message) {
  if(message.author !== bot.user && message.content.startsWith(settings.prefix)) {
    var params = message.content.substring(1).split(" ");

    // Owner kill switch
    if(params[0] === "die" && message.author.username + "#" + message.author.discriminator === settings.owner) {
      console.log("Kill command issued from " + message.author.username + "#" + message.author.discriminator)
      closeBot("chat");
      return;
    }

    // About the project
    if(params[0] === "about") {
    }

    /* Sends input to the correct module */
    // Bot help
    if(params[0] in modules.help) {
      message.channel.sendMessage("Welcome to Pokemiah\nNote: Commands and subs are completely optional\n"
       + "Usage: " + settings.prefix + "<module> <command> <sub> <name>\n"
       + pluralCheck("Module", "", "s", modules) + "(default is \"" + settings['default-module'] + "\"): " + Object.keys(modules).join(", "));
    }

    // Module found
    else if(params[0] in modules) {
      // Module help
      if(params[1] in modules.help) {
        modules[params[0]].help(message);
      }

      // Command found
      else if(params[1] in modules[params[0]] && params[1] !== "run") {

        // Command help
        if(params[2] in modules.help) {
          modules[params[0]][params[1]].help(message);
        }

        // Sub found and passed into function
        else if("sub" in modules[params[0]][params[1]] && params[2] in modules[params[0]][params[1]].sub) {
          // No name specified, call command help
          if(params.slice(3).length === 0) {
            modules[params[0]][params[1]].help(message);
          }
          // Name found and passed into function
          else {
            modules[params[0]][params[1]].run(message, toApiCase(params.slice(3).join("-")), modules[params[0]][params[1]].sub[params[2]]);
          }
        }

        // Sub not found, push rest of input into default sub api call
        else {
          modules[params[0]][params[1]].run(message, toApiCase(params.slice(2).join("-")));
        }
      }

      // Command not found, push rest of input into default command api call
      else {
        modules[params[0]].run(message, toApiCase(params.slice(1).join("-")));
      }

    }

    // Module not found, push rest of input into default module api call
    else {
      if(settings['default-module'] in modules) {
        modules[settings['default-module']].run(message, toApiCase(params.slice(0).join("-")));
      }
      else {
        message.channel.sendMessage("No default module specified");
      }
    }
    /**/
  }
});

bot.login(process.env.DISCORD_TOKEN);

// Handers for exit types
process.on("SIGINT", closeBot.bind(null, "SIGINT"));
process.on("uncaughtException", closeBot.bind(null, "uncaughtException"));

function toApiCase(string) {
  var api = string.replace(/é/g,"e").replace(/[^\-0-9A-Za-z?!]/g,"").toLowerCase();
  if(api in convert)
  {
    api = convert[api];
  }
  return api;
}

function pluralCheck(o, s, p, list) {
  if(Object.keys(list).length > 1) {
    return o + p;
  }
  else {
    return o + s;
  }
}

// Cleanup for closing the bot application
function closeBot(code) {
  console.log("Exit issued from: " + code);
  console.log("Logging off...");
  bot.destroy();
  process.exit();
}
<commit_msg>Unneeded require<commit_after>var fs = require("fs");
if(fs.existsSync("./.env")) {
  require('dotenv').config();
}

var discord = require("discord.js");
var settings = require("./settings.json");
var convert = require("./convert.json").read2form;

// Imports all modules flagged as true in settings.json into modules object
var modules = { help: {} }
Object.keys(settings.modules).forEach(function(key) {
  if(settings.modules[key]) {
    modules[key] = require("./modules/" + key + ".js");
  }
});
Object.keys(settings.help).forEach(function(key) {
  if(settings.help[key]) {
    modules.help[key] = null;
  }
});
var bot = new discord.Client();

bot.on("ready", function() {
  console.log(pluralCheck("Module", "", "s", modules) + " loaded: " + Object.keys(modules).join(", "));
  console.log("Logged in as " + bot.user.username + "#" + bot.user.discriminator);
});

bot.on("disconnect", function() { });

// Command syntax goes as follows[e.g.]: module[dex], command[moves], subcommand[tm], item[nidoking]
bot.on("message", function(message) {
  if(message.author !== bot.user && message.content.startsWith(settings.prefix)) {
    var params = message.content.substring(1).split(" ");

    // Owner kill switch
    if(params[0] === "die" && message.author.username + "#" + message.author.discriminator === settings.owner) {
      console.log("Kill command issued from " + message.author.username + "#" + message.author.discriminator)
      closeBot("chat");
      return;
    }

    // About the project
    if(params[0] === "about") {
    }

    /* Sends input to the correct module */
    // Bot help
    if(params[0] in modules.help) {
      message.channel.sendMessage("Welcome to Pokemiah\nNote: Commands and subs are completely optional\n"
       + "Usage: " + settings.prefix + "<module> <command> <sub> <name>\n"
       + pluralCheck("Module", "", "s", modules) + "(default is \"" + settings['default-module'] + "\"): " + Object.keys(modules).join(", "));
    }

    // Module found
    else if(params[0] in modules) {
      // Module help
      if(params[1] in modules.help) {
        modules[params[0]].help(message);
      }

      // Command found
      else if(params[1] in modules[params[0]] && params[1] !== "run") {

        // Command help
        if(params[2] in modules.help) {
          modules[params[0]][params[1]].help(message);
        }

        // Sub found and passed into function
        else if("sub" in modules[params[0]][params[1]] && params[2] in modules[params[0]][params[1]].sub) {
          // No name specified, call command help
          if(params.slice(3).length === 0) {
            modules[params[0]][params[1]].help(message);
          }
          // Name found and passed into function
          else {
            modules[params[0]][params[1]].run(message, toApiCase(params.slice(3).join("-")), modules[params[0]][params[1]].sub[params[2]]);
          }
        }

        // Sub not found, push rest of input into default sub api call
        else {
          modules[params[0]][params[1]].run(message, toApiCase(params.slice(2).join("-")));
        }
      }

      // Command not found, push rest of input into default command api call
      else {
        modules[params[0]].run(message, toApiCase(params.slice(1).join("-")));
      }

    }

    // Module not found, push rest of input into default module api call
    else {
      if(settings['default-module'] in modules) {
        modules[settings['default-module']].run(message, toApiCase(params.slice(0).join("-")));
      }
      else {
        message.channel.sendMessage("No default module specified");
      }
    }
    /**/
  }
});

bot.login(process.env.DISCORD_TOKEN);

// Handers for exit types
process.on("SIGINT", closeBot.bind(null, "SIGINT"));
process.on("uncaughtException", closeBot.bind(null, "uncaughtException"));

function toApiCase(string) {
  var api = string.replace(/é/g,"e").replace(/[^\-0-9A-Za-z?!]/g,"").toLowerCase();
  if(api in convert)
  {
    api = convert[api];
  }
  return api;
}

function pluralCheck(o, s, p, list) {
  if(Object.keys(list).length > 1) {
    return o + p;
  }
  else {
    return o + s;
  }
}

// Cleanup for closing the bot application
function closeBot(code) {
  console.log("Exit issued from: " + code);
  console.log("Logging off...");
  bot.destroy();
  process.exit();
}
<|endoftext|>


<commit_before>var utility = require('./utility');
var async = require('async');
var db = utility.db;
var logger = utility.logger;
var fs = require('fs');
var moment = require('moment');
var getData = utility.getData;
var request = require('request');
var insertPlayer = utility.insertPlayer;
var insertMatch = utility.insertMatch;
var spawn = require('child_process').spawn;
var replay_dir = process.env.REPLAY_DIR || "./replays/";
var domain = require('domain');

function processParse(job, cb) {
    var t1 = new Date();
    var match_id = job.data.payload.match_id;
    var attempts = job.toJSON().attempts.remaining;
    var noRetry = attempts <= 1;
    async.waterfall([
        async.apply(checkLocal, job),
        getReplayUrl,
        streamReplay,
    ], function(err, job2) {
        logger.info("[PARSER] match_id %s, parse time: %s", match_id, (new Date() - t1) / 1000);
        if (err === "replay expired" || (err && noRetry)) {
            logger.info("match_id %s, error %s, not retrying", match_id, err);
            return db.matches.update({
                match_id: match_id
            }, {
                $set: {
                    parse_status: 1
                }
            }, function(err2) {
                //nullify error if replay expired
                err = err === "replay expired" ? null : err;
                cb(err || err2);
            });
        }
        else if (err) {
            logger.info("match_id %s, error %s, attempts %s", match_id, err, attempts);
            return cb(err);
        }
        else {
            return cb(err);
        }
    });
}

function checkLocal(job, cb) {
    var match_id = job.data.payload.match_id;
    var fileName = job.data.fileName || replay_dir + match_id + ".dem";
    if (fs.existsSync(fileName)) {
        logger.info("[PARSER] %s, found local replay", match_id);
        job.data.fileName = fileName;
        job.update();
    }
    cb(null, job);
}

function getReplayUrl(job, cb) {
    if (job.data.url || job.data.fileName) {
        logger.info("has url or fileName");
        return cb(null, job);
    }
    var match = job.data.payload;
    if (match.start_time > moment().subtract(7, 'days').format('X')) {
        getData("http://retriever?match_id=" + job.data.payload.match_id, function(err, body) {
            if (err || !body || !body.match) {
                return cb("invalid body or error");
            }
            var url = "http://replay" + body.match.cluster + ".valve.net/570/" + match.match_id + "_" + body.match.replaySalt + ".dem.bz2";
            job.data.url = url;
            job.update();
            return cb(null, job);
        });
    }
    /*
    else if (process.env.AWS_S3_BUCKET) {
        getS3Url(match.match_id, function(err, url) {
            if (!url) {
                return cb("replay expired");
            }
            job.data.url = url;
            job.update();
            return cb(err, job);
        });
    }
    */
    else {
        cb("replay expired");
    }
}

function streamReplay(job, cb) {
    //var fileName = replay_dir + match_id + ".dem";
    //var archiveName = fileName + ".bz2";
    var match_id = job.data.payload.match_id;
    logger.info("[PARSER] streaming from %s", job.data.url || job.data.fileName);
    var d = domain.create();
    d.on('error', function(err) {
        cb(err);
    });
    d.run(function() {
        var parser = utility.runParse(function(err, output) {
            if (err) {
                return cb(err);
            }
            db.matches.update({
                match_id: match_id
            }, {
                $set: {
                    parsed_data: output,
                    parse_status: 2
                }
            }, function(err) {
                cb(err, job);
            });
        });
        if (job.data.fileName) {
            fs.createReadStream(job.data.fileName).pipe(parser.stdin);
        }
        else {
            var bz = spawn("bzcat");
            var downStream = request.get({
                url: job.data.url,
                encoding: null,
                timeout: 180000
            });
            downStream.on('response', function(resp) {
                if (resp.statusCode !== 200) {
                    //put error information into job
                    //can't just cb(err) or else the parser crashing will consume another attempt
                    job.data.error="download error";
                    job.update();
                }
            });
            downStream.pipe(bz.stdin);
            bz.stdout.pipe(parser.stdin);
        }
    });
}

function processApi(job, cb) {
    //process an api request
    var payload = job.data.payload;
    getData(job.data.url, function(err, data) {
        if (err) {
            return cb(err);
        }
        if (data.response) {
            logger.info("summaries response");
            async.map(data.response.players, insertPlayer, function(err) {
                cb(err);
            });
        }
        else if (payload.match_id) {
            logger.info("details response");
            var match = data.result;
            //join payload with match
            for (var prop in payload) {
                match[prop] = match[prop] ? match[prop] : payload[prop];
            }
            insertMatch(match, function(err) {
                cb(err);
            });
        }
        else {
            return cb("unknown response");
        }
    });
}

module.exports = {
    processParse: processParse,
    processApi: processApi
};
<commit_msg>changed error handling in processparse<commit_after>var utility = require('./utility');
var async = require('async');
var db = utility.db;
var logger = utility.logger;
var fs = require('fs');
var moment = require('moment');
var getData = utility.getData;
var request = require('request');
var insertPlayer = utility.insertPlayer;
var insertMatch = utility.insertMatch;
var spawn = require('child_process').spawn;
var replay_dir = process.env.REPLAY_DIR || "./replays/";
var domain = require('domain');

function processParse(job, cb) {
    var t1 = new Date();
    var match_id = job.data.payload.match_id;
    var attempts = job.toJSON().attempts.remaining;
    var noRetry = attempts <= 1;
    async.waterfall([
        async.apply(checkLocal, job),
        getReplayUrl,
        streamReplay,
    ], function(err, job2) {
        logger.info("[PARSER] match_id %s, parse time: %s", match_id, (new Date() - t1) / 1000);
        if (err === "replay expired" || (err && noRetry)) {
            logger.info("match_id %s, error %s, not retrying", match_id, err);
            return db.matches.update({
                match_id: match_id
            }, {
                $set: {
                    parse_status: 1
                }
            }, function(err2) {
                //nullify error if replay expired
                err = err === "replay expired" ? null : err;
                cb(err || err2);
            });
        }
        else if (err) {
            logger.info("match_id %s, error %s, attempts %s", match_id, err, attempts);
            return cb(err);
        }
        else {
            return cb(err);
        }
    });
}

function checkLocal(job, cb) {
    var match_id = job.data.payload.match_id;
    var fileName = job.data.fileName || replay_dir + match_id + ".dem";
    if (fs.existsSync(fileName)) {
        logger.info("[PARSER] %s, found local replay", match_id);
        job.data.fileName = fileName;
        job.update();
    }
    cb(null, job);
}

function getReplayUrl(job, cb) {
    if (job.data.url || job.data.fileName) {
        logger.info("has url or fileName");
        return cb(null, job);
    }
    var match = job.data.payload;
    if (match.start_time > moment().subtract(7, 'days').format('X')) {
        getData("http://retriever?match_id=" + job.data.payload.match_id, function(err, body) {
            if (err || !body || !body.match) {
                return cb("invalid body or error");
            }
            var url = "http://replay" + body.match.cluster + ".valve.net/570/" + match.match_id + "_" + body.match.replaySalt + ".dem.bz2";
            job.data.url = url;
            job.update();
            return cb(null, job);
        });
    }
    /*
    else if (process.env.AWS_S3_BUCKET) {
        getS3Url(match.match_id, function(err, url) {
            if (!url) {
                return cb("replay expired");
            }
            job.data.url = url;
            job.update();
            return cb(err, job);
        });
    }
    */
    else {
        cb("replay expired");
    }
}

function streamReplay(job, cb) {
    //var fileName = replay_dir + match_id + ".dem";
    //var archiveName = fileName + ".bz2";
    var match_id = job.data.payload.match_id;
    logger.info("[PARSER] streaming from %s", job.data.url || job.data.fileName);
    var d = domain.create();
    var error;
    d.on('error', function(err) {
        if (!error) {
            //only cb with first error
            error = err;
            cb(err);
        }
    });
    d.run(function() {
        var parser = utility.runParse(function(err, output) {
            if (err) {
                throw err;
            }
            db.matches.update({
                match_id: match_id
            }, {
                $set: {
                    parsed_data: output,
                    parse_status: 2
                }
            }, function(err) {
                cb(err, job);
            });
        });
        if (job.data.fileName) {
            fs.createReadStream(job.data.fileName).pipe(parser.stdin);
        }
        else {
            var bz = spawn("bzcat");
            var downStream = request.get({
                url: job.data.url,
                encoding: null,
                timeout: 180000
            });
            downStream.on('response', function(resp) {
                if (resp.statusCode !== 200) {
                    throw "download error";
                }
            });
            downStream.pipe(bz.stdin);
            bz.stdout.pipe(parser.stdin);
        }
    });
}

function processApi(job, cb) {
    //process an api request
    var payload = job.data.payload;
    getData(job.data.url, function(err, data) {
        if (err) {
            return cb(err);
        }
        if (data.response) {
            logger.info("summaries response");
            async.map(data.response.players, insertPlayer, function(err) {
                cb(err);
            });
        }
        else if (payload.match_id) {
            logger.info("details response");
            var match = data.result;
            //join payload with match
            for (var prop in payload) {
                match[prop] = match[prop] ? match[prop] : payload[prop];
            }
            insertMatch(match, function(err) {
                cb(err);
            });
        }
        else {
            return cb("unknown response");
        }
    });
}

module.exports = {
    processParse: processParse,
    processApi: processApi
};
<|endoftext|>


<commit_before>import { DEFAULT_LOCATION } from '../utils/constants';

export const currentLocation = (location) => {
  return {
    type: 'CURRENT_LOCATION',
    location,
  }
}

export const nearbyLocations = (data) => {
  return {
    type: 'NEARBY_LOCATIONS',
    data,
  }
}

export const mapCenter = (position) => {
  return {
    type: 'CENTER',
    position
  }
}

export const geolocate = () => {
  return (dispatch) => {

    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        const { coords } = position;
        const coordinates = {
          lat: coords.latitude,
          lng: coords.longitude,
        }

        dispatch(currentLocation(coordinates));
      });
    } else {

      dispatch(currentLocation(DEFAULT_LOCATION.coordinates));
    }
  }
}
<commit_msg>fix centering on map<commit_after>import { DEFAULT_LOCATION } from '../utils/constants';

export const currentLocation = (location) => {
  return {
    type: 'CURRENT_LOCATION',
    location,
  }
}

export const nearbyLocations = (data) => {
  return {
    type: 'NEARBY_LOCATIONS',
    data,
  }
}

export const mapCenter = (position) => {
  return {
    type: 'CENTER',
    position
  }
}

export const geolocate = () => {
  return (dispatch) => {

    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        const { coords } = position;
        const coordinates = {
          lat: coords.latitude,
          lng: coords.longitude,
        }

        dispatch(currentLocation(coordinates));
        dispatch(mapCenter(coordinates));
      });
    } else {

      dispatch(currentLocation(DEFAULT_LOCATION.coordinates));
    }
  }
}
<|endoftext|>


<commit_before>import { regexes } from './smileys';

/**
 * Processes links and smileys in "body".
 *
 * @param  {string} body - The message body.
 * @returns {string} Message body with image tags and href tags.
 */
export function processReplacements(body) {
    // make links clickable + add smileys
    return smilify(linkify(body));
}

/**
 * Finds and replaces all links in the links in "body" with an href tag.
 *
 * @param  {string} inputText - The message body.
 * @returns {string} The text replaced with HTML tags for links.
 */
function linkify(inputText) {
    let replacedText;

    /* eslint-disable no-useless-escape, max-len */

    // URLs starting with http://, https://, or ftp://
    const replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;

    replacedText = inputText.replace(replacePattern1, '$1');

    // URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    const replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;

    replacedText = replacedText.replace(replacePattern2, '$1$2');

    // Change email addresses to mailto: links.
    const replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;

    replacedText = replacedText.replace(replacePattern3, '$1');

    /* eslint-enable no-useless-escape */

    return replacedText;
}

/**
 * Replaces common smiley strings with images.
 *
 * @param  {string} body - The message body.
 * @returns {string} Body returned with smiley replaced.
 */
function smilify(body) {
    if (!body) {
        return body;
    }

    let formattedBody = body;

    for (const smiley in regexes) {
        if (regexes.hasOwnProperty(smiley)) {
            formattedBody = formattedBody.replace(regexes[smiley],
                `<img class="smiley" src="images/smileys/${smiley}.svg">`);
        }
    }

    return formattedBody;
}
<commit_msg>Make sure we do only one replacement, not one over another for messages.<commit_after>import { regexes } from './smileys';

/* eslint-disable no-useless-escape, max-len */
const replacePatterns = {

    // URLs starting with http://, https://, or ftp://
    '$1':
        /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim,

    // URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    '$1$2':
        /(^|[^\/])(www\.[\S]+(\b|$))/gim,

    // Change email addresses to mailto: links.
    '$1':
        /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim
};
/* eslint-enable no-useless-escape, max-len */

/**
 * Processes links and smileys in "body".
 *
 * @param  {string} body - The message body.
 * @returns {string} Message body with image tags and href tags.
 */
export function processReplacements(body) {
    // make links clickable + add smileys

    // non of the patterns we search contains a space, that's why we tokenize it
    // and after processing each token we join it again with the results
    // making sure we do only one replacement for a token
    const tokens = body.split(' ');
    const resultText = [];

    for (const token of tokens) {
        let replacedText;
        const tokenLength = token.length;

        for (const newString in replacePatterns) { // eslint-disable-line guard-for-in, max-len
            const replacePattern = replacePatterns[newString];

            replacedText = token.replace(replacePattern, newString);

            // replacement was done, stop doing any other replacements
            if (replacedText.length > tokenLength) {
                break;
            }
            replacedText = null;
        }

        // no replacement was done, then just check for smiley
        if (!replacedText) {
            replacedText = smilify(token);
        }

        resultText.push(replacedText);
    }

    return resultText.join(' ');
}

/**
 * Replaces common smiley strings with images.
 *
 * @param  {string} body - The message body.
 * @returns {string} Body returned with smiley replaced.
 */
function smilify(body) {
    if (!body) {
        return body;
    }

    let formattedBody = body;

    for (const smiley in regexes) {
        if (regexes.hasOwnProperty(smiley)) {
            formattedBody = formattedBody.replace(regexes[smiley],
                `<img class="smiley" src="images/smileys/${smiley}.svg">`);
        }
    }

    return formattedBody;
}
<|endoftext|>


<commit_before>'use strict';

var d              = require('d')
  , validateSymbol = require('./validate-symbol')

  , create = Object.create, defineProperties = Object.defineProperties
  , defineProperty = Object.defineProperty, objPrototype = Object.prototype
  , SymbolPolyfill, HiddenSymbol, globalSymbols = create(null);

var generateName = (function () {
	var created = create(null);
	return function (desc) {
		var postfix = 0, name;
		while (created[desc + (postfix || '')]) ++postfix;
		desc += (postfix || '');
		created[desc] = true;
		name = '@@' + desc;
		defineProperty(objPrototype, name, d.gs(null, function (value) {
			defineProperty(this, name, d(value));
		}));
		return name;
	};
}());

HiddenSymbol = function Symbol(description) {
	if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor');
	return SymbolPolyfill(description);
};
module.exports = SymbolPolyfill = function Symbol(description) {
	var symbol;
	if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor');
	symbol = create(HiddenSymbol.prototype);
	description = (description === undefined ? '' : String(description));
	return defineProperties(symbol, {
		__description__: d('', description),
		__name__: d('', generateName(description))
	});
};
defineProperties(SymbolPolyfill, {
	for: d(function (key) {
		if (globalSymbols[key]) return globalSymbols[key];
		return (globalSymbols[key] = SymbolPolyfill(String(key)));
	}),
	keyFor: d(function (s) {
		var key;
		validateSymbol(s);
		for (key in globalSymbols) if (globalSymbols[key] === s) return key;
	}),
	hasInstance: d('', SymbolPolyfill('hasInstance')),
	isConcatSpreadable: d('', SymbolPolyfill('isConcatSpreadable')),
	iterator: d('', SymbolPolyfill('iterator')),
	match: d('', SymbolPolyfill('match')),
	replace: d('', SymbolPolyfill('replace')),
	search: d('', SymbolPolyfill('search')),
	species: d('', SymbolPolyfill('species')),
	split: d('', SymbolPolyfill('split')),
	toPrimitive: d('', SymbolPolyfill('toPrimitive')),
	toStringTag: d('', SymbolPolyfill('toStringTag')),
	unscopables: d('', SymbolPolyfill('unscopables'))
});
defineProperties(HiddenSymbol.prototype, {
	constructor: d(SymbolPolyfill),
	toString: d('', function () { return this.__name__; })
});

defineProperties(SymbolPolyfill.prototype, {
	toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }),
	valueOf: d(function () { return validateSymbol(this); })
});
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('',
	function () { return validateSymbol(this); }));
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));

defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
	d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));
defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
	d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));
<commit_msg>Reuse native symbols if available<commit_after>'use strict';

var d              = require('d')
  , validateSymbol = require('./validate-symbol')

  , create = Object.create, defineProperties = Object.defineProperties
  , defineProperty = Object.defineProperty, objPrototype = Object.prototype
  , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null);

if (typeof Symbol === 'function') NativeSymbol = Symbol;

var generateName = (function () {
	var created = create(null);
	return function (desc) {
		var postfix = 0, name;
		while (created[desc + (postfix || '')]) ++postfix;
		desc += (postfix || '');
		created[desc] = true;
		name = '@@' + desc;
		defineProperty(objPrototype, name, d.gs(null, function (value) {
			defineProperty(this, name, d(value));
		}));
		return name;
	};
}());

HiddenSymbol = function Symbol(description) {
	if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor');
	return SymbolPolyfill(description);
};
module.exports = SymbolPolyfill = function Symbol(description) {
	var symbol;
	if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor');
	symbol = create(HiddenSymbol.prototype);
	description = (description === undefined ? '' : String(description));
	return defineProperties(symbol, {
		__description__: d('', description),
		__name__: d('', generateName(description))
	});
};
defineProperties(SymbolPolyfill, {
	for: d(function (key) {
		if (globalSymbols[key]) return globalSymbols[key];
		return (globalSymbols[key] = SymbolPolyfill(String(key)));
	}),
	keyFor: d(function (s) {
		var key;
		validateSymbol(s);
		for (key in globalSymbols) if (globalSymbols[key] === s) return key;
	}),
	hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')),
	isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
		SymbolPolyfill('isConcatSpreadable')),
	iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')),
	match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')),
	replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')),
	search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')),
	species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')),
	split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')),
	toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')),
	toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')),
	unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables'))
});
defineProperties(HiddenSymbol.prototype, {
	constructor: d(SymbolPolyfill),
	toString: d('', function () { return this.__name__; })
});

defineProperties(SymbolPolyfill.prototype, {
	toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }),
	valueOf: d(function () { return validateSymbol(this); })
});
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('',
	function () { return validateSymbol(this); }));
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));

defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
	d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));
defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
	d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));
<|endoftext|>


<commit_before>'use strict';

var implementation = require('./implementation');

var supportsDescriptors = require('define-properties').supportsDescriptors;
var gOPD = Object.getOwnPropertyDescriptor;
var TypeErr = TypeError;

module.exports = function getPolyfill() {
	if (!supportsDescriptors) {
		throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
	}
	if (/a/mig.flags === 'gim') {
		return gOPD(RegExp.prototype, 'flags').get;
	}
	return implementation;
};
<commit_msg>[Fix] cover the case where there is no descriptor on the prototype<commit_after>'use strict';

var implementation = require('./implementation');

var supportsDescriptors = require('define-properties').supportsDescriptors;
var gOPD = Object.getOwnPropertyDescriptor;
var TypeErr = TypeError;

module.exports = function getPolyfill() {
	if (!supportsDescriptors) {
		throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
	}
	if (/a/mig.flags === 'gim') {
		var descriptor = gOPD(RegExp.prototype, 'flags');
		if (descriptor && typeof descriptor.get === 'function') {
			return descriptor.get;
		}
	}
	return implementation;
};
<|endoftext|>


<commit_before>const request = require('request-promise');

request.get({url: 'http://localhost:3000/users', json: true }) => {
    const [firstUser] = response.body;

    request.get({url: 'http://localhost:3000/users/' + firstUser + '/age'}, (error, response) => {

        const {userAge} = JSON.parse(response.body);
        console.log('>>> Age of first user is: ' + userAge + ' <<<');
    });
});<commit_msg>clenaup<commit_after><|endoftext|>