<commit_before>/* HEADER BEGIN */
var util = require('./util'),
    updateMap = util.updateMap,
    updateVersion = util.updateVersion,
    updateCategory = util.updateCategory,
    updateOs = util.updateOs,
    dataset = require('./dataset');
/* HEADER END */

var windowsPattern = /Windows ([ .a-zA-Z0-9]+)[;\\)]/;
var windowsPhonePattern = /^Phone OS/;
var challengeWindows = exports.challengeWindows = function(ua, result) {
  if (ua.indexOf('Windows') < 0)
    return false;

  // Xbox Series
  if (ua.indexOf('Xbox') > -1) {
    var d;
    if (ua.indexOf('Xbox; Xbox One)') > -1)
      d = dataset.get("XboxOne");
    else
      d = dataset.get("Xbox360");
    // overwrite browser detections as appliance
    updateMap(result, d);
    return true;
  }

  var data = dataset.get('Win');
  var match = windowsPattern.exec(ua);
  if (!match) {
    // Windows, but version unknown
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_NAME]);
    return true;
  }
  var version = match[1];
  if (version === 'NT 6.3') data = dataset.get('Win8.1');
  else if (version === 'NT 6.2') data = dataset.get('Win8'); // "NT 6.2; ARM;" means Windows RT, oh....
  else if (version === 'NT 6.1') data = dataset.get('Win7');
  else if (version === 'NT 6.0') data = dataset.get('WinVista');
  else if (version === 'NT 5.1') data = dataset.get('WinXP');
  else if (windowsPhonePattern.exec(version)) data = dataset.get('WinPhone');
  else if (version === 'NT 5.0') data = dataset.get('Win2000');
  else if (version === 'NT 4.0') data = dataset.get('WinNT4');
  else if (version === '98') data = dataset.get('Win98'); // wow, WinMe is shown as 'Windows 98; Win9x 4.90', fxxxk
  else if (version === '95') data = dataset.get('Win95');
  else if (version === 'CE') data = dataset.get('WinCE');
  /*
  else
    // windows unknown
   */
  updateCategory(result, data[dataset.KEY_CATEGORY]);
  updateOs(result, data[dataset.KEY_NAME]);
  return true;
};

var challengeOSX = exports.challengeOSX = function(ua, result) {
  if (ua.indexOf('Mac OS X') < 0)
    return false;

  var data = dataset.get('OSX');
  if (ua.indexOf('like Mac OS X') >= 0) {
    if (ua.indexOf('iPhone;') >= 0) data = dataset.get('iPhone');
    else if (ua.indexOf('iPad;') >= 0) data = dataset.get('iPad');
    else if (ua.indexOf('iPod;') >= 0) data = dataset.get('iPod');
  }
  updateCategory(result, data[dataset.KEY_CATEGORY]);
  updateOs(result, data[dataset.KEY_NAME]);
  return true;
};

var challengeLinux = exports.challengeLinux = function(ua, result) {
  if (ua.indexOf('Linux') < 0)
    return false;

  var data = dataset.get('Linux');
  if (ua.indexOf('Android') >= 0)
    data = dataset.get('Android');
  updateCategory(result, data[dataset.KEY_CATEGORY]);
  updateOs(result, data[dataset.KEY_NAME]);
  return true;
};

var challengeSmartPhone = exports.challengeSmartPhone = function(ua, result) {
  var data = null;
  if (ua.indexOf('iPhone') >= 0) data = dataset.get('iPhone');
  else if (ua.indexOf('iPad') >= 0) data = dataset.get('iPad');
  else if (ua.indexOf('iPod') >= 0) data = dataset.get('iPod');
  else if (ua.indexOf('Android') >= 0) data = dataset.get('Android');
  else if (ua.indexOf('CFNetwork') >= 0) data = dataset.get('iOS');
  else if (ua.indexOf('BlackBerry') >= 0) data = dataset.get('BlackBerry');

  if (result[dataset.KEY_NAME] && result[dataset.KEY_NAME] === dataset.get('Firefox')[dataset.KEY_NAME]) {
    // Firefox OS specific pattern
    // http://lawrencemandel.com/2012/07/27/decision-made-firefox-os-user-agent-string/
    if (/^Mozilla\/[.0-9]+ \(Mobile;(.*;)? rv:[.0-9]+\) Gecko\/[.0-9]+ Firefox\/[.0-9]+$/.exec(ua)) {
      data = dataset.get('FirefoxOS');
    }
  }

  if (!data)
    return false;

  updateCategory(result, data[dataset.KEY_CATEGORY]);
  updateOs(result, data[dataset.KEY_NAME]);
  return true;
};

var challengeMobilePhone = exports.challengeMobilePhone = function(ua, result) {
  var data,match;
  if (ua.indexOf('KDDI-') >= 0) {
    if ((match = /KDDI-([^- \/;()"']+)/.exec(ua))) {
      var term = match[1];
      data = dataset.get('au');
      updateCategory(result, data[dataset.KEY_CATEGORY]);
      updateOs(result, data[dataset.KEY_OS]);
      updateVersion(result, term);
      return true;
    }
  }
  if (ua.indexOf('WILLCOM') >= 0 || ua.indexOf('DDIPOCKET') >= 0) {
    if ((match = /(?:WILLCOM|DDIPOCKET);[^\/]+\/([^ \/;()]+)/.exec(ua))) {
      term = match[1];
      data = dataset.get('willcom');
      updateCategory(result, data[dataset.KEY_CATEGORY]);
      updateOs(result, data[dataset.KEY_OS]);
      updateVersion(result, term);
      return true;
    }
  }
  if (ua.indexOf('SymbianOS') >= 0) {
    data = dataset.get('SymbianOS');
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_OS]);
    return true;
  }
  if (ua.indexOf('Google Wireless Transcoder') >= 0) {
    updateMap(result, dataset.get('MobileTranscoder'));
    updateVersion(result, 'Google');
    return true;
  }
  if (ua.indexOf('Naver Transcoder') >= 0) {
    updateMap(result, dataset.get('MobileTranscoder'));
    updateVersion(result, 'Naver');
    return true;
  }

  return false;
};

var challengeAppliance = exports.challengeAppliance = function(ua, result) {
  var data;
  if (ua.indexOf('Nintendo DSi;') >= 0) {
    data = dataset.get('NintendoDSi');
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_OS]);
    return true;
  }
  if (ua.indexOf('Nintendo Wii;') >= 0) {
    data = dataset.get('NintendoWii');
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_OS]);
    return true;
  }
  return false;
};

var challengeMisc = exports.challengeMisc = function(ua, result) {
  var data;
  if (ua.indexOf('(Win98;') >= 0) data = dataset.get('Win98');
  else if (ua.indexOf('Macintosh; U; PPC;') >= 0) data = dataset.get('MacOS');
  else if (ua.indexOf('Mac_PowerPC') >= 0) data = dataset.get('MacOS');
  else if (ua.indexOf('X11; FreeBSD ') >= 0) data = dataset.get('BSD');
  else if (ua.indexOf('X11; CrOS ') >= 0) data = dataset.get('ChromeOS');

  if (data) {
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_NAME]);
    return true;
  }

  return false;
};
<commit_msg>fix for Firefox OS Tablet<commit_after>/* HEADER BEGIN */
var util = require('./util'),
    updateMap = util.updateMap,
    updateVersion = util.updateVersion,
    updateCategory = util.updateCategory,
    updateOs = util.updateOs,
    dataset = require('./dataset');
/* HEADER END */

