<commit_before>#!/usr/bin/env node
'use strict'
const exec = require('child_process').execSync
const fs = require('fs')
const path = require('path')
const util = require('util')

const ghauth = require('ghauth')
const ghissues = require('ghissues')
const pkgToId = require('pkg-to-id')
const program = require('commander')
const semverRegex = require('semver-regex')
const winston = require('winston')

const pkg = require('./package')

const logger = new winston.Logger({
  transports: [new winston.transports.Console()]
})
logger.cli()

function parseArguments (defaults) {
  program
    .version(defaults.version)
    .description(defaults.description)
    .option('-u, --user [user]', 'GitHub user', defaults.user)
    .option('-p, --project [project]', 'GitHub project', defaults.project)
    .option('-t, --tag [tag]', 'Git tag', defaults.tag)
    .option('-l, --log-level [logLevel]',
            'Log level',
            /^(error|warn|info|verbose|debug|silly)$/i,
            defaults.logLevel)
    .option('-n --dry-run',
            'Log actions, but skip adding comments to GitHub PRs')
    .parse(process.argv)
}

function getMergeCommits (revRange) {
  const gitLogCmd = `git log ${revRange} --format='%s' --grep='^Merge pull request #[0-9]\\+ from '`
  logger.debug('Command: %s', gitLogCmd)

  const commits = exec(gitLogCmd).toString().trimRight()
  logger.debug('Commits: %s', commits)
  return commits
}

function writeComments (authOptions, prs, comment) {
  ghauth(authOptions, function (error, authData) {
    if (error) {
      logger.error('GitHub Authorization failure: %s', error)
      process.exit(1)
    }
    logger.debug('GitHub Authorization success for user: %s', authData.user)
    prs.forEach(function (pr) {
      logger.info('Adding comment to PR#%d', pr)
      if (!program.dryRun) {
        ghissues.createComment(
          authData, program.user, program.project, pr, comment, function (error, comment) {
            if (error) {
              logger.error('Error adding comment to PR#%d: %s', pr, error)
            } else {
              logger.debug('Comment: %s', comment)
            }
          })
      }
    })

    logger.info('Done!')
  })
}

function main () {
  logger.info('%s v%s', pkg.name, pkg.version)

  const pkgFile = path.join(process.cwd(), 'package.json')
  const pkgData = fs.existsSync(pkgFile) ? require(pkgFile) : {}
  const pkgId = pkgToId(pkgData)
  const tags = exec("git tag --sort='-version:refname'")
    .toString().split('\n').filter(tag => semverRegex().test(tag))

  const defaults = {
    version: pkg.version,
    description: pkg.description,
    user: pkgId.user,
    project: pkgId.name,
    tag: tags[0],
    logLevel: 'info'
  }
  parseArguments(defaults)

  logger.level = program.logLevel
  logger.debug('pkgId:', pkgId)
  logger.debug('Tags: %s', tags)
  logger.debug('program:', {
    user: program.user,
    project: program.project,
    tag: program.tag,
    logLevel: program.logLevel,
    dryRun: program.dryRun
  })

  if (tags.length === 0) {
    logger.error('No tags found in repository')
    process.exit(1)
  }
  if (!semverRegex().test(program.tag)) {
    logger.error('Tag not semver compliant: %s', program.tag)
    process.exit(1)
  }

  const toTagIndex = tags.indexOf(program.tag)
  if (toTagIndex === -1) {
    logger.error('Tag not found in repository: %s', program.tag)
    process.exit(1)
  }
  const toTag = program.tag
  const fromTag = tags[toTagIndex + 1]

  const revRange = (typeof fromTag !== 'undefined') ? `${fromTag}..${toTag}` : toTag
  const commits = getMergeCommits(revRange)

  const prs = commits.split('\n').map(function (line) {
    const match = /Merge pull request #(\d+) from /.exec(line)
    if (match) {
      return parseInt(match[1], 10)
    }
    return false
  }).filter(Boolean)
  logger.debug('PRs: %s', prs)

  const authOptions = {
    configName: pkg.name,
    note: util.format('%s: %s', pkg.name, pkg.description)
  }
  writeComments(authOptions, prs, toTag)
}

if (require.main === module) {
  main()
}
<commit_msg>Move get PRs code to a separate function<commit_after>#!/usr/bin/env node
'use strict'
const exec = require('child_process').execSync
const fs = require('fs')
const path = require('path')
const util = require('util')

const ghauth = require('ghauth')
const ghissues = require('ghissues')
const pkgToId = require('pkg-to-id')
const program = require('commander')
const semverRegex = require('semver-regex')
const winston = require('winston')

const pkg = require('./package')

const logger = new winston.Logger({
  transports: [new winston.transports.Console()]
})
logger.cli()

function parseArguments (defaults) {
  program
    .version(defaults.version)
    .description(defaults.description)
    .option('-u, --user [user]', 'GitHub user', defaults.user)
    .option('-p, --project [project]', 'GitHub project', defaults.project)
    .option('-t, --tag [tag]', 'Git tag', defaults.tag)
    .option('-l, --log-level [logLevel]',
            'Log level',
            /^(error|warn|info|verbose|debug|silly)$/i,
            defaults.logLevel)
    .option('-n --dry-run',
            'Log actions, but skip adding comments to GitHub PRs')
    .parse(process.argv)
}

function getMergeCommits (revRange) {
  const gitLogCmd = `git log ${revRange} --format='%s' --grep='^Merge pull request #[0-9]\\+ from '`
  logger.debug('Command: %s', gitLogCmd)

  const commits = exec(gitLogCmd).toString().trimRight()
  logger.debug('Commits: %s', commits)
  return commits
}

function getPRs (commits) {
  const prs = commits.split('\n').map(function (line) {
    const match = /Merge pull request #(\d+) from /.exec(line)
    if (match) {
      return parseInt(match[1], 10)
    }
    return false
  }).filter(Boolean)
  logger.debug('PRs: %s', prs)
  return prs
}

function writeComments (authOptions, prs, comment) {
  ghauth(authOptions, function (error, authData) {
    if (error) {
      logger.error('GitHub Authorization failure: %s', error)
      process.exit(1)
    }
    logger.debug('GitHub Authorization success for user: %s', authData.user)
    prs.forEach(function (pr) {
      logger.info('Adding comment to PR#%d', pr)
      if (!program.dryRun) {
        ghissues.createComment(
          authData, program.user, program.project, pr, comment, function (error, comment) {
            if (error) {
              logger.error('Error adding comment to PR#%d: %s', pr, error)
            } else {
              logger.debug('Comment: %s', comment)
            }
          })
      }
    })

    logger.info('Done!')
  })
}

function main () {
  logger.info('%s v%s', pkg.name, pkg.version)

  const pkgFile = path.join(process.cwd(), 'package.json')
  const pkgData = fs.existsSync(pkgFile) ? require(pkgFile) : {}
  const pkgId = pkgToId(pkgData)
  const tags = exec("git tag --sort='-version:refname'")
    .toString().split('\n').filter(tag => semverRegex().test(tag))

  const defaults = {
    version: pkg.version,
    description: pkg.description,
    user: pkgId.user,
    project: pkgId.name,
    tag: tags[0],
    logLevel: 'info'
  }
  parseArguments(defaults)

  logger.level = program.logLevel
  logger.debug('pkgId:', pkgId)
  logger.debug('Tags: %s', tags)
  logger.debug('program:', {
    user: program.user,
    project: program.project,
    tag: program.tag,
    logLevel: program.logLevel,
    dryRun: program.dryRun
  })

  if (tags.length === 0) {
    logger.error('No tags found in repository')
    process.exit(1)
  }
  if (!semverRegex().test(program.tag)) {
    logger.error('Tag not semver compliant: %s', program.tag)
    process.exit(1)
  }

  const toTagIndex = tags.indexOf(program.tag)
  if (toTagIndex === -1) {
    logger.error('Tag not found in repository: %s', program.tag)
    process.exit(1)
  }
  const toTag = program.tag
  const fromTag = tags[toTagIndex + 1]

  const revRange = (typeof fromTag !== 'undefined') ? `${fromTag}..${toTag}` : toTag
  const commits = getMergeCommits(revRange)
  const prs = getPRs(commits)

  const authOptions = {
    configName: pkg.name,
    note: util.format('%s: %s', pkg.name, pkg.description)
  }
  writeComments(authOptions, prs, toTag)
}