var windowsPattern = /Windows ([ .a-zA-Z0-9]+)[;\\)]/;
var windowsPhonePattern = /^Phone OS/;
var challengeWindows = exports.challengeWindows = function(ua, result) {
  if (ua.indexOf('Windows') < 0)
    return false;

  // Xbox Series
  if (ua.indexOf('Xbox') > -1) {
    var d;
    if (ua.indexOf('Xbox; Xbox One)') > -1)
      d = dataset.get("XboxOne");
    else
      d = dataset.get("Xbox360");
    // overwrite browser detections as appliance
    updateMap(result, d);
    return true;
  }

  var data = dataset.get('Win');
  var match = windowsPattern.exec(ua);
  if (!match) {
    // Windows, but version unknown
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_NAME]);
    return true;
  }
  var version = match[1];
  if (version === 'NT 6.3') data = dataset.get('Win8.1');
  else if (version === 'NT 6.2') data = dataset.get('Win8'); // "NT 6.2; ARM;" means Windows RT, oh....
  else if (version === 'NT 6.1') data = dataset.get('Win7');
  else if (version === 'NT 6.0') data = dataset.get('WinVista');
  else if (version === 'NT 5.1') data = dataset.get('WinXP');
  else if (windowsPhonePattern.exec(version)) data = dataset.get('WinPhone');
  else if (version === 'NT 5.0') data = dataset.get('Win2000');
  else if (version === 'NT 4.0') data = dataset.get('WinNT4');
  else if (version === '98') data = dataset.get('Win98'); // wow, WinMe is shown as 'Windows 98; Win9x 4.90', fxxxk
  else if (version === '95') data = dataset.get('Win95');
  else if (version === 'CE') data = dataset.get('WinCE');
  /*
  else
    // windows unknown
   */
  updateCategory(result, data[dataset.KEY_CATEGORY]);
  updateOs(result, data[dataset.KEY_NAME]);
  return true;
};

var challengeOSX = exports.challengeOSX = function(ua, result) {
  if (ua.indexOf('Mac OS X') < 0)
    return false;

  var data = dataset.get('OSX');
  if (ua.indexOf('like Mac OS X') >= 0) {
    if (ua.indexOf('iPhone;') >= 0) data = dataset.get('iPhone');
    else if (ua.indexOf('iPad;') >= 0) data = dataset.get('iPad');
    else if (ua.indexOf('iPod;') >= 0) data = dataset.get('iPod');
  }
  updateCategory(result, data[dataset.KEY_CATEGORY]);
  updateOs(result, data[dataset.KEY_NAME]);
  return true;
};

var challengeLinux = exports.challengeLinux = function(ua, result) {
  if (ua.indexOf('Linux') < 0)
    return false;

  var data = dataset.get('Linux');
  if (ua.indexOf('Android') >= 0)
    data = dataset.get('Android');
  updateCategory(result, data[dataset.KEY_CATEGORY]);
  updateOs(result, data[dataset.KEY_NAME]);
  return true;
};

var challengeSmartPhone = exports.challengeSmartPhone = function(ua, result) {
  var data = null;
  if (ua.indexOf('iPhone') >= 0) data = dataset.get('iPhone');
  else if (ua.indexOf('iPad') >= 0) data = dataset.get('iPad');
  else if (ua.indexOf('iPod') >= 0) data = dataset.get('iPod');
  else if (ua.indexOf('Android') >= 0) data = dataset.get('Android');
  else if (ua.indexOf('CFNetwork') >= 0) data = dataset.get('iOS');
  else if (ua.indexOf('BlackBerry') >= 0) data = dataset.get('BlackBerry');

  if (result[dataset.KEY_NAME] && result[dataset.KEY_NAME] === dataset.get('Firefox')[dataset.KEY_NAME]) {
    // Firefox OS specific pattern
    // http://lawrencemandel.com/2012/07/27/decision-made-firefox-os-user-agent-string/
    // https://github.com/woothee/woothee/issues/2
    if (/^Mozilla\/[.0-9]+ \((Mobile|Tablet);(.*;)? rv:[.0-9]+\) Gecko\/[.0-9]+ Firefox\/[.0-9]+$/.exec(ua)) {
      data = dataset.get('FirefoxOS');
    }
  }

  if (!data)
    return false;

  updateCategory(result, data[dataset.KEY_CATEGORY]);
  updateOs(result, data[dataset.KEY_NAME]);
  return true;
};

var challengeMobilePhone = exports.challengeMobilePhone = function(ua, result) {
  var data,match;
  if (ua.indexOf('KDDI-') >= 0) {
    if ((match = /KDDI-([^- \/;()"']+)/.exec(ua))) {
      var term = match[1];
      data = dataset.get('au');
      updateCategory(result, data[dataset.KEY_CATEGORY]);
      updateOs(result, data[dataset.KEY_OS]);
      updateVersion(result, term);
      return true;
    }
  }
  if (ua.indexOf('WILLCOM') >= 0 || ua.indexOf('DDIPOCKET') >= 0) {
    if ((match = /(?:WILLCOM|DDIPOCKET);[^\/]+\/([^ \/;()]+)/.exec(ua))) {
      term = match[1];
      data = dataset.get('willcom');
      updateCategory(result, data[dataset.KEY_CATEGORY]);
      updateOs(result, data[dataset.KEY_OS]);
      updateVersion(result, term);
      return true;
    }
  }
  if (ua.indexOf('SymbianOS') >= 0) {
    data = dataset.get('SymbianOS');
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_OS]);
    return true;
  }
  if (ua.indexOf('Google Wireless Transcoder') >= 0) {
    updateMap(result, dataset.get('MobileTranscoder'));
    updateVersion(result, 'Google');
    return true;
  }
  if (ua.indexOf('Naver Transcoder') >= 0) {
    updateMap(result, dataset.get('MobileTranscoder'));
    updateVersion(result, 'Naver');
    return true;
  }

  return false;
};

var challengeAppliance = exports.challengeAppliance = function(ua, result) {
  var data;
  if (ua.indexOf('Nintendo DSi;') >= 0) {
    data = dataset.get('NintendoDSi');
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_OS]);
    return true;
  }
  if (ua.indexOf('Nintendo Wii;') >= 0) {
    data = dataset.get('NintendoWii');
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_OS]);
    return true;
  }
  return false;
};

var challengeMisc = exports.challengeMisc = function(ua, result) {
  var data;
  if (ua.indexOf('(Win98;') >= 0) data = dataset.get('Win98');
  else if (ua.indexOf('Macintosh; U; PPC;') >= 0) data = dataset.get('MacOS');
  else if (ua.indexOf('Mac_PowerPC') >= 0) data = dataset.get('MacOS');
  else if (ua.indexOf('X11; FreeBSD ') >= 0) data = dataset.get('BSD');
  else if (ua.indexOf('X11; CrOS ') >= 0) data = dataset.get('ChromeOS');

  if (data) {
    updateCategory(result, data[dataset.KEY_CATEGORY]);
    updateOs(result, data[dataset.KEY_NAME]);
    return true;
  }

  return false;
};
<|endoftext|>


<commit_before>'use strict'

// Setup
const pgsql = require('pg')
const util = require('util')
const Event = require('events').EventEmitter
let app, config, pool

// Exports
module.exports = function (thisApp) {
  app = thisApp
  config = app.config
  pool = new pgsql.Pool(config.secrets.pg)
  pool.on('error', (err) => config.logger.fatal(err))
  return PG
}

function PG () {
  var self = this
  return self
}

PG.new = (opts) => new PG(opts)

util.inherits(PG, Event)

/* INSTANCE METHODS */
PG.prototype.emitData = function (err, data, done) {
  var self = this
  if (err) return self.emit('error', err)
  self.emit('data', data)
  if (typeof done === 'function') done()
}

PG.prototype.query = function (query, params) {
  var self = this
  self.pool.connect(function (err, client, done) {
    if (err) return self.emit('error', err)
    params
      ? client.query(query, params, self.emitData.bind(self))
      : client.query(query, self.emitData.bind(self))
  })
}

PG.prototype.sp = function (name, params) {
  var self = this
  params = params || ''
  self.pool.connect(function (err, client, done) {
    if (err) return self.emit('error', err)
    if (Array.isArray(params) && params.length > 0) {
      var paramHolders = params.map(function (p, i) { return '$' + (i + 1) })
      var paramStr = '(' + paramHolders.join(', ') + ');'
      client.query(
        'SELECT * FROM ' + name + paramStr,
        params,
        self.emitData.bind(self)
      )
      return
    }
    return client.query(
      'SELECT * FROM ' + name + paramStr,
      self.emitData.bind(self)
    )
  })
}
<commit_msg>Address pool correctly<commit_after>'use strict'

// Setup
const pgsql = require('pg')
const util = require('util')
const Event = require('events').EventEmitter
let app, config, pool