if (require.main === module) {
  main()
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'
const fs = require('fs')
const path = require('path')

const pkgToId = require('pkg-to-id')
const program = require('commander')
const semverRegex = require('semver-regex')
const winston = require('winston')

const exec = require('child_process').execSync

const pkg = require('./package')

const pkgFile = path.join(process.cwd(), 'package.json')
const pkgData = fs.existsSync(pkgFile) ? require(pkgFile) : {}
const pkgId = pkgToId(pkgData)

const logger = new winston.Logger({
  level: 'debug',
  transports: [new winston.transports.Console()]
})
logger.cli()

logger.info('%s v%s', pkg.name, pkg.version)
logger.debug('pkgId:', pkgId)

const tags = exec("git tag --sort='-version:refname'")
  .toString().split('\n').filter(tag => semverRegex().test(tag))
logger.debug('Tags: %s', tags)

program
  .version(pkg.version)
  .description(pkg.description)
  .option('-u, --user [user]', 'GitHub user', pkgId.user)
  .option('-p, --project [project]', 'GitHub project', pkgId.name)
  .option('-t, --tag [tag]', 'Git tag', tags[0])
  .parse(process.argv)
logger.debug('program:', {user: program.user, project: program.project})

if (!semverRegex().test(program.tag)) {
  logger.error('Tag not semver compliant: %s', program.tag)
  process.exit(1)
}
if (tags.indexOf(program.tag) === -1) {
  logger.error('Tag not found in repository: %s', program.tag)
  process.exit(1)
}

<commit_msg>Add tag to options logged<commit_after>#!/usr/bin/env node
'use strict'
const fs = require('fs')
const path = require('path')

const pkgToId = require('pkg-to-id')
const program = require('commander')
const semverRegex = require('semver-regex')
const winston = require('winston')

const exec = require('child_process').execSync

const pkg = require('./package')

const pkgFile = path.join(process.cwd(), 'package.json')
const pkgData = fs.existsSync(pkgFile) ? require(pkgFile) : {}
const pkgId = pkgToId(pkgData)

const logger = new winston.Logger({
  level: 'debug',
  transports: [new winston.transports.Console()]
})
logger.cli()

logger.info('%s v%s', pkg.name, pkg.version)
logger.debug('pkgId:', pkgId)

const tags = exec("git tag --sort='-version:refname'")
  .toString().split('\n').filter(tag => semverRegex().test(tag))
logger.debug('Tags: %s', tags)

program
  .version(pkg.version)
  .description(pkg.description)
  .option('-u, --user [user]', 'GitHub user', pkgId.user)
  .option('-p, --project [project]', 'GitHub project', pkgId.name)
  .option('-t, --tag [tag]', 'Git tag', tags[0])
  .parse(process.argv)
logger.debug('program:', {
  user: program.user,
  project: program.project,
  tag: program.tag
})

if (!semverRegex().test(program.tag)) {
  logger.error('Tag not semver compliant: %s', program.tag)
  process.exit(1)
}
if (tags.indexOf(program.tag) === -1) {
  logger.error('Tag not found in repository: %s', program.tag)
  process.exit(1)
}

<|endoftext|>


<commit_before><commit_msg>added<commit_after>$(function() {
function doRequest($progress, url, cb){
//$progress = document.querySelector('#progress');

//var url = 'https://upload.wikimedia.org/wikipedia/commons/6/63/A_large_blank_world_map_with_oceans_marked_in_blue.svg';
//var url = "/svg";
var request = new XMLHttpRequest();
request.onprogress = onProgress;
request.onload = onComplete;
request.onerror = onError;
request.onloadstart = onloadstart;
var total;
function onloadstart(){
  get_filesize(url, null);
  //alert("Total SIze" + total);
  //alert("Load started - " + request.response.length);
}
function onProgress(event) {
  if (!event.lengthComputable) {
    //alert("Recieved so far: " + request.response.length);
    console.log(request.response.length);
//  $progress.textContent = 'Loading... ' + parseFloat(request.response.length / 1024 / 1024).toFixed(2) + ' MBs';
    return;
  }
  var loaded = event.loaded;
  var total = event.total;
  var progress = (loaded / total).toFixed(2);
  $progress.val =  parseInt(progress * 100);
  console.log($progress);

//  $progress.textContent = parseInt(progress * 100);

  console.log("ip " + progress);
}

function onComplete(event) {
 // $img.setAttribute('src', url);
 // $progress.appendChild($img);
 	return cb(url);
  console.log('complete', url);
  //alert("DOne " + request.response.length);
}

function onError(event) {
  console.log('error');
}
function get_filesize(url, callback) {
  xhr = new XMLHttpRequest();
    xhr.open("HEAD", url, true); // Notice "HEAD" instead of "GET",
                                 //  to get only the header
    xhr.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            //alert((xhr.getResponseHeader("Content-Length")));
        }
    };
    xhr.send();
}

//$progress.addEventListener('click', function() {
  request.open('GET', url, true);
  request.overrideMimeType('text/plain; charset=x-user-defined');
  request.send(null);
//});
}

function calculateTotal(cb){
var el = document.getElementById('bar');
var hl = document.getElementById('h1');
var progress = document.getElementById('progress');
var content = document.getElementById('content');
var t  = (man.val + map.val + horizontal.val) / 3;
t = Math.round(t);
//el.textContent = t + ' %';
h1.innerHTML = t + '%';
el.style.width = t + '%'	;

  if(t == 100){
 //	alert("Image loaded")
 	progress.style.opacity = 0;
 	h1.style.opacity = 0;
 	content.style.opacity = 1;
  	return cb();
  }
  setTimeout(function(){
  	calculateTotal(cb);}, 20);
}

}<|endoftext|>


<commit_before>'use strict';

import { EventEmitter } from 'events';

import * as mqtt from 'mqtt';
import { default as extend } from 'extend';
import { default as mqtt_regex } from 'mqtt-regex';

import { MemoryStore } from 'novus-component-store-memory';

/**
 * Default options to use for new routes
**/
const DEFAULT_ROUTE_OPTIONS = {
  subscribe: true
};

/**
 * Component class
**/
export class Component extends EventEmitter {

  /**
   * Constructor
  **/
  constructor(componentId, options = {}) {
    super();
    this._componentId = componentId;
    options.clientId = options.clientId || componentId;
    this._options = options;
    if(!this._options.store) {
      this._options.store = new MemoryStore();
    }
		this._store = this._options.store;

    this._connected = false;
    this._mqtt = null;
    this._routes = [];

    this.methods = {};
  }

  /**
   * Set a key to a value in the Store
  **/
  set(key, value, override = true) {
    if((this._store.get(key) !== null) || (this._store.get(key) === null && override)) {
      this._store.set(key, value, override);
    }
  }

  /**
   * Get the value for a key in the Store
  **/
  get(key, def = null) {
    return this._store.get(key, def);
  }

  /**
   * Returns true if connected to MQTT broker
  **/
  isConnected() {
    return this._mqtt !== null && this._connected;
  }

	/**
	 *
	**/
	register(register, options = {}) {
		if(typeof method === 'function') {
			register = [{
        register: register,
        options: options
      }];
		}

    let promises = [];
    for(let plugin of register) {
      promises.push(plugin.register(this, plugin.options || {}));
    }
    return promises;
	}

  /**
   * Add one or more routes
  **/
  route(routes, handler = null, options = {}) {
    if(typeof handler === 'function') {
      routes = [
        {
          route: routes,
          handler: handler,
          options: options
        }
      ];
    }
    for(let route of routes) {
      route.route = this._replacePlaceholders(route.route);
      route.options = extend(true, {}, DEFAULT_ROUTE_OPTIONS, route.options || {});
      let regex = mqtt_regex(route.route);
      route.topic = regex.topic;
      route.match = regex.exec;
      this._routes.push(route);
    }
  }

  /**
   * Publish a message on a topic
  **/
  publish(topic, message, options = {}) {
    return new Promise((resolve, reject) => {
      if(!this.isConnected()) {
        return reject(new Error('not connected'));
      }
      topic = this._replacePlaceholders(topic);
      this._mqtt.publish(topic, message, options, (err) => {
        if(err) return reject(err);
        return resolve();
      });
    });
  }

  /**
   * Subscribe to a topic
  **/
  subscribe(topic, options = {}) {
    return new Promise((resolve, reject) => {
      if(!this.isConnected()) {
        return reject(new Error('not connected'));
      }
      topic = this._replacePlaceholders(topic);
      this._mqtt.subscribe(topic, options, (err, granted) => {
        if(err) return reject(err);
        return resolve(granted);
      });
    });
  }

  /**
   * Unsubscribe from a topic
  **/
  unsubscribe(topic) {
    return new Promise((resolve, reject) => {
      if(!this.isConnected()) {
        return reject(new Error('not connected'));
      }
      topic = this._replacePlaceholders(topic);
      this._mqtt.unsubscribe(() => {
        return resolve();
      });
    });
  }

  /**
   * Start the Component
  **/
  start() {
    return new Promise((resolve, reject) => {
      if(this._mqtt !== null) {
        return reject(new Error('already started'));
      }

      let promiseDone = false;
      const onError = (err) => {
        if(!promiseDone) {
          reject(err);
          promiseDone = true;
        }
      };

      const onClose = () => {
        this._connected = false;
        if(!promiseDone) {
          reject(new Error('connection closed'));
          promiseDone = true;
        }
      };

      const onConnect = (connack) => {
        this._connected = true;
        this._mqtt.removeListener('error', onError);
        this._mqtt.removeListener('close', onClose);

        this._attachListeners();
        this._subscribeToRoutes();
        return resolve(connack);
      };

      this._mqtt = mqtt.connect(this._options.url || this._options);
      this._mqtt.once('connect', onConnect);
      this._mqtt.once('error', onError);
      this._mqtt.once('close', onClose);
    });
  }

  /**
   * End the connection to the MQTT broker
  **/
  end(force = false) {
    return new Promise((resolve, reject) => {
      if(!this.isConnected()) {
        return reject(new Error('connection already closed'));
      }
      this._mqtt.end(force, () => {
        return resolve();
      });
    });
  }

  /**
   * Attach MQTT listeners
  **/
  _attachListeners() {

    const onMessage = (topic, message, packet) => {
      let route = this._matchTopicToRoute(topic);
      if(route !== null) {
        packet.params = route.match(topic);
        route.handler(packet, this);
      }
    };

    const onError = (err) => {
      this.emit('error', err);
    };

    const onClose = () => {
      this.emit('close');
      this._connected = false;
      this._mqtt = null;
    };

    this._mqtt.on('message', onMessage);
    this._mqtt.on('error', onError);
    this._mqtt.once('close', onClose);

  }

  /**
   * Subscribe to routes
  */
  _subscribeToRoutes() {
    for(let route of this._routes) {
      if(route.options.subscribe) {
        this._mqtt.subscribe(route.topic);
      }
    }
  }