// Exports
module.exports = function (thisApp) {
  app = thisApp
  config = app.config
  pool = new pgsql.Pool(config.secrets.pg)
  pool.on('error', (err) => config.logger.fatal(err))
  return PG
}

function PG () {
  var self = this
  return self
}

PG.new = (opts) => new PG(opts)

util.inherits(PG, Event)

/* INSTANCE METHODS */
PG.prototype.emitData = function (err, data, done) {
  var self = this
  if (err) return self.emit('error', err)
  self.emit('data', data)
  if (typeof done === 'function') done()
}

PG.prototype.query = function (query, params) {
  var self = this
  pool.connect(function (err, client, done) {
    if (err) return self.emit('error', err)
    params
      ? client.query(query, params, self.emitData.bind(self))
      : client.query(query, self.emitData.bind(self))
  })
}

PG.prototype.sp = function (name, params) {
  var self = this
  params = params || ''
  pool.connect(function (err, client, done) {
    if (err) return self.emit('error', err)
    if (Array.isArray(params) && params.length > 0) {
      var paramHolders = params.map(function (p, i) { return '$' + (i + 1) })
      var paramStr = '(' + paramHolders.join(', ') + ');'
      client.query(
        'SELECT * FROM ' + name + paramStr,
        params,
        self.emitData.bind(self)
      )
      return
    }
    return client.query(
      'SELECT * FROM ' + name + paramStr,
      self.emitData.bind(self)
    )
  })
}
<|endoftext|>


<commit_before>'use strict';

var Bluebird = require('./bluebird-fresh.js'),
    printRejectionReason = require('./bluebird-captured-trace-fresh.js').possiblyUnhandledRejection,
    _ = require('lodash'),
    chalk = require('chalk');

// Load Request freshly - so that users can require an unaltered request instance!
var request = (function () {

    function clearCache() {
        _(require.cache).keys().forEach(function (key) {
            delete require.cache[key];
        });
    }

    var temp = _.assign({}, require.cache);
    clearCache();

    var freshRequest = require('request');

    clearCache();
    _.assign(require.cache, temp);

    return freshRequest;

})();

function RP$callback(err, httpResponse, body) {

    /* jshint validthis:true */
    var self = this;

    var origCallbackThrewException = false, thrownException;

    if (_.isFunction(self._rp_callbackOrig)) {
        try {
            self._rp_callbackOrig.apply(self, arguments);
        } catch (e) {
            origCallbackThrewException = true;
            thrownException = e;
        }
    }

    if (err) {
        self._rp_reject({
            error: err,
            options: self._rp_options,
            response: httpResponse
        });
    } else if (self._rp_options.simple && !(/^2/.test('' + httpResponse.statusCode))) {
        self._rp_reject({
            error: body,
            options: self._rp_options,
            response: httpResponse,
            statusCode: httpResponse.statusCode
        });
    } else {
        if (_.isFunction(self._rp_options.transform)) {
            try {
                self._rp_resolve(self._rp_options.transform(body, httpResponse));
            } catch (e) {
                self._rp_reject(e);
            }
        } else if (self._rp_options.resolveWithFullResponse) {
            self._rp_resolve(httpResponse);
        } else {
            self._rp_resolve(body);
        }
    }

    if (origCallbackThrewException) {
        throw thrownException;
    }

    // Mimic original behavior of errors emitted by request with no error listener registered
    if (err && _.isFunction(self._rp_callbackOrig) === false && self._rp_promise_in_use !== true && self.listeners('error').length === 1) {
        throw err;
    }

}

var originalInit = request.Request.prototype.init;

request.Request.prototype.init = function RP$initInterceptor(options) {

    var self = this;

    // Init may be called again - currently in case of redirects
    if (_.isPlainObject(options) && self._callback === undefined && self._rp_promise === undefined) {

        self._rp_promise = new Bluebird(function (resolve, reject) {
            self._rp_resolve = resolve;
            self._rp_reject = reject;
        });
        self._rp_promise._rp_in_use = false;

        self._rp_callbackOrig = self.callback;
        self.callback = RP$callback;

        if (_.isString(options.method)) {
            options.method = options.method.toUpperCase();
        }

        self._rp_options = options;
        self._rp_options.simple = options.simple === false ? false : true;
        self._rp_options.resolveWithFullResponse = options.resolveWithFullResponse === true ? true : false;

    }

    return originalInit.apply(self, arguments);

};

function markPromiseInUse(requestInstance) {
    requestInstance._rp_promise_in_use = true;
    requestInstance._rp_promise._rp_in_use = true;
}

function expose(methodToExpose, exposeAs) {

    exposeAs = exposeAs || methodToExpose;

    /* istanbul ignore if */
    if (!_.isUndefined(request.Request.prototype[exposeAs])) {
        console.error(chalk.bold.bgRed('[Request-Promise] Unable to expose method "' + exposeAs + '". It is already implemented by Request.'));
        return;
    }

    request.Request.prototype[exposeAs] = function RP$exposed() {
        markPromiseInUse(this);
        return this._rp_promise[methodToExpose].apply(this._rp_promise, arguments);
    };

}

_.forEach([
        ['then'],
        ['catch'],
        ['caught'],
        ['finally'],
        ['lastly']
    ],
    function (args) {
        expose.apply(undefined, args);
    }
);

request.Request.prototype.promise = function RP$promise() {
    markPromiseInUse(this);
    return this._rp_promise;
};

Bluebird.onPossiblyUnhandledRejection(function (reason, promise) {
    // For whatever reason we don't see _rp_in_use here at all after then is called. --> We compare to false instead of true.
    if (promise._rp_in_use !== false) {
        printRejectionReason(reason);
    }
    // else: The user did not call .then(...)
    // --> We need to assume that this request is processed with a callback or a pipe etc.
});

module.exports = request;
<commit_msg>Renamed local variable<commit_after>'use strict';

var Bluebird = require('./bluebird-fresh.js'),
    printRejectionReason = require('./bluebird-captured-trace-fresh.js').possiblyUnhandledRejection,
    _ = require('lodash'),
    chalk = require('chalk');

// Load Request freshly - so that users can require an unaltered request instance!
var request = (function () {

    function clearCache() {
        _(require.cache).keys().forEach(function (key) {
            delete require.cache[key];
        });
    }

    var temp = _.assign({}, require.cache);
    clearCache();

    var freshRequest = require('request');

    clearCache();
    _.assign(require.cache, temp);

    return freshRequest;

})();

function RP$callback(err, response, body) {

    /* jshint validthis:true */
    var self = this;

    var origCallbackThrewException = false, thrownException;

    if (_.isFunction(self._rp_callbackOrig)) {
        try {
            self._rp_callbackOrig.apply(self, arguments);
        } catch (e) {
            origCallbackThrewException = true;
            thrownException = e;
        }
    }

    if (err) {
        self._rp_reject({
            error: err,
            options: self._rp_options,
            response: response
        });
    } else if (self._rp_options.simple && !(/^2/.test('' + response.statusCode))) {
        self._rp_reject({
            error: body,
            options: self._rp_options,
            response: response,
            statusCode: response.statusCode
        });
    } else {
        if (_.isFunction(self._rp_options.transform)) {
            try {
                self._rp_resolve(self._rp_options.transform(body, response));
            } catch (e) {
                self._rp_reject(e);
            }
        } else if (self._rp_options.resolveWithFullResponse) {
            self._rp_resolve(response);
        } else {
            self._rp_resolve(body);
        }
    }

    if (origCallbackThrewException) {
        throw thrownException;
    }

    // Mimic original behavior of errors emitted by request with no error listener registered
    if (err && _.isFunction(self._rp_callbackOrig) === false && self._rp_promise_in_use !== true && self.listeners('error').length === 1) {
        throw err;
    }

}

var originalInit = request.Request.prototype.init;

request.Request.prototype.init = function RP$initInterceptor(options) {

    var self = this;

    // Init may be called again - currently in case of redirects
    if (_.isPlainObject(options) && self._callback === undefined && self._rp_promise === undefined) {

        self._rp_promise = new Bluebird(function (resolve, reject) {
            self._rp_resolve = resolve;
            self._rp_reject = reject;
        });
        self._rp_promise._rp_in_use = false;

        self._rp_callbackOrig = self.callback;
        self.callback = RP$callback;

        if (_.isString(options.method)) {
            options.method = options.method.toUpperCase();
        }

        self._rp_options = options;
        self._rp_options.simple = options.simple === false ? false : true;
        self._rp_options.resolveWithFullResponse = options.resolveWithFullResponse === true ? true : false;

    }

    return originalInit.apply(self, arguments);

};

function markPromiseInUse(requestInstance) {
    requestInstance._rp_promise_in_use = true;
    requestInstance._rp_promise._rp_in_use = true;
}

function expose(methodToExpose, exposeAs) {

    exposeAs = exposeAs || methodToExpose;

    /* istanbul ignore if */
    if (!_.isUndefined(request.Request.prototype[exposeAs])) {
        console.error(chalk.bold.bgRed('[Request-Promise] Unable to expose method "' + exposeAs + '". It is already implemented by Request.'));
        return;
    }

    request.Request.prototype[exposeAs] = function RP$exposed() {
        markPromiseInUse(this);
        return this._rp_promise[methodToExpose].apply(this._rp_promise, arguments);
    };

}

_.forEach([
        ['then'],
        ['catch'],
        ['caught'],
        ['finally'],
        ['lastly']
    ],
    function (args) {
        expose.apply(undefined, args);
    }
);

request.Request.prototype.promise = function RP$promise() {
    markPromiseInUse(this);
    return this._rp_promise;
};

Bluebird.onPossiblyUnhandledRejection(function (reason, promise) {
    // For whatever reason we don't see _rp_in_use here at all after then is called. --> We compare to false instead of true.
    if (promise._rp_in_use !== false) {
        printRejectionReason(reason);
    }
    // else: The user did not call .then(...)
    // --> We need to assume that this request is processed with a callback or a pipe etc.
});

module.exports = request;
<|endoftext|>


<commit_before>var _ = require('underscore');
var carto = require('carto');
var chrono = require('chrono');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var crypto = require('crypto');
var TileJSON = require('tilejson');
var Litenik = require('dt');
var sm = new (require('sphericalmercator'));
var tm = {};
var srs900913 = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over';

// Override _prepareURL to add in mod16 prefix token support.
TileJSON.prototype._prepareURL = function(url, z, x, y) {
    return url
        .replace(/\{prefix\}/g, (x%16).toString(16) + (y%16).toString(16))
        .replace(/\{z\}/g, z)
        .replace(/\{x\}/g, x)
        .replace(/\{y\}/g, (this.data.scheme === 'tms') ? (1 << z) - 1 - y : y);
};

var defaults = {
    sources:[],
    styles:{},
    name:'',
    mtime:+new Date,
    center:[0,0,3],
    minzoom:0,
    maxzoom:22,
    _prefs: {
        saveCenter: true
    }
};

module.exports = tm;

tm.cacheProject = {};
tm.cacheBackend = {};

// Set or get config.
tm.db;
tm._config = {};
tm.config = function(opts) {
    if (!opts) return tm._config;

    tm._config = _(opts).defaults(tm._config);
    // @TODO create other paths (cache, etc.)
    try {
        mkdirp.sync(path.dirname(tm.config().db));
    } catch(err) { throw err; }

    // Load + compact the app database.
    var old = require('dirty')(tm.config().db);
    old.on('load', function() {
        fs.unlinkSync(tm.config().db);
        tm.db = require('dirty')(tm.config().db);
        old.forEach(function(k,v) { tm.db.set(k,v); });
    });

    return tm._config;
};
tm.config({
    db: path.join(process.env.HOME, '.tilemill', 'v2', 'app.db')
});

// Set or remove a project id from recent history.
tm.history = function(id, invalidate) {
    if (!id) return tm.db.get('history') || [];

    var history = tm.db.get('history')||[];
    history = invalidate
        ? _(history).reject(function(k) { return k === id; })
        : _(history.concat([id])).uniq();
    if (!_(history).isEqual(tm.db.get('history'))) tm.db.set('history', history);

    return history;
};

// @TODO.
tm.sources = _(fs.readdirSync(__dirname + '/../sources')).reduce(function(memo, file) {
    if (file.charAt(0) === '.') return memo;
    memo[file.split('.')[0]] = JSON.parse(fs.readFileSync(__dirname + '/../sources/' + file, 'utf8'));
    memo[file.split('.')[0]].id = file.split('.')[0];
    return memo;
}, {});

tm.templates = _(fs.readdirSync(__dirname + '/../templates')).reduce(function(memo, file) {
    if (file.charAt(0) === '.') return memo;
    memo[file.split('.')[0]] = _(fs.readFileSync(__dirname + '/../templates/' + file, 'utf8')).template();
    return memo;
}, {});

// Generate or verify that an id is a temporary one.
tm.tmpid = function(id) {
    if (id) return /tmp-[0-9a-f]{8}/.test(id);

    id = 'tmp-';
    var base16 = '0123456789abcdef';
    for (var i = 0; i < 8; i++) id += base16[Math.random() * 16 | 0];
    return id;
};

tm.toXML = function(data, callback) {
    // Convert datatiles sources to mml layer IDs.
    var sources = _(data.sources).chain()
        .filter(function(source) { return tm.sources[source] })
        .map(function(source) { return _(tm.sources[source].layers).keys() })
        .compact()
        .flatten()
        .value();
    // These empty style declarations ensure layers are declared in Carto's
    // MML output and match up with the layer indices in the datatiles.
    var styles = [ {
        data: tm.templates.stylesdef(sources)
    } ].concat(_(data.styles).map(function(style,basename) { return {
        id: basename,
        data: style
    }; }));
    var layers =  sources.map(function(id) { return { name:id, srs:srs900913 } });

    new carto.Renderer().render({
        srs: srs900913,
        Layer: layers,
        Stylesheet: styles
    }, callback);
};

tm.project = function(options, callback) {
    var id = options.id;
    var data = options.data;
    var perm = options.perm;

    if (!data && tm.cacheProject[id]) return callback(null, tm.cacheProject[id]);

    // Load for reads/writes.
    var load = function(data, xml) {
        var opts = {};
        if (!tm.tmpid(id)) opts.base = id;
        opts.xml = xml;
        opts.backend = _(data.sources).map(function(sid) {
            tm.cacheBackend[sid] = tm.cacheBackend[sid] || new TileJSON(__dirname + '/../sources/'+sid+'.json', function() {});
            return tm.cacheBackend[sid];
        });
        if (tm.cacheProject[id]) {
            return tm.cacheProject[id].update(opts, function() {
                data.id = id;
                tm.cacheProject[id].data = data;
                return tm.project(_(options).extend({data:null}), callback);
            });
        } else {
            new Litenik(opts, function(err, project) {
                if (err) return callback(err);
                data.id = id;
                tm.cacheProject[id] = project;
                tm.cacheProject[id].data = data;
                return tm.project(_(options).extend({data:null}), callback);
            });
        }
    };

    // Reading.
    if (!data) return tm.projectInfo(id, function(err, data) {
        if (err) return callback(err);
        var stylesheets = {};
        var readstyles = function() {
            if (!data.styles || !data.styles.length) {
                data.styles = stylesheets;
                return tm.toXML(data, function(err, xml) {
                    if (err) return callback(err);
                    return load(data, xml);
                });
            }
            var basename = data.styles.shift();
            fs.readFile(path.join(id, basename), 'utf8', function(err, mss) {
                if (err && err.code !== 'ENOENT') return callback(err);
                if (mss) stylesheets[basename] = mss;
                readstyles();
            });
        };
        readstyles();
    });

    // Writing.
    data = _(data).defaults(defaults);
    tm.toXML(data, function(err, xml) {
        if (err) return callback(err);
        data.mtime = +new Date;
        if (!perm) return load(data, xml);

        var files = _(data.styles).map(function(v,k) { return { basename:k, data:v }; });
        files.push({
            basename: 'project.json',
            data: JSON.stringify(_(data).reduce(function(memo,v,k) {
                if (!(k in defaults)) return memo;
                memo[k] = k === 'styles' ? _(v).keys() : v;
                return memo;
            }, {}), null, 2)
        });
        var writefiles = function() {
            if (!files.length) return load(data, xml);
            var file = files.shift();
            fs.writeFile(path.join(id, file.basename), file.data, function(err) {
                if (err) return callback(err);
                writefiles();
            });
        };
        mkdirp(id, function(err) {
            if (err) return callback(err);
            writefiles();
            tm.projectThumb({id:id, perm:true});
        });
    });
};