  /**
   * Match a topic to a route
  **/
  _matchTopicToRoute(topic) {
    for(let route of this._routes) {
      if(route.match(topic)) {
        return route;
      }
    }
    return null;
  }

  /**
   * Replaces Component-specific keys in topics
  **/
  _replacePlaceholders(topic) {
    topic = topic.replace('{$componentId}', this._componentId);
    return topic;
  }

}
<commit_msg>Add route option 'once'<commit_after>'use strict';

import { EventEmitter } from 'events';

import * as mqtt from 'mqtt';
import { default as extend } from 'extend';
import { default as mqtt_regex } from 'mqtt-regex';

import { MemoryStore } from 'novus-component-store-memory';

/**
 * Default options to use for new routes
**/
const DEFAULT_ROUTE_OPTIONS = {
  subscribe: true
};

/**
 * Component class
**/
export class Component extends EventEmitter {

  /**
   * Constructor
  **/
  constructor(componentId, options = {}) {
    super();
    this._componentId = componentId;
    options.clientId = options.clientId || componentId;
    this._options = options;
    if(!this._options.store) {
      this._options.store = new MemoryStore();
    }
		this._store = this._options.store;

    this._connected = false;
    this._mqtt = null;
    this._routes = [];

    this.methods = {};
  }

  /**
   * Set a key to a value in the Store
  **/
  set(key, value, override = true) {
    if((this._store.get(key) !== null) || (this._store.get(key) === null && override)) {
      this._store.set(key, value, override);
    }
  }

  /**
   * Get the value for a key in the Store
  **/
  get(key, def = null) {
    return this._store.get(key, def);
  }

  /**
   * Returns true if connected to MQTT broker
  **/
  isConnected() {
    return this._mqtt !== null && this._connected;
  }

	/**
	 *
	**/
	register(register, options = {}) {
		if(typeof method === 'function') {
			register = [{
        register: register,
        options: options
      }];
		}

    let promises = [];
    for(let plugin of register) {
      promises.push(plugin.register(this, plugin.options || {}));
    }
    return promises;
	}

  /**
   * Add one or more routes
  **/
  route(routes, handler = null, options = {}) {
    if(typeof handler === 'function') {
      routes = [
        {
          route: routes,
          handler: handler,
          options: options
        }
      ];
    }
    for(let route of routes) {
      route.route = this._replacePlaceholders(route.route);
      route.options = extend(true, {}, DEFAULT_ROUTE_OPTIONS, route.options || {});
      let regex = mqtt_regex(route.route);
      route.topic = regex.topic;
      route.match = regex.exec;
      this._routes.push(route);
    }
  }

  /**
   * Publish a message on a topic
  **/
  publish(topic, message, options = {}) {
    return new Promise((resolve, reject) => {
      if(!this.isConnected()) {
        return reject(new Error('not connected'));
      }
      topic = this._replacePlaceholders(topic);
      this._mqtt.publish(topic, message, options, (err) => {
        if(err) return reject(err);
        return resolve();
      });
    });
  }

  /**
   * Subscribe to a topic
  **/
  subscribe(topic, options = {}) {
    return new Promise((resolve, reject) => {
      if(!this.isConnected()) {
        return reject(new Error('not connected'));
      }
      topic = this._replacePlaceholders(topic);
      this._mqtt.subscribe(topic, options, (err, granted) => {
        if(err) return reject(err);
        return resolve(granted);
      });
    });
  }

  /**
   * Unsubscribe from a topic
  **/
  unsubscribe(topic) {
    return new Promise((resolve, reject) => {
      if(!this.isConnected()) {
        return reject(new Error('not connected'));
      }
      topic = this._replacePlaceholders(topic);
      this._mqtt.unsubscribe(() => {
        return resolve();
      });
    });
  }

  /**
   * Start the Component
  **/
  start() {
    return new Promise((resolve, reject) => {
      if(this._mqtt !== null) {
        return reject(new Error('already started'));
      }

      let promiseDone = false;
      const onError = (err) => {
        if(!promiseDone) {
          reject(err);
          promiseDone = true;
        }
      };

      const onClose = () => {
        this._connected = false;
        if(!promiseDone) {
          reject(new Error('connection closed'));
          promiseDone = true;
        }
      };

      const onConnect = (connack) => {
        this._connected = true;
        this._mqtt.removeListener('error', onError);
        this._mqtt.removeListener('close', onClose);

        this._attachListeners();
        this._subscribeToRoutes();
        return resolve(connack);
      };

      this._mqtt = mqtt.connect(this._options.url || this._options);
      this._mqtt.once('connect', onConnect);
      this._mqtt.once('error', onError);
      this._mqtt.once('close', onClose);
    });
  }

  /**
   * End the connection to the MQTT broker
  **/
  end(force = false) {
    return new Promise((resolve, reject) => {
      if(!this.isConnected()) {
        return reject(new Error('connection already closed'));
      }
      this._mqtt.end(force, () => {
        return resolve();
      });
    });
  }

  /**
   * Attach MQTT listeners
  **/
  _attachListeners() {

    const onMessage = (topic, message, packet) => {
      let route = this._matchTopicToRoute(topic);
      if(route !== null) {
        packet.params = route.match(topic);
        route.handler(packet, this);
      }
    };

    const onError = (err) => {
      this.emit('error', err);
    };

    const onClose = () => {
      this.emit('close');
      this._connected = false;
      this._mqtt = null;
    };

    this._mqtt.on('message', onMessage);
    this._mqtt.on('error', onError);
    this._mqtt.once('close', onClose);

  }

  /**
   * Subscribe to routes
  */
  _subscribeToRoutes() {
    for(let route of this._routes) {
      if(route.options.subscribe) {
        this._mqtt.subscribe(route.topic);
      }
    }
  }

  /**
   * Match a topic to a route
  **/
  _matchTopicToRoute(topic) {
    for(let route of this._routes) {
      if(route.match(topic)) {
        if(route.options.once) {
          this.unsubscribe(route.topic);
        }
        return route;
      }
    }
    return null;
  }

  /**
   * Replaces Component-specific keys in topics
  **/
  _replacePlaceholders(topic) {
    topic = topic.replace('{$componentId}', this._componentId);
    return topic;
  }

}
<|endoftext|>


<commit_before><commit_msg>update pascalprechts avatar<commit_after><|endoftext|>


<commit_before>import _ from 'lodash';
import request from 'request';

/**
 * Makes a request to Classy's API.
 *
 * @param  {string} path    Request URI
 * @param  {string} method  Request method
 * @param  {object} headers Request headers
 * @param  {object} form    Request form (optional)
 * @return {promise}         Promise based on API request
 */
export default function _makeRequest(path, method, headers, form, data) {
  const _this = this;
  let forceQs = null;

  if (data.noLog) {
    headers['x-no-log'] = true;
    delete data.noLog;
  }

  if (_.isObject(data.qs)) {
    forceQs = data.qs;
    delete data.qs;
  }

  const promise = new Promise((resolve, reject) => {
    // the encoding param defaults to undefined, which means the response will be stringified
    // we want to preserve the binary encoding for pdfs, so return null in this case
    const encoding = _.includes(headers['Content-Type'], 'pdf')
      ? null
      : undefined;

    const requestParams = {
      baseUrl: this.baseUrl,
      uri: path,
      method: method,
      headers: headers,
      rejectUnauthorized: false,
      form: form,
      encoding: encoding
    };

    if (method === 'GET') {
      requestParams.qs = data;
    } else {
      requestParams.body = JSON.stringify(data);
    }

    if (forceQs) {
      requestParams.qs = _.merge(requestParams.qs || {}, forceQs);
    }

    request(requestParams, (err, response, body) => {
      if (err || !/^2/.test('' + response.statusCode)) {
        let error;
        if (err && err instanceof Error) {
          error = err;
        } else if (err && !(err instanceof Error)) {
          const errorString = JSON.stringify(err);
          error = new Error(errorString);
        } else {
          const errorString = body ? JSON.stringify(body) : 'Non-200 response';
          error = new Error(errorString);
          error.statusCode = response.statusCode;
        }

        reject(error);
      } else {
        // if we're not returning a pdf file, parse body
        if (!_.includes(response.headers['Content-Type'], 'pdf')) {
          body = body ? JSON.parse(body) : {};
        }
        resolve(body);
      }
    });
  });

  return promise;
}
<commit_msg>CL-22 fix formatting<commit_after>import _ from 'lodash';
import request from 'request';

/**
 * Makes a request to Classy's API.
 *
 * @param  {string} path    Request URI
 * @param  {string} method  Request method
 * @param  {object} headers Request headers
 * @param  {object} form    Request form (optional)
 * @return {promise}         Promise based on API request
 */
export default function _makeRequest(path, method, headers, form, data) {
  const _this = this;
  let forceQs = null;

  if (data.noLog) {
    headers['x-no-log'] = true;
    delete data.noLog;
  }

  if (_.isObject(data.qs)) {
    forceQs = data.qs;
    delete data.qs;
  }

  const promise = new Promise((resolve, reject) => {
    // the encoding param defaults to undefined, which means the response will be stringified
    // we want to preserve the binary encoding for pdfs, so return null in this case
    const encoding = _.includes(headers['Content-Type'], 'pdf')
      ? null
      : undefined;

    const requestParams = {
      baseUrl: this.baseUrl,
      uri: path,
      method: method,
      headers: headers,
      rejectUnauthorized: false,
      form: form,
      encoding: encoding
    };

    if (method === 'GET') {
      requestParams.qs = data;
    } else {
      requestParams.body = JSON.stringify(data);
    }

    if (forceQs) {
      requestParams.qs = _.merge(requestParams.qs || {}, forceQs);
    }

    request(requestParams, (err, response, body) => {
      if (err || !/^2/.test('' + response.statusCode)) {
        let error;
        if (err && err instanceof Error) {
          error = err;
        } else if (err && !(err instanceof Error)) {
          const errorString = JSON.stringify(err);
          error = new Error(errorString);
        } else {
          const errorString = body ? JSON.stringify(body) : 'Non-200 response';
          error = new Error(errorString);
          error.statusCode = response.statusCode;
        }

        reject(error);
      } else {
        // if we're not returning a pdf file, parse body
        if (!_.includes(response.headers['Content-Type'], 'pdf')) {
          body = body ? JSON.parse(body) : {};
        }

        resolve(body);
      }
    });
  });

  return promise;
}
<|endoftext|>