// Light read of project info.
tm.projectInfo = function(id, callback) {
    return fs.readFile(path.join(id,'project.json'), 'utf8', function(err, data) {
        if (err) return callback(err);
        try { data = JSON.parse(data); }
        catch(err) { return callback(err); }
        data._id = id;
        return callback(null, _(data).defaults(defaults));
    });
};

// Read the project thumb.
tm.projectThumb = function(opts, callback) {
    callback = callback || function() {};

    if (!opts.perm) return fs.readFile(path.join(opts.id,'.thumb.png'), function(err, buffer) {
        if (!err && buffer) return callback(null, buffer);
        if (err && err.code !== 'ENOENT') return callback(err);
        tm.projectThumb({id:opts.id, perm:true}, callback);
    });

    return tm.project({id:opts.id}, function(err, source) {
        if (err) return callback(err);
        var center = source.data.center;
        var xyz = sm.xyz([center[0],center[1],center[0],center[1]], center[2], false);
        source.getTile(center[2],xyz.minX,xyz.minY, function(err, buffer) {
            if (err) return callback(err);
            callback(null, buffer);
            // Save the thumb to disk.
            fs.writeFile(path.join(opts.id,'.thumb.png'), buffer, function(err) {
                if (err) console.error(err);
            });
        });
    });
};

<commit_msg>Implement MBTiles caching datasource.<commit_after>var _ = require('underscore');
var carto = require('carto');
var chrono = require('chrono');
var fs = require('fs');
var path = require('path');
var util = require('util');
var mkdirp = require('mkdirp');
var crypto = require('crypto');
var MBTiles = require('mbtiles');
var TileJSON = require('tilejson');
var Litenik = require('dt');
var sm = new (require('sphericalmercator'));
var tm = {};
var srs900913 = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over';

// Override _prepareURL to add in mod16 prefix token support.
TileJSON.prototype._prepareURL = function(url, z, x, y) {
    return url
        .replace(/\{prefix\}/g, (x%16).toString(16) + (y%16).toString(16))
        .replace(/\{z\}/g, z)
        .replace(/\{x\}/g, x)
        .replace(/\{y\}/g, (this.data.scheme === 'tms') ? (1 << z) - 1 - y : y);
};

// Caching source.
function CachingSource(uri, callback) {
    return TileJSON.call(this, uri, function(err, source) {
        if (err) return callback(err);
        var hash = crypto.createHash('md5')
            .update(JSON.stringify(source.data))
            .digest('hex')
            .substr(0,16);
        var cachepath = path.join(tm.config().cache, hash + '.mbtiles?batch=16');
        new MBTiles(cachepath, function(err, mbtiles) {
            if (err) return callback(err);
            source._mbtiles = mbtiles;
            source._mbtiles.startWriting(function(err) {
                if (err) return callback(err);
                return callback(null, source);
            });
        });
    });
};
util.inherits(CachingSource, TileJSON);
CachingSource.prototype.getTile = function(z,x,y,callback) {
    var source = this;
    this._mbtiles.getTile(z,x,y,function(err, data, headers) {
        if (!err) return callback(err, data, headers);
        TileJSON.prototype.getTile.call(source,z,x,y,function(err, data, headers) {
            callback(err, data, headers);
            if (!err && data) source._mbtiles.putTile(z,x,y,data,function(){});
        });
    });
};

var defaults = {
    sources:[],
    styles:{},
    name:'',
    mtime:+new Date,
    center:[0,0,3],
    minzoom:0,
    maxzoom:22,
    _prefs: {
        saveCenter: true
    }
};

module.exports = tm;

tm.cacheProject = {};
tm.cacheBackend = {};

// Set or get config.
tm.db;
tm._config = {};
tm.config = function(opts) {
    if (!opts) return tm._config;

    tm._config = _(opts).defaults(tm._config);
    // @TODO create other paths (cache, etc.)
    try {
        mkdirp.sync(path.dirname(tm.config().db));
        mkdirp.sync(tm.config().cache);
    } catch(err) { throw err; }

    // Load + compact the app database.
    var old = require('dirty')(tm.config().db);
    old.on('load', function() {
        fs.unlinkSync(tm.config().db);
        tm.db = require('dirty')(tm.config().db);
        old.forEach(function(k,v) { tm.db.set(k,v); });
    });

    return tm._config;
};
tm.config({
    db: path.join(process.env.HOME, '.tilemill', 'v2', 'app.db'),
    cache: path.join(process.env.HOME, '.tilemill', 'v2', 'cache')
});

// Set or remove a project id from recent history.
tm.history = function(id, invalidate) {
    if (!id) return tm.db.get('history') || [];

    var history = tm.db.get('history')||[];
    history = invalidate
        ? _(history).reject(function(k) { return k === id; })
        : _(history.concat([id])).uniq();
    if (!_(history).isEqual(tm.db.get('history'))) tm.db.set('history', history);

    return history;
};

// @TODO.
tm.sources = _(fs.readdirSync(__dirname + '/../sources')).reduce(function(memo, file) {
    if (file.charAt(0) === '.') return memo;
    memo[file.split('.')[0]] = JSON.parse(fs.readFileSync(__dirname + '/../sources/' + file, 'utf8'));
    memo[file.split('.')[0]].id = file.split('.')[0];
    return memo;
}, {});

tm.templates = _(fs.readdirSync(__dirname + '/../templates')).reduce(function(memo, file) {
    if (file.charAt(0) === '.') return memo;
    memo[file.split('.')[0]] = _(fs.readFileSync(__dirname + '/../templates/' + file, 'utf8')).template();
    return memo;
}, {});

// Generate or verify that an id is a temporary one.
tm.tmpid = function(id) {
    if (id) return /tmp-[0-9a-f]{8}/.test(id);

    id = 'tmp-';
    var base16 = '0123456789abcdef';
    for (var i = 0; i < 8; i++) id += base16[Math.random() * 16 | 0];
    return id;
};

tm.toXML = function(data, callback) {
    // Convert datatiles sources to mml layer IDs.
    var sources = _(data.sources).chain()
        .filter(function(source) { return tm.sources[source] })
        .map(function(source) { return _(tm.sources[source].layers).keys() })
        .compact()
        .flatten()
        .value();
    // These empty style declarations ensure layers are declared in Carto's
    // MML output and match up with the layer indices in the datatiles.
    var styles = [ {
        data: tm.templates.stylesdef(sources)
    } ].concat(_(data.styles).map(function(style,basename) { return {
        id: basename,
        data: style
    }; }));
    var layers =  sources.map(function(id) { return { name:id, srs:srs900913 } });

    new carto.Renderer().render({
        srs: srs900913,
        Layer: layers,
        Stylesheet: styles
    }, callback);
};

tm.project = function(options, callback) {
    var id = options.id;
    var data = options.data;
    var perm = options.perm;

    if (!data && tm.cacheProject[id]) return callback(null, tm.cacheProject[id]);

    // Load for reads/writes.
    var load = function(data, xml) {
        var opts = {};
        if (!tm.tmpid(id)) opts.base = id;
        opts.xml = xml;
        opts.backend = _(data.sources).map(function(sid) {
            tm.cacheBackend[sid] = tm.cacheBackend[sid] || new CachingSource(__dirname + '/../sources/'+sid+'.json', function() {});
            return tm.cacheBackend[sid];
        });
        if (tm.cacheProject[id]) {
            return tm.cacheProject[id].update(opts, function() {
                data.id = id;
                tm.cacheProject[id].data = data;
                return tm.project(_(options).extend({data:null}), callback);
            });
        } else {
            new Litenik(opts, function(err, project) {
                if (err) return callback(err);
                data.id = id;
                tm.cacheProject[id] = project;
                tm.cacheProject[id].data = data;
                return tm.project(_(options).extend({data:null}), callback);
            });
        }
    };

    // Reading.
    if (!data) return tm.projectInfo(id, function(err, data) {
        if (err) return callback(err);
        var stylesheets = {};
        var readstyles = function() {
            if (!data.styles || !data.styles.length) {
                data.styles = stylesheets;
                return tm.toXML(data, function(err, xml) {
                    if (err) return callback(err);
                    return load(data, xml);
                });
            }
            var basename = data.styles.shift();
            fs.readFile(path.join(id, basename), 'utf8', function(err, mss) {
                if (err && err.code !== 'ENOENT') return callback(err);
                if (mss) stylesheets[basename] = mss;
                readstyles();
            });
        };
        readstyles();
    });

    // Writing.
    data = _(data).defaults(defaults);
    tm.toXML(data, function(err, xml) {
        if (err) return callback(err);
        data.mtime = +new Date;
        if (!perm) return load(data, xml);

        var files = _(data.styles).map(function(v,k) { return { basename:k, data:v }; });
        files.push({
            basename: 'project.json',
            data: JSON.stringify(_(data).reduce(function(memo,v,k) {
                if (!(k in defaults)) return memo;
                memo[k] = k === 'styles' ? _(v).keys() : v;
                return memo;
            }, {}), null, 2)
        });
        var writefiles = function() {
            if (!files.length) return load(data, xml);
            var file = files.shift();
            fs.writeFile(path.join(id, file.basename), file.data, function(err) {
                if (err) return callback(err);
                writefiles();
            });
        };
        mkdirp(id, function(err) {
            if (err) return callback(err);
            writefiles();
            tm.projectThumb({id:id, perm:true});
        });
    });
};

// Light read of project info.
tm.projectInfo = function(id, callback) {
    return fs.readFile(path.join(id,'project.json'), 'utf8', function(err, data) {
        if (err) return callback(err);
        try { data = JSON.parse(data); }
        catch(err) { return callback(err); }
        data._id = id;
        return callback(null, _(data).defaults(defaults));
    });
};

// Read the project thumb.
tm.projectThumb = function(opts, callback) {
    callback = callback || function() {};

    if (!opts.perm) return fs.readFile(path.join(opts.id,'.thumb.png'), function(err, buffer) {
        if (!err && buffer) return callback(null, buffer);
        if (err && err.code !== 'ENOENT') return callback(err);
        tm.projectThumb({id:opts.id, perm:true}, callback);
    });

    return tm.project({id:opts.id}, function(err, source) {
        if (err) return callback(err);
        var center = source.data.center;
        var xyz = sm.xyz([center[0],center[1],center[0],center[1]], center[2], false);
        source.getTile(center[2],xyz.minX,xyz.minY, function(err, buffer) {
            if (err) return callback(err);
            callback(null, buffer);
            // Save the thumb to disk.
            fs.writeFile(path.join(opts.id,'.thumb.png'), buffer, function(err) {
                if (err) console.error(err);
            });
        });
    });
};

<|endoftext|>


<commit_before>/* eslint-env browser */
import React, { Component } from 'react';
import QuestionDetail from '../parts/QuestionDetail';
import * as CommonQuestionParts from '../parts/CommonQuestionParts';
import { AgeRow, BirthYearRow, ContactEasyTimeRow, ContactMeansRow, EmailRow, FaxRow, FuriganaRow, HomeTelRow, HospitalNameRow, HospitalPrefectureRow, InterviewPlaceRow, InterviewMeansRow, InterviewRow, MobileTelRow, NameRow, PositionRow, ProfessionalAreaRow, RequestEtcRow, ScheduleRow, SexRow, SpecialityRow, WorkPostalCodeRow, WorkTelRow } from './PersonalInfoQuestion/Rows';

/** 設問：個人情報 */
export default class PersonalInfoQuestion extends Component {
  generateRow(survey, question, item) {
    switch (item.getRowType()) {
      case 'AgeRow':
        return <AgeRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'BirthYearRow':
        return <BirthYearRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'ContactEasyTimeRow':
        return <ContactEasyTimeRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'ContactMeansRow':
        return <ContactMeansRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'EmailRow':
        return <EmailRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'FaxRow':
        return <FaxRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'FuriganaRow':
        return <FuriganaRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'HomeTelRow':
        return <HomeTelRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'HospitalNameRow':
        return <HospitalNameRow key={item.getId()} survey={survey} item={item} question={question} />;
      case 'InterviewPlaceRow':
        return <InterviewPlaceRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'InterviewMeansRow':
        return <InterviewMeansRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'InterviewRow':
        const homeTelInInterview = question.getItems().filter(i => i.isHomeTelRow()).get(0);
        const mobileTelInInterview = question.getItems().filter(i => i.isMobileTelRow()).get(0);
        const workTelInInterview = question.getItems().filter(i => i.isWorkTelRow()).get(0);
        return (<InterviewRow
          key={item.getId()}
          survey={survey}
          question={question}
          item={item}
          homeTel={homeTelInInterview}
          mobileTel={mobileTelInInterview}
          workTel={workTelInInterview}
        />);
      case 'MobileTelRow':
        return <MobileTelRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'HospitalPrefectureRow':
        return <HospitalPrefectureRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'NameRow':
        return <NameRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'PositionRow':
        return <PositionRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'ProfessionalAreaRow':
        return <ProfessionalAreaRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'RequestEtcRow':
        return <RequestEtcRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'ScheduleRow':
        const homeTelInSchedule = question.getItems().filter(i => i.isHomeTelRow()).get(0);
        const mobileTelInSchedule = question.getItems().filter(i => i.isMobileTelRow()).get(0);
        const workTelInSchedule = question.getItems().filter(i => i.isWorkTelRow()).get(0);
        const emailInSchedule = question.getItems().filter(i => i.isEmailRow()).get(0);
        return (<ScheduleRow
          key={item.getId()}
          survey={survey}
          question={question}
          item={item}
          homeTel={homeTelInSchedule}
          mobileTel={mobileTelInSchedule}
          workTel={workTelInSchedule}
          email={emailInSchedule}
        />);
      case 'SexRow':
        return <SexRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'SpecialityRow':
        return <SpecialityRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'WorkPostalCodeRow':
        return <WorkPostalCodeRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'WorkTelRow':
        return <WorkTelRow key={item.getId()} survey={survey} question={question} item={item} />;
      default:
        throw new Error(`NotImplementedError: ${item.getRowType()}`);
    }
  }

  render() {
    const { replacer, survey, question, options } = this.props;

    return (

        { CommonQuestionParts.title(question, replacer) }
        { CommonQuestionParts.description(question, replacer) }

              {question.getItems().map(item => this.generateRow(survey, question, item))}

        { options.isShowDetail() ? <QuestionDetail {...this.props} /> : null }

    );
  }
}
<commit_msg>Fix to use namespace for Row.js<commit_after>/* eslint-env browser */
import React, { Component } from 'react';
import QuestionDetail from '../parts/QuestionDetail';
import * as CommonQuestionParts from '../parts/CommonQuestionParts';
import * as Rows from './PersonalInfoQuestion/Rows';