<commit_before>"use strict";
var fs = require("fs");
var vm = require("vm");
var os = require("os");
var path = require("path");
var isLib = require("./isLib");
var parseURL = require("../basic/parseURL");
var userAgent = "Efront/1.0";
var mainLoaderPromise = new Promise(function (ok, oh) {
    fs.readFile(path.join(__dirname, "../basic/loader.js"), function (error, data) {
        if (error) oh(error);
        ok(data.toString());
    });
});
function fromComponent(base) {
    var packer = require("./finalpacker");
    var requestInternet = fromInternet("");
    var request = function (url, onsuccess, onerror) {
        var isdestroied = false;
        if (/^https?\:\/\//i.test(url)) {
            return requestInternet(url, onsuccess, onerror);
        }
        if (/^\/?comm\b/i.test(url)) {
            try {

                var temppath = require.resolve(url.replace(/^\/?comm\b/i, '.').replace(/[\\\$]/g, '/'), { paths: process.env.COMS_PATH.split(',') })
                if (isLib(temppath)) {
                    var mode = function () {
                        return require(temppath);
                    };
                    mode.file = temppath;
                    onsuccess(mode);
                    return;
                }
            } catch (e) {

            }
        }
        var abort = function () {
            isdestroied = true;
        };
        requestHandles.push(abort);
        var url1 = base.replace(/[^\\\/]*$/, url);
        url1 = url1.replace(/^\/?/, "/");

        packer(url1, function (result) {
            var index = requestHandles.indexOf(abort);
            if (index >= 0) {
                requestHandles.splice(index, 1);
            }
            if (isdestroied) return;
            if (result instanceof Error) {
                onerror(result);
            }
            if (!result) {
                if (!/^comm\//i.test(url)) {

                    console.fail(url);
                } else {
                    url1 = url.replace(/^comm\//i, '');
                    if (global[url1]) {
                        result = function () { return this }.bind(global[url1]);
                    } else {
                        try {
                            url1 = url1.replace(/\$/g, '/');
                            if (/\./.test(url1)) {
                                var resolved = require.resolve(url1, { paths: process.env.COMS_PATH.split(',') });
                            } else {
                                var resolved = require.resolve(url1);
                            }
                            if (resolved) {

                                result = function () {
                                    return require(resolved);
                                };
                                result.file = resolved;
                                result.args = [];
                            }
                        } catch (e) {
                            console.fail(url1);
                        }
                    }
                }
            } else {
                result = result.toString();
            }
            onsuccess(result || '');
            require("./watch").close();
        });
    };
    require("./watch").close();
    return request;
}
function fromInternet(mainfilepath) {
    var http = require('http');
    var https = require('https');
    var URL = require("url");
    var reg = /^(https?)\:\/\//i;
    function request(url, onsuccess, onerror) {
        if (!reg.test(url)) {
            url = mainfilepath.replace(/\/[^\/]*$/, url.replace(/^\/?/, "/"));
        }
        var _url = parseURL(url);
        var req = /^https?/i.test(_url.protocol) ? https : http;
        var onend = function () {
            var index = requestHandles.indexOf(abort);
            if (index >= 0) {
                requestHandles.splice(index, 1);
            }
        };
        var request = req.request(Object.assign({ method: "get" }, _url), function (res) {
            var result = [];
            var size = 0;
            res.on("data", function (buffer) {
                size += buffer.length;
                result.push(buffer);
            });
            res.once("end", function (event) {
                onend();
                onsuccess(Buffer.concat(result).toString());
            });
            res.once("abort", onend);
            res.once('timeout', function (event) {
                onend();
                onerror(event);
            });
            res.once("error", function (event) {
                onend();
                onerror(event);
            });
        });
        request.end();
        var abort = request.abort.bind(request);
        requestHandles.push(abort);
    }
    return request;
}
var timeoutHandles = {};
var intervalHandles = {};
var requestHandles = [];
function efront() {
    function Storage() { }
    Storage.prototype = {
        getItem() { },
        setItem() { }
    };

    var Window = function () {
    };
    Window.prototype = global;
    var window = new Window;
    Object.assign(window, {
        performance: {},
        require(modulepath) {
            try {
                return require(modulepath);
            } catch (e) {
            }
            var resolved = require.resolve("./" + modulepath, { paths: process.env.COMS_PATH.split(",") });

            return require(resolved);
        },
        setTimeout(f, timerout) {
            var args = [].slice.call(arguments, 2);
            var handle = setTimeout(function () {
                delete timeoutHandles[handle];
                return f.apply(this, args);
            }, timerout);
            timeoutHandles[handle] = true;
            return handle;
        },
        setInterval(f, timerout) {
            var args = [].slice.call(arguments, 2);
            var handle = setInterval(function () {
                delete intervalHandles[handle];
                return f.apply(this, args);
            }, timerout);
            intervalHandles[handle] = true;
            return handle;
        },
        navigator: {
            userAgent,
            platform: os.platform()
        },
        clearTimeout(handle) {
            delete timeoutHandles[handle];
            return clearTimeout(handle);
        },
        clearInterval(handle) {
            delete intervalHandles[handle];
            return clearInterval(handle);
        },
        document: {
            documentElement: {
                style: {}
            },
            body: {
                style: {},
                setAttribute() {
                },
                getAttribute() {
                }
            },
            write() {
                console.log.apply(console, arguments);
            }
        },
        localStorage: new Storage,
        sessionStorage: new Storage

    });
    window.top = window.window = window;
    return window;
}
module.exports = function (mainpath, args) {
    mainpath = mainpath.replace(/\.[tj]sx?$/i, '');
    var unload = function () {
        Object.keys(intervalHandles).map(clearInterval);
        Object.keys(timeoutHandles).map(clearTimeout);
        requestHandles.slice(0).map(r => r());
    };
    var fullpath = require.resolve(mainpath, { paths: process.env.COMS_PATH.split(",") });
    var pathname = path.relative(mainpath.replace(/[^\\\/]+$/, ''), '.');
    pathname = path.join(fullpath, pathname);
    pathname = pathname.replace(/\\/g, '/').replace(/[^\/]+$/, '');
    var location = Object.freeze({
        pathname,
        reload() {
            unload();
            var window = efront();
            var getLoader;
            if (/^https?\:\/\//i.test(mainpath)) {
                getLoader = fromInternet.bind(window, mainpath);
            } else {
                getLoader = fromComponent.bind(window, '/');
            }
            window.request = getLoader();
            window.location = location;
            window.startPath = mainpath.replace(/^\.[\/\\]/, '');
            window.process = Object.create(process);
            Object.assign(window.process, {
                argv: args
            });

            mainLoaderPromise.then(function (loader) {
                new Function(loader).call(window);
            }).catch(function (e) {
                console.log(e);
                console.error("启动失败");
            });
        }
    });
    location.reload();
};<commit_msg>修复run命令<commit_after>"use strict";
var fs = require("fs");
var vm = require("vm");
var os = require("os");
var path = require("path");
var isLib = require("./isLib");
var parseURL = require("../basic/parseURL");
var userAgent = "Efront/1.0";
var mainLoaderPromise = new Promise(function (ok, oh) {
    fs.readFile(path.join(__dirname, "../basic/loader.js"), function (error, data) {
        if (error) oh(error);
        ok(data.toString());
    });
});
function fromComponent(base) {
    var packer = require("./finalpacker");
    var requestInternet = fromInternet("");
    var request = function (url, onsuccess, onerror) {
        var isdestroied = false;
        if (/^https?\:\/\//i.test(url)) {
            return requestInternet(url, onsuccess, onerror);
        }
        if (/^\/?comm\b/i.test(url)) {
            try {

                var temppath = require.resolve(url.replace(/^\/?comm\b/i, '.').replace(/[\\\$]/g, '/'), { paths: [].concat(process.env.COMS_PATH.split(','), ".") })
                if (isLib(temppath)) {
                    var mode = function () {
                        return require(temppath);
                    };
                    mode.file = temppath;
                    onsuccess(mode);
                    return;
                }
            } catch (e) {

            }
        }
        var abort = function () {
            isdestroied = true;
        };
        requestHandles.push(abort);
        var url1 = base.replace(/[^\\\/]*$/, url);
        url1 = url1.replace(/^\/?/, "/");

        packer(url1, function (result) {
            var index = requestHandles.indexOf(abort);
            if (index >= 0) {
                requestHandles.splice(index, 1);
            }
            if (isdestroied) return;
            if (result instanceof Error) {
                onerror(result);
            }
            if (!result) {
                if (!/^comm\//i.test(url)) {

                    console.fail(url);
                } else {
                    url1 = url.replace(/^comm\//i, '');
                    if (global[url1]) {
                        result = function () { return this }.bind(global[url1]);
                    } else {
                        try {
                            url1 = url1.replace(/\$/g, '/');
                            if (/\//.test(url1)) {
                                var parth = path.relative(url1, '.');
                                if (/^\./.test(parth)) {
                                    url1 = "./" + path.relative('.', url1).replace('\\', '/');
                                }

                                var resolved = require.resolve(url1, { paths: [].concat(process.env.COMS_PATH.split(','), '.') });
                            } else {
                                var resolved = require.resolve(url1);
                            }
                            if (resolved) {

                                result = function () {
                                    return require(resolved);
                                };
                                result.file = resolved;
                                result.args = [];
                            }
                        } catch (e) {
                            console.fail(url1);
                        }
                    }
                }
            } else {
                result = result.toString();
            }
            onsuccess(result || '');
            require("./watch").close();
        });
    };
    require("./watch").close();
    return request;
}
function fromInternet(mainfilepath) {
    var http = require('http');
    var https = require('https');
    var URL = require("url");
    var reg = /^(https?)\:\/\//i;
    function request(url, onsuccess, onerror) {
        if (!reg.test(url)) {
            url = mainfilepath.replace(/\/[^\/]*$/, url.replace(/^\/?/, "/"));
        }
        var _url = parseURL(url);
        var req = /^https?/i.test(_url.protocol) ? https : http;
        var onend = function () {
            var index = requestHandles.indexOf(abort);
            if (index >= 0) {
                requestHandles.splice(index, 1);
            }
        };
        var request = req.request(Object.assign({ method: "get" }, _url), function (res) {
            var result = [];
            var size = 0;
            res.on("data", function (buffer) {
                size += buffer.length;
                result.push(buffer);
            });
            res.once("end", function (event) {
                onend();
                onsuccess(Buffer.concat(result).toString());
            });
            res.once("abort", onend);
            res.once('timeout', function (event) {
                onend();
                onerror(event);
            });
            res.once("error", function (event) {
                onend();
                onerror(event);
            });
        });
        request.end();
        var abort = request.abort.bind(request);
        requestHandles.push(abort);
    }
    return request;
}
var timeoutHandles = {};
var intervalHandles = {};
var requestHandles = [];
function efront() {
    function Storage() { }
    Storage.prototype = {
        getItem() { },
        setItem() { }
    };

    var Window = function () {
    };
    Window.prototype = global;
    var window = new Window;
    Object.assign(window, {
        performance: {},
        require(modulepath) {
            try {
                return require(modulepath);
            } catch (e) {
            }
            var resolved = require.resolve(modulepath, { paths: [].concat(process.env.COMS_PATH.split(","), '.') });

            return require(resolved);
        },
        setTimeout(f, timerout) {
            var args = [].slice.call(arguments, 2);
            var handle = setTimeout(function () {
                delete timeoutHandles[handle];
                return f.apply(this, args);
            }, timerout);
            timeoutHandles[handle] = true;
            return handle;
        },
        setInterval(f, timerout) {
            var args = [].slice.call(arguments, 2);
            var handle = setInterval(function () {
                delete intervalHandles[handle];
                return f.apply(this, args);
            }, timerout);
            intervalHandles[handle] = true;
            return handle;
        },
        navigator: {
            userAgent,
            platform: os.platform()
        },
        clearTimeout(handle) {
            delete timeoutHandles[handle];
            return clearTimeout(handle);
        },
        clearInterval(handle) {
            delete intervalHandles[handle];
            return clearInterval(handle);
        },
        document: {
            documentElement: {
                style: {}
            },
            body: {
                style: {},
                setAttribute() {
                },
                getAttribute() {
                }
            },
            write() {
                console.log.apply(console, arguments);
            }
        },
        localStorage: new Storage,
        sessionStorage: new Storage

    });
    window.require.resolve = require.resolve;
    window.top = window.window = window;
    return window;
}
module.exports = function (mainpath, args) {
    mainpath = mainpath.replace(/\.[tj]sx?$/i, '');
    var unload = function () {
        Object.keys(intervalHandles).map(clearInterval);
        Object.keys(timeoutHandles).map(clearTimeout);
        requestHandles.slice(0).map(r => r());
    };
    var fullpath = require.resolve("./" + mainpath, { paths: [].concat(process.env.COMS_PATH.split(","), '.') });
    var pathname = path.relative(mainpath.replace(/[^\\\/]+$/, ''), '.');
    pathname = path.join(fullpath, pathname);
    pathname = pathname.replace(/\\/g, '/').replace(/[^\/]+$/, '');
    var location = Object.freeze({
        pathname,
        reload() {
            unload();
            var window = efront();
            var getLoader;
            if (/^https?\:\/\//i.test(mainpath)) {
                getLoader = fromInternet.bind(window, mainpath);
            } else {
                getLoader = fromComponent.bind(window, '/');
            }
            window.request = getLoader();
            window.location = location;
            window.startPath = mainpath.replace(/^\.[\/\\]/, '');
            window.process = Object.create(process);
            Object.assign(window.process, {
                argv: args
            });

            mainLoaderPromise.then(function (loader) {
                new Function(loader).call(window);
            }).catch(function (e) {
                console.log(e);
                console.error("启动失败");
            });
        }
    });
    location.reload();
};<|endoftext|>


<commit_before>'use strict';

var scopeObject = {
  snapIndex: '=?',
  snapHeight: '=?',
  beforeSnap: '&',
  afterSnap: '&'
};

var controller = ['$scope', function ($scope) {
  this.setSnapHeight = function (height) {
    $scope.snapHeight = height;
  };
}];

var watchSnapHeight = function (scope, element, callback) {
  scope.$watch('snapHeight', function (snapHeight) {
    if (angular.isUndefined(snapHeight)) {
      scope.snapHeight = element[0].offsetHeight;
      return;
    }
    if (!angular.isNumber(snapHeight)) {
      scope.snapHeight = element[0].offsetHeight;
      return;
    }
    element.css('height', snapHeight + 'px');
    if (angular.isFunction(callback)) {
      callback(snapHeight);
    }
  });
};

var watchSnapIndex = function (scope, callback) {
  scope.$watch('snapIndex', function (snapIndex) {
    if (angular.isUndefined(snapIndex)) {
      scope.snapIndex = 0;
      return;
    }
    if (!angular.isNumber(snapIndex)) {
      scope.snapIndex = 0;
      return;
    }
    if (angular.isFunction(callback)) {
      callback(snapIndex);
    }
  });
};

var snapscrollAsAnAttribute = ['$timeout',
  function ($timeout) {
    return {
      restrict: 'A',
      scope: scopeObject,
      controller: controller,
      link: function (scope, element, attributes) {
        var snapTo,
            onScroll,
            bindScroll,
            unbindScroll,
            scrollPromise = 0,
            scrollDelay = attributes.scrollDelay;

        if (scrollDelay === 'false') {
          scrollDelay = false;
        } else {
          scrollDelay = parseInt(scrollDelay);
          if (isNaN(scrollDelay)) {
            scrollDelay = 250;
          }
        }

        snapTo = function (index) {
          unbindScroll();
          element[0].scrollTop = index * scope.snapHeight;
          bindScroll();
        };

        onScroll = function () {
          var snap = function () {
            var top = element[0].scrollTop,
                previousSnapIndex = scope.snapIndex,
                newSnapIndex = Math.round(top / scope.snapHeight);
            if (previousSnapIndex === newSnapIndex) {
              snapTo(newSnapIndex);
            } else {
              scope.$apply(function () {
                scope.snapIndex = newSnapIndex;
              });
            }
          };
          if (scrollDelay === false) {
            snap();
          } else {
            $timeout.cancel(scrollPromise);
            scrollPromise = $timeout(snap, scrollDelay);
          }
        };

        bindScroll = function () {
          element.on('scroll', onScroll);
        };

        unbindScroll = function () {
          element.off('scroll', onScroll);
        };

        watchSnapHeight(scope, element, function () {
          snapTo(scope.snapIndex);
        });

        watchSnapIndex(scope, function (snapIndex) {
          snapTo(snapIndex);
        });

        bindScroll();
        scope.$on('$destroy', unbindScroll);
      }
    };
  }
];

var snapscrollAsAnElement = [
  function () {
    return {
      restrict: 'E',
      scope: scopeObject,
      controller: controller,
      link: function (scope, element) {
        watchSnapHeight(scope, element);
        watchSnapIndex(scope);
      }
    };
  }
];

angular.module('snapscroll')
  .directive('snapscroll', snapscrollAsAnAttribute)
  .directive('snapscroll', snapscrollAsAnElement);<commit_msg>better this way..<commit_after>'use strict';

var scopeObject = {
  snapIndex: '=?',
  snapHeight: '=?',
  beforeSnap: '&',
  afterSnap: '&'
};

var controller = ['$scope', function ($scope) {
  this.setSnapHeight = function (height) {
    $scope.snapHeight = height;
  };
}];

var watchSnapHeight = function (scope, element, callback) {
  scope.$watch('snapHeight', function (snapHeight) {
    if (angular.isUndefined(snapHeight)) {
      scope.snapHeight = element[0].offsetHeight;
      return;
    }
    if (!angular.isNumber(snapHeight)) {
      scope.snapHeight = element[0].offsetHeight;
      return;
    }
    element.css('height', snapHeight + 'px');
    if (angular.isFunction(callback)) {
      callback(snapHeight);
    }
  });
};

var watchSnapIndex = function (scope, callback) {
  scope.$watch('snapIndex', function (snapIndex) {
    if (angular.isUndefined(snapIndex)) {
      scope.snapIndex = 0;
      return;
    }
    if (!angular.isNumber(snapIndex)) {
      scope.snapIndex = 0;
      return;
    }
    if (angular.isFunction(callback)) {
      callback(snapIndex);
    }
  });
};

var snapscrollAsAnAttribute = ['$timeout',
  function ($timeout) {
    return {
      restrict: 'A',
      scope: scopeObject,
      controller: controller,
      link: function (scope, element, attributes) {
        var snapTo,
            onScroll,
            bindScroll,
            unbindScroll,
            watchSnapIndexCallback,
            scrollPromise = 0,
            scrollDelay = attributes.scrollDelay;

        if (scrollDelay === 'false') {
          scrollDelay = false;
        } else {
          scrollDelay = parseInt(scrollDelay);
          if (isNaN(scrollDelay)) {
            scrollDelay = 250;
          }
        }

        snapTo = function (index) {
          unbindScroll();
          element[0].scrollTop = index * scope.snapHeight;
          bindScroll();
        };

        onScroll = function () {
          var snap = function () {
            var top = element[0].scrollTop,
                previousSnapIndex = scope.snapIndex,
                newSnapIndex = Math.round(top / scope.snapHeight);
            if (previousSnapIndex === newSnapIndex) {
              watchSnapIndexCallback(newSnapIndex);
            } else {
              scope.$apply(function () {
                scope.snapIndex = newSnapIndex;
              });
            }
          };
          if (scrollDelay === false) {
            snap();
          } else {
            $timeout.cancel(scrollPromise);
            scrollPromise = $timeout(snap, scrollDelay);
          }
        };

        watchSnapIndexCallback = function (snapIndex) {
          snapTo(snapIndex);
        };

        bindScroll = function () {
          element.on('scroll', onScroll);
        };

        unbindScroll = function () {
          element.off('scroll', onScroll);
        };

        watchSnapHeight(scope, element, function () {
          snapTo(scope.snapIndex);
        });

        watchSnapIndex(scope, watchSnapIndexCallback);

        bindScroll();
        scope.$on('$destroy', unbindScroll);
      }
    };
  }
];

var snapscrollAsAnElement = [
  function () {
    return {
      restrict: 'E',
      scope: scopeObject,
      controller: controller,
      link: function (scope, element) {
        watchSnapHeight(scope, element);
        watchSnapIndex(scope);
      }
    };
  }
];

angular.module('snapscroll')
  .directive('snapscroll', snapscrollAsAnAttribute)
  .directive('snapscroll', snapscrollAsAnElement);<|endoftext|>


<commit_before>import React from "react/addons";

import ResolverError from "./ResolverError";

const { Children } = React;
const { cloneWithProps } = React.addons;

class Container extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = this.getResolver().getContainerState(this);
  }

  componentWillMount() {
    if (!this.state.fulfilled) {
      this.getResolver().resolve(this, this.setState.bind(this));
    }
  }

  getChildContext() {
    const resolver = this.getResolver();

    return { resolver };
  }

  getResolver() {
    const resolver = this.props.resolver || this.context.resolver;

    if (!resolver) {
      throw new ReferenceError("Resolver is not defined in either `context` or `props`.  (Perhaps missing a root <Container resolver={new Resolver()} />?)");
    }

    return resolver;
  }

  shouldComponentUpdate(props, state) {
    return state.fulfilled;
  }

  render() {
    if (!this.state.fulfilled) {
      return false;
    }

    if (this.props.component) {
      return (
        <this.props.component {...this.state.values} />
      );
    }

    if (this.props.element) {
      return cloneWithProps(this.props.element);
    }

    if (this.props.children) {
      if (Children.count(this.props.children) === 1) {
        return cloneWithProps(Children.only(this.props.children));
      }
      return (

          {Children.map(this.props.children, cloneWithProps)}

      );
    }

    throw new ResolverError("<Container /> requires one of the following props to render: `element`, `component`, or `children`");
  }
}