/** 設問：個人情報 */
export default class PersonalInfoQuestion extends Component {
  generateRow(survey, question, item) {
    switch (item.getRowType()) {
      case 'AgeRow':
        return <Rows.AgeRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'BirthYearRow':
        return <Rows.BirthYearRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'ContactEasyTimeRow':
        return <Rows.ContactEasyTimeRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'ContactMeansRow':
        return <Rows.ContactMeansRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'EmailRow':
        return <Rows.EmailRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'FaxRow':
        return <Rows.FaxRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'FuriganaRow':
        return <Rows.FuriganaRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'HomeTelRow':
        return <Rows.HomeTelRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'HospitalNameRow':
        return <Rows.HospitalNameRow key={item.getId()} survey={survey} item={item} question={question} />;
      case 'InterviewPlaceRow':
        return <Rows.InterviewPlaceRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'InterviewMeansRow':
        return <Rows.InterviewMeansRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'InterviewRow':
        const homeTelInInterview = question.getItems().filter(i => i.isHomeTelRow()).get(0);
        const mobileTelInInterview = question.getItems().filter(i => i.isMobileTelRow()).get(0);
        const workTelInInterview = question.getItems().filter(i => i.isWorkTelRow()).get(0);
        return (<Rows.InterviewRow
          key={item.getId()}
          survey={survey}
          question={question}
          item={item}
          homeTel={homeTelInInterview}
          mobileTel={mobileTelInInterview}
          workTel={workTelInInterview}
        />);
      case 'MobileTelRow':
        return <Rows.MobileTelRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'HospitalPrefectureRow':
        return <Rows.HospitalPrefectureRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'NameRow':
        return <Rows.NameRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'PositionRow':
        return <Rows.PositionRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'ProfessionalAreaRow':
        return <Rows.ProfessionalAreaRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'RequestEtcRow':
        return <Rows.RequestEtcRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'ScheduleRow':
        const homeTelInSchedule = question.getItems().filter(i => i.isHomeTelRow()).get(0);
        const mobileTelInSchedule = question.getItems().filter(i => i.isMobileTelRow()).get(0);
        const workTelInSchedule = question.getItems().filter(i => i.isWorkTelRow()).get(0);
        const emailInSchedule = question.getItems().filter(i => i.isEmailRow()).get(0);
        return (<Rows.ScheduleRow
          key={item.getId()}
          survey={survey}
          question={question}
          item={item}
          homeTel={homeTelInSchedule}
          mobileTel={mobileTelInSchedule}
          workTel={workTelInSchedule}
          email={emailInSchedule}
        />);
      case 'SexRow':
        return <Rows.SexRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'SpecialityRow':
        return <Rows.SpecialityRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'WorkPostalCodeRow':
        return <Rows.WorkPostalCodeRow key={item.getId()} survey={survey} question={question} item={item} />;
      case 'WorkTelRow':
        return <Rows.WorkTelRow key={item.getId()} survey={survey} question={question} item={item} />;
      default:
        throw new Error(`NotImplementedError: ${item.getRowType()}`);
    }
  }

  render() {
    const { replacer, survey, question, options } = this.props;

    return (

        { CommonQuestionParts.title(question, replacer) }
        { CommonQuestionParts.description(question, replacer) }

              {question.getItems().map(item => this.generateRow(survey, question, item))}

        { options.isShowDetail() ? <QuestionDetail {...this.props} /> : null }

    );
  }
}
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('dpDataSelection')
        .constant('DATA_SELECTION_CONFIG', {
            options: {
                MAX_NUMBER_OF_CLUSTERED_MARKERS: 10000
            },
            datasets: {
                bag: {
                    CUSTOM_API: 'dataSelectionApiDataSelection',
                    MAX_AVAILABLE_PAGES: 100,
                    ENDPOINT_PREVIEW: 'dataselectie/bag/',
                    ENDPOINT_MARKERS: 'dataselectie/bag/geolocation/',
                    ENDPOINT_EXPORT: 'dataselectie/bag/export/',
                    ENDPOINT_DETAIL: 'bag/nummeraanduiding/',
                    PRIMARY_KEY: 'id',
                    TITLE: 'Adressen',
                    FILTERS: [
                        {
                            slug: 'stadsdeel_naam',
                            label: 'Stadsdeel'
                        }, {
                            slug: 'ggw_naam',
                            label: 'GGW-gebied'
                        }, {
                            slug: 'buurtcombinatie_naam',
                            label: 'Buurtcombinatie'
                        }, {
                            slug: 'buurt_naam',
                            label: 'Buurt'
                        }, {
                            slug: 'naam',
                            label: 'Openbare ruimte'
                        }, {
                            slug: 'postcode',
                            label: 'Postcode'
                        }
                    ],
                    CONTENT: {
                        TABLE: [
                            {
                                label: 'Naam openbare ruimte',
                                variables: ['_openbare_ruimte_naam']
                            },
                            {
                                label: 'Num.',
                                variables: ['huisnummer']
                            },
                            {
                                label: 'Let.',
                                variables: ['huisletter']
                            },
                            {
                                label: 'Toev.',
                                variables: ['huisnummer_toevoeging']
                            },
                            {
                                label: 'Postcode',
                                variables: ['postcode']
                            },
                            {
                                label: 'Stadsdeel',
                                variables: ['stadsdeel_naam']
                            },
                            {
                                label: '-code',
                                variables: ['stadsdeel_code']
                            },
                            {
                                label: 'GGW-gebied',
                                variables: ['ggw_naam']
                            },
                            {
                                label: '-code',
                                variables: ['ggw_code']
                            },
                            {
                                label: 'Buurtcombinatie',
                                variables: ['buurtcombinatie_naam']
                            },
                            {
                                label: '-code',
                                variables: ['buurtcombinatie_code']
                            },
                            {
                                label: 'Buurt',
                                variables: ['buurt_naam']
                            },
                            {
                                label: '-code',
                                variables: ['buurt_code']
                            }
                        ],
                        LIST: [
                            {
                                variables: [
                                    '_openbare_ruimte_naam',
                                    'huisnummer',
                                    'huisletter',
                                    'huisnummer_toevoeging'
                                ],
                                formatter: 'bagAddress'
                            },
                            {
                                variables: [
                                    'ligplaats_id',
                                    'standplaats_id'
                                ],
                                formatter: 'nummeraanduidingType'
                            },
                            {
                                variables: [
                                    'hoofdadres'
                                ],
                                formatter: 'nevenadres'
                            },
                            {
                                variables: [
                                    'status_id'
                                ],
                                formatter: 'verblijfsobjectGevormd'
                            }
                        ]
                    }
                },
                catalogus: {
                    MAX_ITEMS_PER_PAGE: 100,
                    CUSTOM_API: 'dataSelectionApiCkan',
                    ENDPOINT_PREVIEW: 'catalogus/api/3/action/package_search',
                    ENDPOINT_DETAIL: 'catalogus/api/3/action/package_show',
                    PRIMARY_KEY: 'id',
                    TITLE: 'Catalogus',
                    SHOW_FILTER_OPTION_COUNTS: false,
                    FILTERS: [
                        {
                            slug: 'groups',
                            label: 'Thema\'s'
                        }, {
                            slug: 'res_format',
                            label: 'Formaten',
                            formatter: 'lowercase'
                        }, {
                            slug: 'organization',
                            label: 'Gepubliceerd door'
                        }
                    ],
                    CONTENT: {
                        CARDS: [
                            {
                                label: 'Naam',
                                variables: ['title']
                            }, {
                                label: 'Datum',
                                variables: ['metadata_created', 'metadata_modified'],
                                formatter: 'modificationDate'
                            }, {
                                label: 'Formaten',
                                variables: ['resources.format'],
                                formatter: 'aggregate',
                                template: 'file-type'
                            }, {
                                label: 'Labels',
                                variables: ['tags.display_name'],
                                formatter: 'aggregate',
                                template: 'tags'
                            }, {
                                label: 'Omschrijving',
                                formatter: 'truncateHtmlAsText',
                                variables: ['notes']
                            }
                        ]
                    }
                },
                hr: {
                    CUSTOM_API: 'dataSelectionApiDataSelection',
                    MAX_AVAILABLE_PAGES: 100,
                    ENDPOINT_PREVIEW: 'dataselectie/hr/',
                    ENDPOINT_MARKERS: 'dataselectie/hr/geolocation/',
                    ENDPOINT_EXPORT: 'dataselectie/hr/export/',
                    ENDPOINT_DETAIL: 'handelsregister/vestiging/',
                    PRIMARY_KEY: 'id',
                    TITLE: 'Vestigingen',
                    FILTERS: [
                        {
                            slug: 'hoofdcategorie',
                            label: 'Hoofdcategorie'
                        }, {
                            slug: 'subcategorie',
                            label: 'Subcategorie'
                        }, {
                            slug: 'stadsdeel_naam',
                            label: 'Stadsdeel'
                        }, {
                            slug: 'ggw_naam',
                            label: 'GGW-gebied'
                        }, {
                            slug: 'buurtcombinatie_naam',
                            label: 'Buurtcombinatie'
                        }, {
                            slug: 'buurt_naam',
                            label: 'Buurt'
                        }, {
                            slug: 'openbare_ruimte',
                            label: 'Openbare ruimte'
                        }, {
                            slug: 'postcode',
                            label: 'Postcode'
                        }
                    ],
                    CONTENT: {
                        TABLE: [
                            {
                                label: 'KvK-num.',
                                variables: ['kvk_nummer']
                            },
                            {
                                label: 'Handelsnaam',
                                variables: ['handelsnaam']
                            },
                            {
                                label: 'Bezoekadres',
                                variables: ['bezoekadres_volledig_adres']
                            },
                            {
                                label: 'Hoofdcategorie',
                                variables: ['hoofdcategorie']
                            },
                            {
                                label: 'Subcategorie',
                                variables: ['subcategorie']
                            },
                            {
                                label: 'SBI-omschrijving',
                                variables: ['sbi_omschrijving']
                            },
                            {
                                label: 'SBI-code',
                                variables: ['sbi_code']
                            }
                        ],
                        LIST: [
                            {
                                variables: ['handelsnaam']
                            }
                        ]
                    }
                }
            }
        });
})();
<commit_msg>Naamwijziging id fields<commit_after>(function () {
    'use strict';

    angular
        .module('dpDataSelection')
        .constant('DATA_SELECTION_CONFIG', {
            options: {
                MAX_NUMBER_OF_CLUSTERED_MARKERS: 10000
            },
            datasets: {
                bag: {
                    CUSTOM_API: 'dataSelectionApiDataSelection',
                    MAX_AVAILABLE_PAGES: 100,
                    ENDPOINT_PREVIEW: 'dataselectie/bag/',
                    ENDPOINT_MARKERS: 'dataselectie/bag/geolocation/',
                    ENDPOINT_EXPORT: 'dataselectie/bag/export/',
                    ENDPOINT_DETAIL: 'bag/nummeraanduiding/',
                    PRIMARY_KEY: 'nummeraanduiding_id',
                    TITLE: 'Adressen',
                    FILTERS: [
                        {
                            slug: 'stadsdeel_naam',
                            label: 'Stadsdeel'
                        }, {
                            slug: 'ggw_naam',
                            label: 'GGW-gebied'
                        }, {
                            slug: 'buurtcombinatie_naam',
                            label: 'Buurtcombinatie'
                        }, {
                            slug: 'buurt_naam',
                            label: 'Buurt'
                        }, {
                            slug: 'naam',
                            label: 'Openbare ruimte'
                        }, {
                            slug: 'postcode',
                            label: 'Postcode'
                        }
                    ],
                    CONTENT: {
                        TABLE: [
                            {
                                label: 'Naam openbare ruimte',
                                variables: ['_openbare_ruimte_naam']
                            },
                            {
                                label: 'Num.',
                                variables: ['huisnummer']
                            },
                            {
                                label: 'Let.',
                                variables: ['huisletter']
                            },
                            {
                                label: 'Toev.',
                                variables: ['huisnummer_toevoeging']
                            },
                            {
                                label: 'Postcode',
                                variables: ['postcode']
                            },
                            {
                                label: 'Stadsdeel',
                                variables: ['stadsdeel_naam']
                            },
                            {
                                label: '-code',
                                variables: ['stadsdeel_code']
                            },
                            {
                                label: 'GGW-gebied',
                                variables: ['ggw_naam']
                            },
                            {
                                label: '-code',
                                variables: ['ggw_code']
                            },
                            {
                                label: 'Buurtcombinatie',
                                variables: ['buurtcombinatie_naam']
                            },
                            {
                                label: '-code',
                                variables: ['buurtcombinatie_code']
                            },
                            {
                                label: 'Buurt',
                                variables: ['buurt_naam']
                            },
                            {
                                label: '-code',
                                variables: ['buurt_code']
                            }
                        ],
                        LIST: [
                            {
                                variables: [
                                    '_openbare_ruimte_naam',
                                    'huisnummer',
                                    'huisletter',
                                    'huisnummer_toevoeging'
                                ],
                                formatter: 'bagAddress'
                            },
                            {
                                variables: [
                                    'ligplaats_id',
                                    'standplaats_id'
                                ],
                                formatter: 'nummeraanduidingType'
                            },
                            {
                                variables: [
                                    'hoofdadres'
                                ],
                                formatter: 'nevenadres'
                            },
                            {
                                variables: [
                                    'status_id'
                                ],
                                formatter: 'verblijfsobjectGevormd'
                            }
                        ]
                    }
                },
                catalogus: {
                    MAX_ITEMS_PER_PAGE: 100,
                    CUSTOM_API: 'dataSelectionApiCkan',
                    ENDPOINT_PREVIEW: 'catalogus/api/3/action/package_search',
                    ENDPOINT_DETAIL: 'catalogus/api/3/action/package_show',
                    PRIMARY_KEY: 'id',
                    TITLE: 'Catalogus',
                    SHOW_FILTER_OPTION_COUNTS: false,
                    FILTERS: [
                        {
                            slug: 'groups',
                            label: 'Thema\'s'
                        }, {
                            slug: 'res_format',
                            label: 'Formaten',
                            formatter: 'lowercase'
                        }, {
                            slug: 'organization',
                            label: 'Gepubliceerd door'
                        }
                    ],
                    CONTENT: {
                        CARDS: [
                            {
                                label: 'Naam',
                                variables: ['title']
                            }, {
                                label: 'Datum',
                                variables: ['metadata_created', 'metadata_modified'],
                                formatter: 'modificationDate'
                            }, {
                                label: 'Formaten',
                                variables: ['resources.format'],
                                formatter: 'aggregate',
                                template: 'file-type'
                            }, {
                                label: 'Labels',
                                variables: ['tags.display_name'],
                                formatter: 'aggregate',
                                template: 'tags'
                            }, {
                                label: 'Omschrijving',
                                formatter: 'truncateHtmlAsText',
                                variables: ['notes']
                            }
                        ]
                    }
                },
                hr: {
                    CUSTOM_API: 'dataSelectionApiDataSelection',
                    MAX_AVAILABLE_PAGES: 100,
                    ENDPOINT_PREVIEW: 'dataselectie/hr/',
                    ENDPOINT_MARKERS: 'dataselectie/hr/geolocation/',
                    ENDPOINT_EXPORT: 'dataselectie/hr/export/',
                    ENDPOINT_DETAIL: 'handelsregister/vestiging/',
                    PRIMARY_KEY: 'vestiging_id',
                    TITLE: 'Vestigingen',
                    FILTERS: [
                        {
                            slug: 'hoofdcategorie',
                            label: 'Hoofdcategorie'
                        }, {
                            slug: 'subcategorie',
                            label: 'Subcategorie'
                        }, {
                            slug: 'stadsdeel_naam',
                            label: 'Stadsdeel'
                        }, {
                            slug: 'ggw_naam',
                            label: 'GGW-gebied'
                        }, {
                            slug: 'buurtcombinatie_naam',
                            label: 'Buurtcombinatie'
                        }, {
                            slug: 'buurt_naam',
                            label: 'Buurt'
                        }, {
                            slug: 'openbare_ruimte',
                            label: 'Openbare ruimte'
                        }, {
                            slug: 'postcode',
                            label: 'Postcode'
                        }
                    ],
                    CONTENT: {
                        TABLE: [
                            {
                                label: 'KvK-num.',
                                variables: ['kvk_nummer']
                            },
                            {
                                label: 'Handelsnaam',
                                variables: ['handelsnaam']
                            },
                            {
                                label: 'Bezoekadres',
                                variables: ['bezoekadres_volledig_adres']
                            },
                            {
                                label: 'Hoofdcategorie',
                                variables: ['hoofdcategorie']
                            },
                            {
                                label: 'Subcategorie',
                                variables: ['subcategorie']
                            },
                            {
                                label: 'SBI-omschrijving',
                                variables: ['sbi_omschrijving']
                            },
                            {
                                label: 'SBI-code',
                                variables: ['sbi_code']
                            }
                        ],
                        LIST: [
                            {
                                variables: ['handelsnaam']
                            }
                        ]
                    }
                }
            }
        });
})();
<|endoftext|>