Container.childContextTypes = {
  resolver: React.PropTypes.object,
};

Container.contextTypes = {
  id: React.PropTypes.string,
  resolver: React.PropTypes.object,
};

Container.displayName = "ResolverContainer";

Container.propTypes = {
  component: React.PropTypes.any,
  element: React.PropTypes.element,
  resolve: React.PropTypes.object,
  resolver: React.PropTypes.object,
};

export default Container;
<commit_msg>setState callback returns Promise for render()<commit_after>import React from "react/addons";

import ResolverError from "./ResolverError";

const { Children } = React;
const { cloneWithProps } = React.addons;

class Container extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.id = this.getResolver().getContainerId(this);
    this.state = this.getResolver().getContainerState(this);
  }

  componentWillMount() {
    if (!this.state.fulfilled) {
      this.getResolver().resolve(this, (state) => {
        return new Promise((resolve) => {
          this.setState(state, resolve);
        });
      });
    }
  }

  getChildContext() {
    const parent = this;
    const resolver = this.getResolver();

    return {
      parent,
      resolver,
    };
  }

  getResolver() {
    const resolver = this.props.resolver || this.context.resolver;

    if (!resolver) {
      throw new ReferenceError("Resolver is not defined in either `context` or `props`.  (Perhaps missing a root <Container resolver={new Resolver()} />?)");
    }

    return resolver;
  }

  shouldComponentUpdate(props, state) {
    return state.fulfilled;
  }

  render() {
    if (!this.state.fulfilled) {
      return false;
    }

    if (this.props.component) {
      return (
        <this.props.component {...this.state.values} />
      );
    }

    if (this.props.element) {
      return cloneWithProps(this.props.element);
    }

    if (this.props.children) {
      if (Children.count(this.props.children) === 1) {
        return cloneWithProps(Children.only(this.props.children));
      }
      return (

          {Children.map(this.props.children, cloneWithProps)}

      );
    }

    throw new ResolverError("<Container /> requires one of the following props to render: `element`, `component`, or `children`");
  }
}

Container.childContextTypes = {
  resolver: React.PropTypes.object,
};

Container.contextTypes = {
  id: React.PropTypes.string,
  resolver: React.PropTypes.object,
};

Container.displayName = "ResolverContainer";

Container.propTypes = {
  component: React.PropTypes.any,
  element: React.PropTypes.element,
  resolve: React.PropTypes.object,
  resolver: React.PropTypes.object,
};

export default Container;
<|endoftext|>


<commit_before>/*!
 * jQuery Browser Plugin v0.0.3
 * https://github.com/gabceb/jquery-browser-plugin
 *
 * Original jquery-browser code Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
 * http://jquery.org/license
 *
 * Modifications Copyright 2013 Gabriel Cebrian
 * https://github.com/gabceb
 *
 * Released under the MIT license
 *
 * Date: 2013-07-29T17:23:27-07:00
 */
(function(e,t,n){"use strict";var r,i;e.uaMatch=function(e){e=e.toLowerCase();var t=/(opr)[\/]([\w.]+)/.exec(e)||/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];var n=/(ipad)/.exec(e)||/(iphone)/.exec(e)||/(android)/.exec(e)||/(win)/.exec(e)||/(mac)/.exec(e)||/(linux)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0",platform:n[0]||""}};r=e.uaMatch(t.navigator.userAgent);i={};if(r.browser){i[r.browser]=true;i.version=r.version}if(r.platform){i[r.platform]=true}if(i.chrome||i.opr){i.webkit=true}else if(i.webkit){i.safari=true}if(i.rv){i.msie=true}if(i.opr){i.opera=true}e.browser=i})(jQuery,window)<commit_msg>Added trailing semicolon on min js file<commit_after>/*!
 * jQuery Browser Plugin v0.0.3
 * https://github.com/gabceb/jquery-browser-plugin
 *
 * Original jquery-browser code Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
 * http://jquery.org/license
 *
 * Modifications Copyright 2013 Gabriel Cebrian
 * https://github.com/gabceb
 *
 * Released under the MIT license
 *
 * Date: 2013-07-29T17:23:27-07:00
 */
(function(e,t,n){"use strict";var r,i;e.uaMatch=function(e){e=e.toLowerCase();var t=/(opr)[\/]([\w.]+)/.exec(e)||/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];var n=/(ipad)/.exec(e)||/(iphone)/.exec(e)||/(android)/.exec(e)||/(win)/.exec(e)||/(mac)/.exec(e)||/(linux)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0",platform:n[0]||""}};r=e.uaMatch(t.navigator.userAgent);i={};if(r.browser){i[r.browser]=true;i.version=r.version}if(r.platform){i[r.platform]=true}if(i.chrome||i.opr){i.webkit=true}else if(i.webkit){i.safari=true}if(i.rv){i.msie=true}if(i.opr){i.opera=true}e.browser=i})(jQuery,window);
<|endoftext|>


<commit_before>/* Flot plugin for drawing all elements of a plot on the canvas.

Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.

Flot normally produces certain elements, like axis labels and the legend, using
HTML elements. This permits greater interactivity and customization, and often
looks better, due to cross-browser canvas text inconsistencies and limitations.

It can also be desirable to render the plot entirely in canvas, particularly
if the goal is to save it as an image, or if Flot is being used in a context
where the HTML DOM does not exist, as is the case within Node.js. This plugin
switches out Flot's standard drawing operations for canvas-only replacements.

Currently the plugin supports only axis labels, but it will eventually allow
every element of the plot to be rendered directly to canvas.

The plugin supports these options:

{
    canvas: boolean
}

The "canvas" option controls whether full canvas drawing is enabled, making it
possible to toggle on and off. This is useful when a plot uses HTML text in the
browser, but needs to redraw with canvas text when exporting as an image.

*/

(function($) {

	var options = {
		canvas: true
	};

	var render, getTextInfo, addText;

	// Cache the prototype hasOwnProperty for faster access

	var hasOwnProperty = Object.prototype.hasOwnProperty;

	function init(plot, classes) {

		var Canvas = classes.Canvas;

		// We only want to replace the functions once; the second time around
		// we would just get our new function back.  This whole replacing of
		// prototype functions is a disaster, and needs to be changed ASAP.

		if (render == null) {
			getTextInfo = Canvas.prototype.getTextInfo,
			addText = Canvas.prototype.addText,
			render = Canvas.prototype.render;
		}

		// Finishes rendering the canvas, including overlaid text

		Canvas.prototype.render = function() {

			if (!plot.getOptions().canvas) {
				return render.call(this);
			}

			var context = this.context,
				cache = this._textCache;

			// For each text layer, render elements marked as active

			context.save();

			// TODO: Comments in Ole's implementation indicate that some
			// browsers differ in their interpretation of 'top'; so far I
			// don't see this, but it requires more testing.  We'll stick
			// with top until this can be verified.

			// Original comment was:
			// Top alignment would be more natural, but browsers can differ a
			// pixel or two in where they consider the top to be, so instead
			// we middle align to minimize variation between browsers and
			// compensate when calculating the coordinates.

			context.textBaseline = "top";

			for (var layerKey in cache) {
				if (hasOwnProperty.call(cache, layerKey)) {
					var layerCache = cache[layerKey];
					for (var styleKey in layerCache) {
						if (hasOwnProperty.call(layerCache, styleKey)) {
							var styleCache = layerCache[styleKey],
								updateStyles = true;
							for (var key in styleCache) {
								if (hasOwnProperty.call(styleCache, key)) {

									var info = styleCache[key];

									if (!info.active) {
										delete styleCache[key];
										continue;
									}

									var x = info.x,
										y = info.y,
										lines = info.lines,
										halign = info.halign;

									// Since every element at this level of the cache have the
									// same font and fill styles, we can just change them once
									// using the values from the first element.

									if (updateStyles) {
										context.fillStyle = info.font.color;
										context.font = info.font.definition;
										updateStyles = false;
									}

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

										var line = lines[i],
											linex = x;

										// Apply horizontal alignment per-line

										if (halign == "center") {
											linex -= line.width / 2;
										} else if (halign == "right") {
											linex -= line.width;
										}

										// FIXME: LEGACY BROWSER FIX
										// AFFECTS: Opera < 12.00

										// Round the coordinates, since Opera otherwise
										// switches to uglier (probably non-hinted) rendering.
										// Also offset the y coordinate, since Opera is off
										// pretty consistently compared to the other browsers.

										if (!!(window.opera && window.opera.version().split(".")[0] < 12)) {
											linex = Math.floor(linex);
											y = Math.ceil(y - 2);
										}

										context.fillText(line.text, Math.round(linex), Math.round(y));
										y += line.height;
									}
								}
							}
						}
					}
				}
			}

			context.restore();
		};

		// Creates (if necessary) and returns a text info object.
		//
		// When the canvas option is set, the object looks like this:
		//
		// {
		//     x: X coordinate at which the text is located.
		//     x: Y coordinate at which the text is located.
		//     width: Width of the text's bounding box.
		//     height: Height of the text's bounding box.
		//     active: Flag indicating whether the text should be visible.
		//     lines: [{
		//         height: Height of this line.
		//         widths: Width of this line.
		//         text: Text on this line.
		//     }],
		//     font: {
		//         definition: Canvas font property string.
		//         color: Color of the text.
		//     },
		// }

		Canvas.prototype.getTextInfo = function(layer, text, font, angle) {

			if (!plot.getOptions().canvas) {
				return getTextInfo.call(this, layer, text, font, angle);
			}

			var textStyle, layerCache, styleCache, info;

			// Cast the value to a string, in case we were given a number

			text = "" + text;

			// If the font is a font-spec object, generate a CSS definition

			if (typeof font === "object") {
				textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family;
			} else {
				textStyle = font;
			}

			// Retrieve (or create) the cache for the text's layer and styles

			layerCache = this._textCache[layer];

			if (layerCache == null) {
				layerCache = this._textCache[layer] = {};
			}

			styleCache = layerCache[textStyle];

			if (styleCache == null) {
				styleCache = layerCache[textStyle] = {};
			}

			info = styleCache[text];

			if (info == null) {

				var context = this.context;

				// If the font was provided as CSS, create a div with those
				// classes and examine it to generate a canvas font spec.

				// Note the trick of using a line-height of 1, without units;
				// this sets it equal to the font-size, even if the font-size
				// is something abstract, like 'smaller'.  This enables us to
				// read the real font-size via the element's height, working
				// around browsers that return the literal 'smaller' value.

				if (typeof font !== "object") {

					var element = $("

")
						.addClass(typeof font === "string" ? font : null)
						.css({ position: "absolute", padding: 0, 'line-height': 1 })
						.appendTo(this.getTextLayer(layer));

					font = {
						style: element.css("font-style"),
						variant: element.css("font-variant"),
						weight: element.css("font-weight"),
						size: element.height(),
						family: element.css("font-family"),
						color: element.css("color")
					};

					element.remove();
				}

				textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family;

				// Create a new info object, initializing the dimensions to
				// zero so we can count them up line-by-line.

				info = styleCache[text] = {
					x: null,
					y: null,
					width: 0,
					height: 0,
					active: false,
					lines: [],
					font: {
						definition: textStyle,
						color: font.color
					}
				};

				context.save();
				context.font = textStyle;

				// Canvas can't handle multi-line strings; break on various
				// newlines, including HTML brs, to build a list of lines.
				// Note that we could split directly on regexps, but IE < 9 is
				// broken; revisit when we drop IE 7/8 support.

				var lines = (text + "").replace(/
|\r\n|\r/g, "\n").split("\n");

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

					var lineText = lines[i],
						measured = context.measureText(lineText),
						lineWidth, lineHeight;

					lineWidth = measured.width;

					// Height might not be defined; not in the standard yet

					lineHeight = measured.height || font.size;

					// Add a bit of margin since font rendering is not pixel
					// perfect and cut off letters look bad.  This also doubles
					// as spacing between lines.

					lineHeight += Math.round(font.size * 0.15);

					info.width = Math.max(lineWidth, info.width);
					info.height += lineHeight;

					info.lines.push({
						text: lineText,
						width: lineWidth,
						height: lineHeight
					});
				}

				context.restore();
			}

			return info;
		};

		// Adds a text string to the canvas text overlay.

		Canvas.prototype.addText = function(layer, x, y, text, font, angle, halign, valign) {

			if (!plot.getOptions().canvas) {
				return addText.call(this, layer, x, y, text, font, angle, halign, valign);
			}

			var info = this.getTextInfo(layer, text, font, angle);

			// Mark the text for inclusion in the next render pass

			info.active = true;

			// Save horizontal alignment for later; we'll apply it per-line

			info.x = x;
			info.halign = halign;

			// Tweak the initial y-position to match vertical alignment

			if (valign == "middle") {
				info.y = y - info.height / 2;
			} else if (valign == "bottom") {
				info.y = y - info.height;
			} else {
				info.y = y;
			}
		};
	}

	$.plot.plugins.push({
		init: init,
		options: options,
		name: "canvas",
		version: "1.0"
	});

})(jQuery);
<commit_msg>Pre-compute coordinates for each line of text.<commit_after>/* Flot plugin for drawing all elements of a plot on the canvas.

Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.

Flot normally produces certain elements, like axis labels and the legend, using
HTML elements. This permits greater interactivity and customization, and often
looks better, due to cross-browser canvas text inconsistencies and limitations.

It can also be desirable to render the plot entirely in canvas, particularly
if the goal is to save it as an image, or if Flot is being used in a context
where the HTML DOM does not exist, as is the case within Node.js. This plugin
switches out Flot's standard drawing operations for canvas-only replacements.

Currently the plugin supports only axis labels, but it will eventually allow
every element of the plot to be rendered directly to canvas.

The plugin supports these options:

{
    canvas: boolean
}

The "canvas" option controls whether full canvas drawing is enabled, making it
possible to toggle on and off. This is useful when a plot uses HTML text in the
browser, but needs to redraw with canvas text when exporting as an image.

*/

(function($) {

	var options = {
		canvas: true
	};

	var render, getTextInfo, addText;

	// Cache the prototype hasOwnProperty for faster access

	var hasOwnProperty = Object.prototype.hasOwnProperty;

	function init(plot, classes) {

		var Canvas = classes.Canvas;

		// We only want to replace the functions once; the second time around
		// we would just get our new function back.  This whole replacing of
		// prototype functions is a disaster, and needs to be changed ASAP.

		if (render == null) {
			getTextInfo = Canvas.prototype.getTextInfo,
			addText = Canvas.prototype.addText,
			render = Canvas.prototype.render;
		}

		// Finishes rendering the canvas, including overlaid text

		Canvas.prototype.render = function() {

			if (!plot.getOptions().canvas) {
				return render.call(this);
			}

			var context = this.context,
				cache = this._textCache;

			// For each text layer, render elements marked as active

			context.save();

			// TODO: Comments in Ole's implementation indicate that some
			// browsers differ in their interpretation of 'top'; so far I
			// don't see this, but it requires more testing.  We'll stick
			// with top until this can be verified.

			// Original comment was:
			// Top alignment would be more natural, but browsers can differ a
			// pixel or two in where they consider the top to be, so instead
			// we middle align to minimize variation between browsers and
			// compensate when calculating the coordinates.

			context.textBaseline = "top";

			for (var layerKey in cache) {
				if (hasOwnProperty.call(cache, layerKey)) {
					var layerCache = cache[layerKey];
					for (var styleKey in layerCache) {
						if (hasOwnProperty.call(layerCache, styleKey)) {
							var styleCache = layerCache[styleKey],
								updateStyles = true;
							for (var key in styleCache) {
								if (hasOwnProperty.call(styleCache, key)) {

									var info = styleCache[key];

									if (!info.active) {
										delete styleCache[key];
										continue;
									}

									// Since every element at this level of the cache have the
									// same font and fill styles, we can just change them once
									// using the values from the first element.

									if (updateStyles) {
										context.fillStyle = info.font.color;
										context.font = info.font.definition;
										updateStyles = false;
									}

									var lines = info.lines;
									for (var i = 0; i < lines.length; ++i) {
										var line = lines[i];
										context.fillText(line.text, line.x, line.y);
									}
								}
							}
						}
					}
				}
			}

			context.restore();
		};

		// Creates (if necessary) and returns a text info object.
		//
		// When the canvas option is set, the object looks like this:
		//
		// {
		//     x: X coordinate at which the text is located.
		//     x: Y coordinate at which the text is located.
		//     width: Width of the text's bounding box.
		//     height: Height of the text's bounding box.
		//     active: Flag indicating whether the text should be visible.
		//     lines: [{
		//         height: Height of this line.
		//         widths: Width of this line.
		//         text: Text on this line.
		//     }],
		//     font: {
		//         definition: Canvas font property string.
		//         color: Color of the text.
		//     },
		// }

		Canvas.prototype.getTextInfo = function(layer, text, font, angle) {

			if (!plot.getOptions().canvas) {
				return getTextInfo.call(this, layer, text, font, angle);
			}

			var textStyle, layerCache, styleCache, info;

			// Cast the value to a string, in case we were given a number

			text = "" + text;

			// If the font is a font-spec object, generate a CSS definition

			if (typeof font === "object") {
				textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family;
			} else {
				textStyle = font;
			}

			// Retrieve (or create) the cache for the text's layer and styles

			layerCache = this._textCache[layer];

			if (layerCache == null) {
				layerCache = this._textCache[layer] = {};
			}

			styleCache = layerCache[textStyle];

			if (styleCache == null) {
				styleCache = layerCache[textStyle] = {};
			}

			info = styleCache[text];

			if (info == null) {

				var context = this.context;

				// If the font was provided as CSS, create a div with those
				// classes and examine it to generate a canvas font spec.

				// Note the trick of using a line-height of 1, without units;
				// this sets it equal to the font-size, even if the font-size
				// is something abstract, like 'smaller'.  This enables us to
				// read the real font-size via the element's height, working
				// around browsers that return the literal 'smaller' value.

				if (typeof font !== "object") {

					var element = $("

")
						.addClass(typeof font === "string" ? font : null)
						.css({ position: "absolute", padding: 0, 'line-height': 1 })
						.appendTo(this.getTextLayer(layer));

					font = {
						style: element.css("font-style"),
						variant: element.css("font-variant"),
						weight: element.css("font-weight"),
						size: element.height(),
						family: element.css("font-family"),
						color: element.css("color")
					};

					element.remove();
				}

				textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family;

				// Create a new info object, initializing the dimensions to
				// zero so we can count them up line-by-line.

				info = styleCache[text] = {
					width: 0,
					height: 0,
					active: false,
					lines: [],
					font: {
						definition: textStyle,
						color: font.color
					}
				};

				context.save();
				context.font = textStyle;

				// Canvas can't handle multi-line strings; break on various
				// newlines, including HTML brs, to build a list of lines.
				// Note that we could split directly on regexps, but IE < 9 is
				// broken; revisit when we drop IE 7/8 support.

				var lines = (text + "").replace(/
|\r\n|\r/g, "\n").split("\n");

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

					var lineText = lines[i],
						measured = context.measureText(lineText),
						lineWidth, lineHeight;

					lineWidth = measured.width;

					// Height might not be defined; not in the standard yet

					lineHeight = measured.height || font.size;

					// Add a bit of margin since font rendering is not pixel
					// perfect and cut off letters look bad.  This also doubles
					// as spacing between lines.

					lineHeight += Math.round(font.size * 0.15);

					info.width = Math.max(lineWidth, info.width);
					info.height += lineHeight;

					info.lines.push({
						text: lineText,
						width: lineWidth,
						height: lineHeight
					});
				}

				context.restore();
			}

			return info;
		};

		// Adds a text string to the canvas text overlay.

		Canvas.prototype.addText = function(layer, x, y, text, font, angle, halign, valign) {

			if (!plot.getOptions().canvas) {
				return addText.call(this, layer, x, y, text, font, angle, halign, valign);
			}

			var info = this.getTextInfo(layer, text, font, angle);

			// Mark the text for inclusion in the next render pass

			info.active = true;

			// Tweak the initial y-position to match vertical alignment

			if (valign == "middle") {
				y = Math.round(y - info.height / 2);
			} else if (valign == "bottom") {
				y = Math.round(y - info.height);
			} else {
				y = Math.round(y);
			}

			// FIXME: LEGACY BROWSER FIX
			// AFFECTS: Opera < 12.00

			// Offset the y coordinate, since Opera is off pretty
			// consistently compared to the other browsers.

			if (!!(window.opera && window.opera.version().split(".")[0] < 12)) {
				y -= 2;
			}

			// Fill in the x & y positions of each line, adjusting them
			// individually for horizontal alignment.

			var lines = info.lines;
			for (var i = 0; i < lines.length; ++i) {
				var line = lines[i];
				line.y = y;
				y += line.height;
				if (halign == "center") {
					line.x = Math.round(x - line.width / 2);
				} else if (halign == "right") {
					line.x = Math.round(x - line.width);
				} else {
					line.x = Math.round(x);
				}
			}
		};
	}

	$.plot.plugins.push({
		init: init,
		options: options,
		name: "canvas",
		version: "1.0"
	});

})(jQuery);
<|endoftext|>


<commit_before>"use strict";

// module Data.Show

exports.showIntImpl = function (n) {
  return n.toString();
};

exports.showNumberImpl = function (n) {
  /* jshint bitwise: false */
  return n === (n | 0) ? n + ".0" : n.toString();
};

exports.showCharImpl = function (c) {
  var code = c.charCodeAt(0);
  if (code < 0x20 || code === 0x7F) {
    switch (c) {
      case "\x07": return "'\\a'";
      case "\b": return "'\\b'";
      case "\f": return "'\\f'";
      case "\n": return "'\\n'";
      case "\r": return "'\\r'";
      case "\t": return "'\\t'";
      case "\v": return "'\\v'";
    }
    return "'\\" + code.toString(10) + "'";
  }
  return c === "'" || c === "\\" ? "'\\" + c + "'" : "'" + c + "'";
};

exports.showStringImpl = function (s) {
  var l = s.length;
  return "\"" + s.replace(
    /[\0-\x1F\x7F"\\]/g,
    function (c, i) { // jshint ignore:line
      switch (c) {
        case "\"":
        case "\\":
          return "\\" + c;
        case "\x07": return "\\a";
        case "\b": return "\\b";
        case "\f": return "\\f";
        case "\n": return "\\n";
        case "\r": return "\\r";
        case "\t": return "\\t";
        case "\v": return "\\v";
      }
      var k = i + 1;
      var empty = k < l && s[k] >= "0" && s[k] <= "9" ? "\\&" : "";
      return "\\" + c.charCodeAt(0).toString(10) + empty;
    }
  ) + "\"";
};

exports.showArrayImpl = function (f) {
  return function (xs) {
    var ss = [];
    for (var i = 0, l = xs.length; i < l; i++) {
      ss[i] = f(xs[i]);
    }
    return "[" + ss.join(",") + "]";
  };
};
<commit_msg>Fix Show Number for integers outside the Int range<commit_after>"use strict";

// module Data.Show

exports.showIntImpl = function (n) {
  return n.toString();
};

exports.showNumberImpl = function (n) {
  var str = n.toString();
  return str.indexOf("e") === -1 && str.indexOf(".") === -1 ?
            str + ".0" :
            str;
};

exports.showCharImpl = function (c) {
  var code = c.charCodeAt(0);
  if (code < 0x20 || code === 0x7F) {
    switch (c) {
      case "\x07": return "'\\a'";
      case "\b": return "'\\b'";
      case "\f": return "'\\f'";
      case "\n": return "'\\n'";
      case "\r": return "'\\r'";
      case "\t": return "'\\t'";
      case "\v": return "'\\v'";
    }
    return "'\\" + code.toString(10) + "'";
  }
  return c === "'" || c === "\\" ? "'\\" + c + "'" : "'" + c + "'";
};

exports.showStringImpl = function (s) {
  var l = s.length;
  return "\"" + s.replace(
    /[\0-\x1F\x7F"\\]/g,
    function (c, i) { // jshint ignore:line
      switch (c) {
        case "\"":
        case "\\":
          return "\\" + c;
        case "\x07": return "\\a";
        case "\b": return "\\b";
        case "\f": return "\\f";
        case "\n": return "\\n";
        case "\r": return "\\r";
        case "\t": return "\\t";
        case "\v": return "\\v";
      }
      var k = i + 1;
      var empty = k < l && s[k] >= "0" && s[k] <= "9" ? "\\&" : "";
      return "\\" + c.charCodeAt(0).toString(10) + empty;
    }
  ) + "\"";
};

exports.showArrayImpl = function (f) {
  return function (xs) {
    var ss = [];
    for (var i = 0, l = xs.length; i < l; i++) {
      ss[i] = f(xs[i]);
    }
    return "[" + ss.join(",") + "]";
  };
};
<|endoftext|>