<commit_before>import Ember from 'ember';
import layout from '../templates/components/ember-lxl';
import {
  keyDown,
  EKMixin
} from 'ember-keyboard';

const second = 1000;
const lxlTagClass = 'lxl-tag';
const wordClass = 'lxl-word';
const letterClass = 'lxl-letter';

const htmlTagRegex = '<.*?>';
const lxlTagRegex = '\\(\\([#\\/].*?\\)\\)';

const {
  Component,
  computed,
  get,
  getProperties,
  isBlank,
  isPresent,
  set,
  setProperties
} = Ember;

const { String: { htmlSafe } } = Ember;
const { run: { later } } = Ember;
const { or } = computed;

export default Component.extend(EKMixin, {
  layout,

  keys: [],
  effect: {},
  cps: 25,
  tweenRate: 25,

  activeWordIndex: 0,
  classNames: ['lxl-container'],

  isInstant: or('instantWritePage', 'instantWriteText'),

  didInsertElement(...args) {
    this._super(...args);

    this._bindKeys();
    this._bindResize();
    this._scrollToFirstWord();
  },

  _bindKeys() {
    const keys = get(this, 'keys');

    keys.forEach((key) => {
      this.on(keyDown(key), this._advanceText);
    });
  },

  _bindResize() {
    const resizeService = get(this, 'resizeService');

    if (isPresent(resizeService)) {
      resizeService.on('debouncedDidResize', () => {
        const currentPageFirstWord = get(this, 'currentPageFirstWord');

        this._scrollToWord(currentPageFirstWord);
      });
    }
  },

  _scrollToFirstWord() {
    const $words = get(this, '$words');
    const firstWord = $words.first();

    this._scrollToWord(firstWord);

    set(this, 'currentPageFirstWord', firstWord);
  },

  mouseUp(...args) {
    this._super(...args);

    this._pressEvent(...args);
  },

  touchEnd(...args) {
    this._super(...args);

    this._pressEvent(...args);
  },

  _pressEvent(event) {
    // do nothing on right-click or mouse wheel or combo
    if (event.buttons > 1) { return; }

    // do nothing if the text contains highlighted text
    if (!window.getSelection().isCollapsed) { return; }

    this._advanceText(event);
  },

  _advanceText(event) {
    if (event) {
      event.preventDefault();
    }

    if (get(this, 'pageLoaded')) {
      this._turnPage();
    } else {
      set(this, 'instantWritePage', true);
    }
  },

  _turnPage() {
    const nextPageFirstWord = get(this, 'nextPageFirstWord');

    set(this, 'currentPageFirstWord', nextPageFirstWord);

    this._scrollToWord(nextPageFirstWord);

    if (isBlank(nextPageFirstWord) && this.attrs.onComplete) {
      this.attrs.onComplete();
    }
  },

  _scrollToWord(word) {
    const $words = get(this, '$words');
    const $container = this.$();
    const $word = this.$(word);
    const scrollTop = $word.offset().top - $container.offset().top + $container.scrollTop();

    $container.scrollTop(scrollTop);

    set(this, 'nextPageFirstWord', this._findNextPageFirstWord());

    this._processWord($words.index($word));
  },

  _findNextPageFirstWord() {
    const {
      currentPageLastWordIndex,
      wordElements
    } = getProperties(this, 'currentPageLastWordIndex', 'wordElements');
    const $container = this.$().parent();
    const offsetBottom = $container.offset().top + $container.height();

    return wordElements.slice(currentPageLastWordIndex + 1).find((element) => {
      const $element = this.$(element);

      return $element.offset().top + $element.height() >= offsetBottom;
    });
  },

  words: computed('text', {
    get() {
      // the first part of the regex matches html tags (eg, `<strong>`), the second part lxl-text-tags,
      // and the last part matches and removes spaces, as we break on spaces to capture words.
      const regex = new RegExp(`${htmlTagRegex}|${lxlTagRegex}|[^<\\s]+`, 'g');

      return Ember.A(get(this, 'text').match(regex));
    }
  }).readOnly(),

  formattedText: computed('words.[]', {
    get() {
      return htmlSafe(get(this, 'words').map((word) => {
        // test if the word is actually a tag
        return new RegExp(htmlTagRegex).test(word) ? word :
          new RegExp(lxlTagRegex).test(word) ?
          `<span class="${lxlTagClass} ${wordClass}" aria-hidden="true">${word}</span>` :
          `<span class="${wordClass}">${word}</span>`;
      }).join(' '));
    }
  }).readOnly(),

  $words: computed('formattedText', {
    get() {
      return this.$(`span.${wordClass}`);
    }
  }).readOnly(),

  wordElements: computed('$words', {
    get() {
      return Ember.A(get(this, '$words').toArray());
    }
  }).readOnly(),

  _processWord(index) {
    const $words = get(this, '$words');

    if (isBlank($words)) { return; }

    const $word = $words.eq(index);
    const nextPageFirstWord = get(this, 'nextPageFirstWord');

    // stop if the word has already been written
    if ($word.css('opacity') === '1') { return; }

    const pageIsLoaded =
      index >= $words.length ||
      (isPresent(nextPageFirstWord) && index >= $words.index(nextPageFirstWord));

    if (pageIsLoaded) {
      this._markPageAsComplete(index);
    } else {
      set(this, 'pageLoaded', false);

      this._writeWord($word, index);
    }
  },

  _markPageAsComplete(currentPageLastWordIndex) {
    setProperties(this, {
      currentPageLastWordIndex,
      pageLoaded: true
    });

    if (!get(this, 'instantWriteText')) {
      set(this, 'instantWritePage', false);
    }
  },

  _writeWord($word, index) {
    if ($word.hasClass(lxlTagClass)) {
      this._executeCustomTag($word.text(), index);
    } else if (get(this, 'isInstant')) {
      this._processWord(index + 1);
    } else {
      const letters = $word.text().split('');

      $word.html(letters.map((letter) => `<span class="${letterClass}">${letter}</span>`).join(''));
      this._writeLetter($word, letters.length, 0, index);
    }

    $word.css('opacity', 1);
  },

  _writeLetter($word, wordLength, characterIndex, wordIndex) {
    if (get(this, 'isInstant')) { return this._shortCircuitWord($word, wordIndex); }

    const { cpsRate, effect, tweenDuration } = getProperties(this, 'cpsRate', 'effect', 'tweenDuration');
    const $letter = $word.find(`span.${letterClass}:eq(${characterIndex})`);

    effect.opacity = effect.opacity ? effect.opacity : { to: 1, from: 0 };

    motion.tween({
      values: effect,
      duration: tweenDuration
    }).on($letter[0]).start();

    later(() => {
      if (characterIndex + 1 < wordLength) {
        this._writeLetter($word, wordLength, characterIndex + 1, wordIndex);
      } else {
        this._processWord(wordIndex + 1);
      }
    }, cpsRate);
  },

  cpsRate: computed('cps', {
    get() {
      return second / get(this, 'cps');
    }
  }),

  tweenDuration: computed('cpsRate', 'tweenRate', {
    get() {
      return get(this, 'cpsRate') * get(this, 'tweenRate');
    }
  }),

  _shortCircuitWord($word, wordIndex) {
    const text = $word.text().trim();

    $word.html(text);

    this._processWord(wordIndex + 1);
  },

  _executeCustomTag(text, index) {
    const [, openingOrClosing, content] = text.match(/\(\((#|\/)(.*?)\)\)/);
    const args = content.split(' ');
    const tagName = args.shift();
    const tag = this[tagName].create();
    const method = openingOrClosing === '#' ? 'start' : 'stop';

    tag[method](this, index, ...args.join(' ').split('|'));
  }
});
<commit_msg>function shuffle<commit_after>import Ember from 'ember';
import layout from '../templates/components/ember-lxl';
import {
  keyDown,
  EKMixin
} from 'ember-keyboard';

const second = 1000;
const lxlTagClass = 'lxl-tag';
const wordClass = 'lxl-word';
const letterClass = 'lxl-letter';

const htmlTagRegex = '<.*?>';
const lxlTagRegex = '\\(\\([#\\/].*?\\)\\)';

const {
  Component,
  computed,
  get,
  getProperties,
  isBlank,
  isPresent,
  set,
  setProperties
} = Ember;

const { String: { htmlSafe } } = Ember;
const { run: { later } } = Ember;
const { or } = computed;

export default Component.extend(EKMixin, {
  layout,

  keys: [],
  effect: {},
  cps: 25,
  tweenRate: 25,

  activeWordIndex: 0,
  classNames: ['lxl-container'],

  isInstant: or('instantWritePage', 'instantWriteText'),

  didInsertElement(...args) {
    this._super(...args);

    this._bindKeys();
    this._bindResize();
    this._scrollToFirstWord();
  },

  _bindKeys() {
    const keys = get(this, 'keys');

    keys.forEach((key) => {
      this.on(keyDown(key), this._advanceText);
    });
  },

  _bindResize() {
    const resizeService = get(this, 'resizeService');

    if (isPresent(resizeService)) {
      resizeService.on('debouncedDidResize', () => {
        const currentPageFirstWord = get(this, 'currentPageFirstWord');

        this._scrollToWord(currentPageFirstWord);
      });
    }
  },

  _scrollToFirstWord() {
    const $words = get(this, '$words');
    const firstWord = $words.first();

    this._scrollToWord(firstWord);

    set(this, 'currentPageFirstWord', firstWord);
  },

  mouseUp(...args) {
    this._super(...args);

    this._pressEvent(...args);
  },

  touchEnd(...args) {
    this._super(...args);

    this._pressEvent(...args);
  },

  _pressEvent(event) {
    // do nothing on right-click or mouse wheel or combo
    if (event.buttons > 1) { return; }

    // do nothing if the text contains highlighted text
    if (!window.getSelection().isCollapsed) { return; }

    this._advanceText(event);
  },

  _advanceText(event) {
    if (event) {
      event.preventDefault();
    }

    if (get(this, 'pageLoaded')) {
      this._turnPage();
    } else {
      set(this, 'instantWritePage', true);
    }
  },

  _turnPage() {
    const nextPageFirstWord = get(this, 'nextPageFirstWord');

    set(this, 'currentPageFirstWord', nextPageFirstWord);

    this._scrollToWord(nextPageFirstWord);

    if (isBlank(nextPageFirstWord) && this.attrs.onComplete) {
      this.attrs.onComplete();
    }
  },

  _scrollToWord(word) {
    const $words = get(this, '$words');
    const $container = this.$();
    const $word = this.$(word);
    const scrollTop = $word.offset().top - $container.offset().top + $container.scrollTop();

    $container.scrollTop(scrollTop);

    set(this, 'nextPageFirstWord', this._findNextPageFirstWord());

    this._processWord($words.index($word));
  },

  _findNextPageFirstWord() {
    const {
      currentPageLastWordIndex,
      wordElements
    } = getProperties(this, 'currentPageLastWordIndex', 'wordElements');
    const $container = this.$().parent();
    const offsetBottom = $container.offset().top + $container.height();

    return wordElements.slice(currentPageLastWordIndex + 1).find((element) => {
      const $element = this.$(element);

      return $element.offset().top + $element.height() >= offsetBottom;
    });
  },

  cpsRate: computed('cps', {
    get() {
      return second / get(this, 'cps');
    }
  }),

  tweenDuration: computed('cpsRate', 'tweenRate', {
    get() {
      return get(this, 'cpsRate') * get(this, 'tweenRate');
    }
  }),

  words: computed('text', {
    get() {
      // the first part of the regex matches html tags (eg, `<strong>`), the second part lxl-text-tags,
      // and the last part matches and removes spaces, as we break on spaces to capture words.
      const regex = new RegExp(`${htmlTagRegex}|${lxlTagRegex}|[^<\\s]+`, 'g');

      return Ember.A(get(this, 'text').match(regex));
    }
  }).readOnly(),

  formattedText: computed('words.[]', {
    get() {
      return htmlSafe(get(this, 'words').map((word) => {
        // test if the word is actually a tag
        return new RegExp(htmlTagRegex).test(word) ? word :
          new RegExp(lxlTagRegex).test(word) ?
          `<span class="${lxlTagClass} ${wordClass}" aria-hidden="true">${word}</span>` :
          `<span class="${wordClass}">${word}</span>`;
      }).join(' '));
    }
  }).readOnly(),

  $words: computed('formattedText', {
    get() {
      return this.$(`span.${wordClass}`);
    }
  }).readOnly(),

  wordElements: computed('$words', {
    get() {
      return Ember.A(get(this, '$words').toArray());
    }
  }).readOnly(),

  _processWord(index) {
    const $words = get(this, '$words');

    if (isBlank($words)) { return; }

    const $word = $words.eq(index);
    const nextPageFirstWord = get(this, 'nextPageFirstWord');

    // stop if the word has already been written
    if ($word.css('opacity') === '1') { return; }

    const pageIsLoaded =
      index >= $words.length ||
      (isPresent(nextPageFirstWord) && index >= $words.index(nextPageFirstWord));

    if (pageIsLoaded) {
      this._markPageAsComplete(index);
    } else {
      set(this, 'pageLoaded', false);

      this._writeWord($word, index);
    }
  },

  _markPageAsComplete(currentPageLastWordIndex) {
    setProperties(this, {
      currentPageLastWordIndex,
      pageLoaded: true
    });

    if (!get(this, 'instantWriteText')) {
      set(this, 'instantWritePage', false);
    }
  },

  _writeWord($word, index) {
    if ($word.hasClass(lxlTagClass)) {
      this._executeCustomTag($word.text(), index);
    } else if (get(this, 'isInstant')) {
      this._processWord(index + 1);
    } else {
      const letters = $word.text().split('');

      $word.html(letters.map((letter) => `<span class="${letterClass}">${letter}</span>`).join(''));
      this._writeLetter($word, letters.length, 0, index);
    }

    $word.css('opacity', 1);
  },

  _writeLetter($word, wordLength, characterIndex, wordIndex) {
    if (get(this, 'isInstant')) { return this._shortCircuitWord($word, wordIndex); }

    const { cpsRate, effect, tweenDuration } = getProperties(this, 'cpsRate', 'effect', 'tweenDuration');
    const $letter = $word.find(`span.${letterClass}:eq(${characterIndex})`);

    effect.opacity = effect.opacity ? effect.opacity : { to: 1, from: 0 };

    motion.tween({
      values: effect,
      duration: tweenDuration
    }).on($letter[0]).start();

    later(() => {
      if (characterIndex + 1 < wordLength) {
        this._writeLetter($word, wordLength, characterIndex + 1, wordIndex);
      } else {
        this._processWord(wordIndex + 1);
      }
    }, cpsRate);
  },

  _shortCircuitWord($word, wordIndex) {
    const text = $word.text().trim();

    $word.html(text);

    this._processWord(wordIndex + 1);
  },

  _executeCustomTag(text, index) {
    const [, openingOrClosing, content] = text.match(/\(\((#|\/)(.*?)\)\)/);
    const args = content.split(' ');
    const tagName = args.shift();
    const tag = this[tagName].create();
    const method = openingOrClosing === '#' ? 'start' : 'stop';

    tag[method](this, index, ...args.join(' ').split('|'));
  }
});
<|endoftext|>


<commit_before>'use strict'

var _ = require('lodash');

const LEFT = 0;
const RIGHT = 1;
const TOP = 2;
const BOTTOM = 3;

function process(result){
	const maxPart = Math.min(result.tomatoesCpt, result.mushroomsCpt);
	let arraySlices = new Array();
	const type = result.tomatoesCpt < result.mushroomsCpt ? 'T' : 'M';
	const oppositeType = result.tomatoesCpt < result.mushroomsCpt ? 'M' : 'T';
	for(let row=0; row < result.R; row++){
		for(let col=0; col < result.C; col++){
			let arrayTmp = searchForCell({
				type: type,
				oppositeType: oppositeType,
				result: result,
				row: row,
				col:col
			});
			if (arrayTmp && arrayTmp.length>0){
				arraySlices =  _.concat(arraySlices, arrayTmp);
			}
		}
	}

	const groupArray = _.groupBy(arraySlices,'key');

	_.mapValues(groupArray, (slice) => {
		console.log(slice);
	});

}

function searchForCell({type, oppositeType, result, row, col}){
	const arraySlices = new Array();
	if (result.rows[row].detail[col] === type){
		// cell upside
		if (row > 0 && result.rows[row-1].detail[col] === oppositeType){
			arraySlices.push(addSlice({
				col:col,
				row:row,
				position:TOP
			}));
		}
		// cell downside
		if (row < result.R && result.rows[row+1].detail[col] === oppositeType){
			arraySlices.push(addSlice({
				col:col,
				row:row,
				position:BOTTOM
			}));
		}
		//cell left
		if (col > 0 && result.rows[row].detail[col-1] === oppositeType){
			arraySlices.push(addSlice({
				col:col,
				row:row,
				position:LEFT
			}));
		}
		//cell right
		if (col < result.C && result.rows[row].detail[col+1] === oppositeType){
			arraySlices.push(addSlice({
				col:col,
				row:row,
				position:RIGHT
			}));
		}

		return arraySlices;
	}
}

function addSlice({col, row, position}){
	return {
		key: `col:${col}|row:${row}`,
		origin: {
			x: col,
			y: row
		},
		top: {
			x: (position === LEFT ?col -1 : col),
			y: (position === TOP ? row -1 : row)
		},
		bottom: {
			x: (position === RIGHT ?col +1 : col),
			y: (position === BOTTOM ? row +1 : row)
		}
	}
}

function tomatoesInferior(result){
	return result.tomatoesCpt < result.mushroomsCpt;
}

module.exports = {
	process : process
}<commit_msg>FuuuuuUuUUUU<commit_after>'use strict'

var _ = require('lodash');

const LEFT = 0;
const RIGHT = 1;
const TOP = 2;
const BOTTOM = 3;

function process(result){
	const maxPart = Math.min(result.tomatoesCpt, result.mushroomsCpt);
	let arraySlices = new Array();
	const type = result.tomatoesCpt < result.mushroomsCpt ? 'T' : 'M';
	const oppositeType = result.tomatoesCpt < result.mushroomsCpt ? 'M' : 'T';
	for(let row=0; row < result.R; row++){
		for(let col=0; col < result.C; col++){
			let arrayTmp = searchForCell({
				type: type,
				oppositeType: oppositeType,
				result: result,
				row: row,
				col:col
			});
			if (arrayTmp && arrayTmp.length>0){
				arraySlices =  _.concat(arraySlices, arrayTmp);
			}
		}
	}

	const groupArray = _.groupBy(arraySlices,'key');
	const intersect = _.intersectionWith(arraySlices, arraySlices, (value, other) => {

		if (value.key === 'col:3|row:1' && other.key === 'col:5|row:1'){
			console.log('Value', value, 'Other', other);
			console.log(other.top.x > value.bottom.x+1 ||
           	other.bottom.x+1 < value.top.x ||
           	other.top.y > value.bottom.y+1 ||
           	other.bottom.y+1 < value.top.y);
		}

		return
			other.top.x > value.bottom.x+1 ||
           	other.bottom.x+1 < value.top.x ||
           	other.top.y > value.bottom.y+1 ||
           	other.bottom.y+1 < value.top.y
	});
	console.log(intersect);
	const groupIntersect = _.groupBy(intersect, 'key');
	console.log('intersect');
	_.mapValues(groupIntersect, (elt) => {
		console.log(elt);
	});

	/*console.log('grouped');
	_.mapValues(groupArray, (slice) => {
		console.log(slice);
	});*/

}

function searchForCell({type, oppositeType, result, row, col}){
	const arraySlices = new Array();
	if (result.rows[row].detail[col] === type){
		// cell upside
		if (row > 0 && result.rows[row-1].detail[col] === oppositeType){
			arraySlices.push(addSlice({
				col:col,
				row:row,
				position:TOP
			}));
		}
		// cell downside
		if (row+1 < +result.R && result.rows[row+1].detail[col] === oppositeType){
			arraySlices.push(addSlice({
				col:col,
				row:row,
				position:BOTTOM
			}));
		}
		//cell left
		if (col > 0 && result.rows[row].detail[col-1] === oppositeType){
			arraySlices.push(addSlice({
				col:col,
				row:row,
				position:LEFT
			}));
		}
		//cell right
		if (col+1 < +result.C && result.rows[row].detail[col+1] === oppositeType){
			arraySlices.push(addSlice({
				col:col,
				row:row,
				position:RIGHT
			}));
		}

		return arraySlices;
	}
}

function addSlice({col, row, position}){
	return {
		key: `col:${col}|row:${row}`,
		origin: {
			x: col,
			y: row
		},
		top: {
			x: (position === LEFT ?col -1 : col),
			y: (position === TOP ? row -1 : row)
		},
		bottom: {
			x: (position === RIGHT ?col +1 : col),
			y: (position === BOTTOM ? row +1 : row)
		}
	}
}

function tomatoesInferior(result){
	return result.tomatoesCpt < result.mushroomsCpt;
}

module.exports = {
	process : process
}<|endoftext|>


<commit_before>// redis.js - a Redis client for server-side JavaScript, in particular Node
// which runs atop Google V8.
//
// Please review the Redis command reference and protocol specification:
//
// http://code.google.com/p/redis/wiki/CommandReference
// http://code.google.com/p/redis/wiki/ProtocolSpecification
//
// This implementation should make for easy maintenance given that Redis
// commands follow only a couple of conventions.  To add support for a new
// command, simply add the name to either 'inlineCommands' or 'bulkCommands'
// below.
//
// Replies are handled generically and shouldn't need any updates unless Redis
// adds a completely new response type (other than status code, integer, error,
// bulk, and multi-bulk).  See http://code.google.com/p/redis/wiki/ReplyTypes
//
// To learn more about Node and Google V8, see http://tinyclouds.org/node/ and
// http://code.google.com/p/v8/ respectively.
//
// Brian Hammond, Fictorial
//
// Thanks to:
// - Elliott Cable for Node.js 0.1.7 API changes and unit test enhancements.

var DEFAULT_PORT = 6379;

var sys = require("sys");
var tcp = require("tcp");

var conn = new process.tcp.Connection();

// Connect to redis server.  This is most commonly to a redis-server instance
// running on the same host.

exports.connect = function(onConnect, port, host) {
  port = port || DEFAULT_PORT;
  host = host || '127.0.0.1';

  writeDebugMessage('connecting to ' + host + ':' + port);

  conn.connect(port, host);

  conn.addListener("connect", function(){
    conn.setEncoding("utf8");
    if (typeof(onConnect) == "function")
      onConnect();
  });
}

var CRLF = "\r\n";
var CRLF_LENGTH = 2;

// Commands supported by Redis 1.0
//
// Note: 'sort', 'quit', and 'slaveof' are handled as special cases.
//
// Note: 'monitor' is not included as that's generally only used
// in a telnet connection to the redis-server instance.

var inlineCommands = {
  auth:1,
  bgsave:1,
  dbsize:1,
  decr:1,
  decrby:1,
  del:1,
  exists:1,
  expire:1,
  flushall:1,
  flushdb:1,
  get:1,
  incr:1,
  incrby:1,
  info:1,
  keys:1,
  lastsave:1,
  lindex:1,
  llen:1,
  lpop:1,
  lrange:1,
  ltrim:1,
  mget:1,
  move:1,
  randomkey:1,
  rename:1,
  renamenx:1,
  rpop:1,
  save:1,
  scard:1,
  sdiff:1,
  sdiffstore:1,
  select:1,
  shutdown:1,
  sinter:1,
  sinterstore:1,
  smembers:1,
  spop:1,
  sunion:1,
  sunionstore:1,
  ttl:1,
  type:1,
};

var bulkCommands = {
  getset:1,
  lpush:1,
  lrem:1,
  lset:1,
  rpush:1,
  sadd:1,
  set:1,
  setnx:1,
  sismember:1,
  smove:1,
  srem:1,
};

// callbacks:
// Node is event driven / asynchronous with respect to all I/O.  Thus, we call
// user code back when we parse Redis responses.  Note: redis responds in the
// same order as commands are sent.  Thus, pipelining is perfectly valid.  See
// the unit test(s) for examples of callbacks.

var callbacks = [];

exports.debugMode = true;

function writeDebugMessage(data) {
  if (!exports.debugMode || !data)
    return;

  sys.debug(data.replace(/\r\n/g, '\\r\\n'));
}

function fatal(errorMessage) {
  writeDebugMessage("\n\nFATAL: " + errorMessage + "\n");
  throw errorMessage;
}

function maybeConvertToNumber(str) {
  if (/^\s*\d+\s*$/.test(str))
    return parseInt(str, 10);

  if (/^\s*\d+\.(\d+)?\s*$/.test(str))
    return parseFloat(str);

  return str;
}

// Format an inline redis command.
// See http://code.google.com/p/redis/wiki/ProtocolSpecification#Simple_INLINE_commands

function formatInline(commandName, commandArgs, argCount) {
  var str = commandName;

  for (var i = 0; i < argCount; ++i)
    str += ' ' + commandArgs[i];

  return str + CRLF;
}

// Format a bulk redis command.
// e.g. lset key index value => lset key index value-length\r\nvalue\r\n
// where lset is commandName; key, index, and value are commandArgs
// See http://code.google.com/p/redis/wiki/ProtocolSpecification#Bulk_commands

function formatBulk(commandName, commandArgs, argCount) {
  var args = commandName;

  for (var i = 0; i < argCount - 1; ++i) {
    var val = typeof(commandArgs[i]) != 'string'
      ? commandArgs[i].toString()
      : commandArgs[i];

    args += ' ' + val;
  }

  var lastArg = typeof(commandArgs[argCount - 1]) != 'string'
    ? commandArgs[argCount - 1].toString()
    : commandArgs[argCount - 1];

  var cmd = args + ' ' + lastArg.length + CRLF + lastArg + CRLF;

  return cmd;
}

// Creates a function to send a command to the redis server.

function createCommandSender(commandName) {
  return function() {
    if (conn.readyState != "open")
      fatal("connection is not open");

    // last arg (if any) should be callback function.

    var callback = null;
    var numArgs = arguments.length;

    if (typeof(arguments[arguments.length - 1]) == 'function') {
      callback = arguments[arguments.length - 1];
      numArgs = arguments.length - 1;
    }

    // Format the command and send it.

    var cmd;

    if (inlineCommands[commandName]) {
      cmd = formatInline(commandName, arguments, numArgs);
    } else if (bulkCommands[commandName]) {
      cmd = formatBulk(commandName, arguments, numArgs);
    } else {
      fatal('unknown command ' + commandName);
    }

    writeDebugMessage('> ' + cmd);

    // Always push something, even if its null.
    // We need received replies to match number of entries in `callbacks`.

    callbacks.push({ cb:callback, cmd:commandName.toLowerCase() });
    conn.send(cmd);
  };
}

// Create command senders for all commands.

for (var commandName in inlineCommands)
  exports[commandName] = createCommandSender(commandName);

for (var commandName in bulkCommands)
  exports[commandName] = createCommandSender(commandName);

// All reply handlers are passed the full received data which may contain
// multiple replies.  Each should return [ result, offsetOfFollowingReply ]

function handleBulkReply(reply, offset) {
  ++offset; // skip '$'

  var crlfIndex = reply.indexOf(CRLF, offset);
  var valueLength = parseInt(reply.substr(offset, crlfIndex - offset), 10);

  if (valueLength == -1)
    return [ null, crlfIndex + CRLF_LENGTH ];

  var value = reply.substr(crlfIndex + CRLF_LENGTH, valueLength);

  var nextOffset = crlfIndex   + CRLF_LENGTH +
                   valueLength + CRLF_LENGTH;

  return [ value, nextOffset ];
}

function handleMultiBulkReply(reply, offset) {
  ++offset; // skip '*'

  var crlfIndex = reply.indexOf(CRLF, offset);
  var count = parseInt(reply.substr(offset, crlfIndex - offset), 10);

  offset = crlfIndex + CRLF_LENGTH;

  if (count === -1)
    return [ null, offset ];

  var entries = [];

  for (var i = 0; i < count; ++i) {
    var bulkReply = handleBulkReply(reply, offset);
    entries.push(bulkReply[0]);
    offset = bulkReply[1];
  }

  return [ entries, offset ];
}

function handleSingleLineReply(reply, offset) {
  ++offset; // skip '+'

  var crlfIndex = reply.indexOf(CRLF, offset);
  var value = reply.substr(offset, crlfIndex - offset);

  // Most single-line replies are '+OK' so convert such to a true value.

  if (value === 'OK')
    value = true;

  return [ value, crlfIndex + CRLF_LENGTH ];
}

function handleIntegerReply(reply, offset) {
  ++offset; // skip ':'

  var crlfIndex = reply.indexOf(CRLF, offset);

  return [ parseInt(reply.substr(offset, crlfIndex - offset), 10),
           crlfIndex + CRLF_LENGTH ];
}

function handleErrorReply(reply, offset) {
  ++offset; // skip '-'

  var crlfIndex = reply.indexOf(CRLF, offset);

  var errorMessage = (reply.indexOf("ERR ") != 0)
    ? "something bad happened: " + reply.substr(offset, crlfIndex - offset)
    : reply.substr(4, crlfIndex - 4);

  fatal(errorMessage);
}

// See http://code.google.com/p/redis/wiki/ReplyTypes

var replyPrefixToHandler = {
  '$': handleBulkReply,
  '*': handleMultiBulkReply,
  '+': handleSingleLineReply,
  ':': handleIntegerReply,
  '-': handleErrorReply
};

// INFO output is an object with properties for each server metadatum.
// KEYS output is a list (which is more intuitive than a ws-delimited string).

function postProcessResults(command, result) {
  switch (command) {
  case 'info':
    var infoObject = {};

    result.split('\r\n').forEach(function(line) {
      var parts = line.split(':');
      if (parts.length == 2)
        infoObject[parts[0]] = maybeConvertToNumber(parts[1]);
    });

    result = infoObject;
    break;

  case 'keys':
    result = result.split(' ');
    break;

  case 'lastsave':
    result = maybeConvertToNumber(result);
    break;

  default:
    break;
  }

  return result;
}

conn.addListener("receive", function(data){
  if (exports.writeDebugMessageMode)
    writeDebugMessage('< ' + data);

  if (data.length == 0)
    fatal("empty response");

  var offset = 0;

  while (offset < data.length) {
    var replyPrefix = data.charAt(offset);
    var replyHandler = replyPrefixToHandler[replyPrefix];

    if (!replyHandler)
      fatal("unknown prefix " + replyPrefix + " in reply @ offset " + offset);

    var resultInfo = replyHandler(data, offset);
    var result = resultInfo[0];
    offset = resultInfo[1];

    var callback = callbacks.shift();
    if (callback && callback.cb) {
      result = postProcessResults(callback.cmd, result);
      callback.cb(result);
    }
  }
});

// Read this first: http://code.google.com/p/redis/wiki/SortCommand
// options is an object which can have the following properties:
//   'byPattern': 'pattern'
//   'limit': [start, end]
//   'getPatterns': [ 'pattern', 'pattern', ... ]
//   'ascending': true|false
//   'lexicographically': true|false

exports.sort = function(key, options, callback) {
  if (conn.readyState != "open")
    fatal("connection is not open");

  var cmd = 'sort ' + key;

  if (typeof(options) == 'object') {
    var optBy = options.byPattern ? ('by ' + options.byPattern) : '';

    var optGet = '';
    if (options.getPatterns) {
      options.getPatterns.forEach(function(pat) {
        optGet += 'get ' + pat + ' ';
      });
    }

    var optAsc   = options.ascending         ? ''      : 'desc';
    var optAlpha = options.lexicographically ? 'alpha' : '';

    var optLimit = options.limit
      ? 'limit ' + options.limit[0] + ' ' + options.limit[1]
      : '';

    cmd += ' ' + optBy    + ' ' +
                 optLimit + ' ' +
                 optGet   + ' ' +
                 optAsc   + ' ' +
                 optAlpha + ' ' + CRLF;

    cmd = cmd.replace(/\s+$/, '') + CRLF;
  }

  if (exports.writeDebugMessageMode)
    writeDebugMessage('> ' + cmd);

  conn.send(cmd);

  // Always push something, even if its null.
  // We need received replies to match number of entries in `callbacks`.

  callbacks.push({ cb:callback, cmd:'sort' });
}

// Close the connection.

exports.quit = function() {
  if (conn.readyState != "open")
    fatal("connection is not open");

  writeDebugMessage('> quit');

  conn.send('quit' + CRLF);
  conn.close();
}

// Make the current redis instance we're connected to a master
// in a master-slave replication configuration.

exports.makeMaster = function() {
  if (conn.readyState != "open")
    fatal("connection is not open");

  writeDebugMessage('> slaveof no one');  // I am SPARTACUS!

  conn.send('slaveof no one');

  callbacks.push({ cb:null, cmd:'slaveof' });
}

// Make the current redis instance we're connected to a slave
// in a master-slave replication configuration.

exports.makeSlaveOf = function(host, port) {
  if (conn.readyState != "open")
    fatal("connection is not open");

  port = port || DEFAULT_PORT;

  var cmd = 'slaveof ' + host + ' ' + port;

  writeDebugMessage('> ' + cmd);

  conn.send(cmd);

  callbacks.push({ cb:null, cmd:'slaveof' });
}

conn.addListener("close", function(hadError){
  if (hadError)
    fatal("disconnected from redis server in error -- redis server up?");
});

<commit_msg>extra debugging for bulk cmds<commit_after>// redis.js - a Redis client for server-side JavaScript, in particular Node
// which runs atop Google V8.
//
// Please review the Redis command reference and protocol specification:
//
// http://code.google.com/p/redis/wiki/CommandReference
// http://code.google.com/p/redis/wiki/ProtocolSpecification
//
// This implementation should make for easy maintenance given that Redis
// commands follow only a couple of conventions.  To add support for a new
// command, simply add the name to either 'inlineCommands' or 'bulkCommands'
// below.
//
// Replies are handled generically and shouldn't need any updates unless Redis
// adds a completely new response type (other than status code, integer, error,
// bulk, and multi-bulk).  See http://code.google.com/p/redis/wiki/ReplyTypes
//
// To learn more about Node and Google V8, see http://tinyclouds.org/node/ and
// http://code.google.com/p/v8/ respectively.
//
// Brian Hammond, Fictorial
//
// Thanks to:
// - Elliott Cable for Node.js 0.1.7 API changes and unit test enhancements.

var DEFAULT_PORT = 6379;

var sys = require("sys");
var tcp = require("tcp");

var conn = new process.tcp.Connection();

// Connect to redis server.  This is most commonly to a redis-server instance
// running on the same host.

exports.connect = function(onConnect, port, host) {
  port = port || DEFAULT_PORT;
  host = host || '127.0.0.1';

  writeDebugMessage('connecting to ' + host + ':' + port);

  conn.connect(port, host);

  conn.addListener("connect", function(){
    conn.setEncoding("utf8");
    if (typeof(onConnect) == "function")
      onConnect();
  });
}

var CRLF = "\r\n";
var CRLF_LENGTH = 2;

// Commands supported by Redis 1.0
//
// Note: 'sort', 'quit', and 'slaveof' are handled as special cases.
//
// Note: 'monitor' is not included as that's generally only used
// in a telnet connection to the redis-server instance.

var inlineCommands = {
  auth:1,
  bgsave:1,
  dbsize:1,
  decr:1,
  decrby:1,
  del:1,
  exists:1,
  expire:1,
  flushall:1,
  flushdb:1,
  get:1,
  incr:1,
  incrby:1,
  info:1,
  keys:1,
  lastsave:1,
  lindex:1,
  llen:1,
  lpop:1,
  lrange:1,
  ltrim:1,
  mget:1,
  move:1,
  randomkey:1,
  rename:1,
  renamenx:1,
  rpop:1,
  save:1,
  scard:1,
  sdiff:1,
  sdiffstore:1,
  select:1,
  shutdown:1,
  sinter:1,
  sinterstore:1,
  smembers:1,
  spop:1,
  sunion:1,
  sunionstore:1,
  ttl:1,
  type:1,
};

var bulkCommands = {
  getset:1,
  lpush:1,
  lrem:1,
  lset:1,
  rpush:1,
  sadd:1,
  set:1,
  setnx:1,
  sismember:1,
  smove:1,
  srem:1,
};

// callbacks:
// Node is event driven / asynchronous with respect to all I/O.  Thus, we call
// user code back when we parse Redis responses.  Note: redis responds in the
// same order as commands are sent.  Thus, pipelining is perfectly valid.  See
// the unit test(s) for examples of callbacks.

var callbacks = [];

exports.debugMode = true;

function writeDebugMessage(data) {
  if (!exports.debugMode || !data)
    return;

  sys.debug(data.replace(/\r\n/g, '\\r\\n'));
}

function fatal(errorMessage) {
  writeDebugMessage("\n\nFATAL: " + errorMessage + "\n");
  throw errorMessage;
}

function maybeConvertToNumber(str) {
  if (/^\s*\d+\s*$/.test(str))
    return parseInt(str, 10);

  if (/^\s*\d+\.(\d+)?\s*$/.test(str))
    return parseFloat(str);

  return str;
}

// Format an inline redis command.
// See http://code.google.com/p/redis/wiki/ProtocolSpecification#Simple_INLINE_commands

function formatInline(commandName, commandArgs, argCount) {
  var str = commandName;

  for (var i = 0; i < argCount; ++i)
    str += ' ' + commandArgs[i];

  return str + CRLF;
}

// Format a bulk redis command.
// e.g. lset key index value => lset key index value-length\r\nvalue\r\n
// where lset is commandName; key, index, and value are commandArgs
// See http://code.google.com/p/redis/wiki/ProtocolSpecification#Bulk_commands

function formatBulk(commandName, commandArgs, argCount) {
  var args = commandName;

  for (var i = 0; i < argCount - 1; ++i) {
    var val = typeof(commandArgs[i]) != 'string'
      ? commandArgs[i].toString()
      : commandArgs[i];

    args += ' ' + val;
  }

  writeDebugMessage("formatBulk " + commandName +
    "; args=" + sys.inspect(commandArgs) + "; count=" + argCount);

  var lastArg = typeof(commandArgs[argCount - 1]) != 'string'
    ? commandArgs[argCount - 1].toString()
    : commandArgs[argCount - 1];

  var cmd = args + ' ' + lastArg.length + CRLF + lastArg + CRLF;

  return cmd;
}

// Creates a function to send a command to the redis server.

function createCommandSender(commandName) {
  return function() {
    if (conn.readyState != "open")
      fatal("connection is not open");

    // last arg (if any) should be callback function.

    var callback = null;
    var numArgs = arguments.length;

    if (typeof(arguments[arguments.length - 1]) == 'function') {
      callback = arguments[arguments.length - 1];
      numArgs = arguments.length - 1;
    }

    // Format the command and send it.

    var cmd;

    if (inlineCommands[commandName]) {
      cmd = formatInline(commandName, arguments, numArgs);
    } else if (bulkCommands[commandName]) {
      cmd = formatBulk(commandName, arguments, numArgs);
    } else {
      fatal('unknown command ' + commandName);
    }

    writeDebugMessage('> ' + cmd);

    // Always push something, even if its null.
    // We need received replies to match number of entries in `callbacks`.

    callbacks.push({ cb:callback, cmd:commandName.toLowerCase() });
    conn.send(cmd);
  };
}

// Create command senders for all commands.

for (var commandName in inlineCommands)
  exports[commandName] = createCommandSender(commandName);

for (var commandName in bulkCommands)
  exports[commandName] = createCommandSender(commandName);

// All reply handlers are passed the full received data which may contain
// multiple replies.  Each should return [ result, offsetOfFollowingReply ]

function handleBulkReply(reply, offset) {
  ++offset; // skip '$'

  var crlfIndex = reply.indexOf(CRLF, offset);
  var valueLength = parseInt(reply.substr(offset, crlfIndex - offset), 10);

  if (valueLength == -1)
    return [ null, crlfIndex + CRLF_LENGTH ];

  var value = reply.substr(crlfIndex + CRLF_LENGTH, valueLength);

  var nextOffset = crlfIndex   + CRLF_LENGTH +
                   valueLength + CRLF_LENGTH;

  return [ value, nextOffset ];
}

function handleMultiBulkReply(reply, offset) {
  ++offset; // skip '*'

  var crlfIndex = reply.indexOf(CRLF, offset);
  var count = parseInt(reply.substr(offset, crlfIndex - offset), 10);

  offset = crlfIndex + CRLF_LENGTH;

  if (count === -1)
    return [ null, offset ];

  var entries = [];

  for (var i = 0; i < count; ++i) {
    var bulkReply = handleBulkReply(reply, offset);
    entries.push(bulkReply[0]);
    offset = bulkReply[1];
  }

  return [ entries, offset ];
}

function handleSingleLineReply(reply, offset) {
  ++offset; // skip '+'

  var crlfIndex = reply.indexOf(CRLF, offset);
  var value = reply.substr(offset, crlfIndex - offset);

  // Most single-line replies are '+OK' so convert such to a true value.

  if (value === 'OK')
    value = true;

  return [ value, crlfIndex + CRLF_LENGTH ];
}

function handleIntegerReply(reply, offset) {
  ++offset; // skip ':'

  var crlfIndex = reply.indexOf(CRLF, offset);

  return [ parseInt(reply.substr(offset, crlfIndex - offset), 10),
           crlfIndex + CRLF_LENGTH ];
}

function handleErrorReply(reply, offset) {
  ++offset; // skip '-'

  var crlfIndex = reply.indexOf(CRLF, offset);

  var errorMessage = (reply.indexOf("ERR ") != 0)
    ? "something bad happened: " + reply.substr(offset, crlfIndex - offset)
    : reply.substr(4, crlfIndex - 4);

  fatal(errorMessage);
}

// See http://code.google.com/p/redis/wiki/ReplyTypes

var replyPrefixToHandler = {
  '$': handleBulkReply,
  '*': handleMultiBulkReply,
  '+': handleSingleLineReply,
  ':': handleIntegerReply,
  '-': handleErrorReply
};

// INFO output is an object with properties for each server metadatum.
// KEYS output is a list (which is more intuitive than a ws-delimited string).

function postProcessResults(command, result) {
  switch (command) {
  case 'info':
    var infoObject = {};

    result.split('\r\n').forEach(function(line) {
      var parts = line.split(':');
      if (parts.length == 2)
        infoObject[parts[0]] = maybeConvertToNumber(parts[1]);
    });

    result = infoObject;
    break;

  case 'keys':
    result = result.split(' ');
    break;

  case 'lastsave':
    result = maybeConvertToNumber(result);
    break;

  default:
    break;
  }

  return result;
}

conn.addListener("receive", function(data){
  if (exports.writeDebugMessageMode)
    writeDebugMessage('< ' + data);

  if (data.length == 0)
    fatal("empty response");

  var offset = 0;

  while (offset < data.length) {
    var replyPrefix = data.charAt(offset);
    var replyHandler = replyPrefixToHandler[replyPrefix];

    if (!replyHandler)
      fatal("unknown prefix " + replyPrefix + " in reply @ offset " + offset);

    var resultInfo = replyHandler(data, offset);
    var result = resultInfo[0];
    offset = resultInfo[1];

    var callback = callbacks.shift();
    if (callback && callback.cb) {
      result = postProcessResults(callback.cmd, result);
      callback.cb(result);
    }
  }
});

// Read this first: http://code.google.com/p/redis/wiki/SortCommand
// options is an object which can have the following properties:
//   'byPattern': 'pattern'
//   'limit': [start, end]
//   'getPatterns': [ 'pattern', 'pattern', ... ]
//   'ascending': true|false
//   'lexicographically': true|false

exports.sort = function(key, options, callback) {
  if (conn.readyState != "open")
    fatal("connection is not open");

  var cmd = 'sort ' + key;

  if (typeof(options) == 'object') {
    var optBy = options.byPattern ? ('by ' + options.byPattern) : '';

    var optGet = '';
    if (options.getPatterns) {
      options.getPatterns.forEach(function(pat) {
        optGet += 'get ' + pat + ' ';
      });
    }

    var optAsc   = options.ascending         ? ''      : 'desc';
    var optAlpha = options.lexicographically ? 'alpha' : '';

    var optLimit = options.limit
      ? 'limit ' + options.limit[0] + ' ' + options.limit[1]
      : '';

    cmd += ' ' + optBy    + ' ' +
                 optLimit + ' ' +
                 optGet   + ' ' +
                 optAsc   + ' ' +
                 optAlpha + ' ' + CRLF;

    cmd = cmd.replace(/\s+$/, '') + CRLF;
  }

  if (exports.writeDebugMessageMode)
    writeDebugMessage('> ' + cmd);

  conn.send(cmd);

  // Always push something, even if its null.
  // We need received replies to match number of entries in `callbacks`.

  callbacks.push({ cb:callback, cmd:'sort' });
}

// Close the connection.

exports.quit = function() {
  if (conn.readyState != "open")
    fatal("connection is not open");

  writeDebugMessage('> quit');

  conn.send('quit' + CRLF);
  conn.close();
}

// Make the current redis instance we're connected to a master
// in a master-slave replication configuration.

exports.makeMaster = function() {
  if (conn.readyState != "open")
    fatal("connection is not open");

  writeDebugMessage('> slaveof no one');  // I am SPARTACUS!

  conn.send('slaveof no one');

  callbacks.push({ cb:null, cmd:'slaveof' });
}

// Make the current redis instance we're connected to a slave
// in a master-slave replication configuration.

exports.makeSlaveOf = function(host, port) {
  if (conn.readyState != "open")
    fatal("connection is not open");

  port = port || DEFAULT_PORT;

  var cmd = 'slaveof ' + host + ' ' + port;

  writeDebugMessage('> ' + cmd);

  conn.send(cmd);

  callbacks.push({ cb:null, cmd:'slaveof' });
}

conn.addListener("close", function(hadError){
  if (hadError)
    fatal("disconnected from redis server in error -- redis server up?");
});

<|endoftext|>


<commit_before>'use strict'

var _ = require('lodash');

function process(result){

	let result = {
		nbCacheServers: 1,
		cacheServers: [
			{
				id: 0,
				videoIds:[]
			}
		]
	};

	writeOutput(result);
}

function writeOutput(result) {

}

module.exports = {
	process : process
}<commit_msg>FIX : double result lol<commit_after>'use strict'

var _ = require('lodash');

function process(data){

	let result = {
		nbCacheServers: 1,
		cacheServers: [
			{
				id: 0,
				videoIds:[]
			}
		]
	};

	writeOutput(result);
}

function writeOutput(result) {

}

module.exports = {
	process : process
}<|endoftext|>


<commit_before>var React = require('react'),
	CreateForm = require('../../components/CreateForm');

var View = React.createClass({

	// TODO: Handle auto-display of create form when validation failed

	getInitialState: function() {
		return {
			createIsVisible: false
		};
	},

	toggleCreate: function(visible) {
		this.setState({
			createIsVisible: visible
		});
	},

	renderCreateButton: function() {
		if (Keystone.list.autocreate) {
			return (

						Create {Keystone.list.singular}

			);
		}
		return (

				<button type="button" className="btn btn-default btn-create btn-create-item" onClick={this.toggleCreate.bind(this, true)}>

					Create {Keystone.list.singular}
				</button>

		);
	},

	renderCreateForm: function() {
		if (!this.state.createIsVisible) return null;
		return <CreateForm list={Keystone.list} onCancel={this.toggleCreate.bind(this, false)} />
	},

	render: function() {
		if (Keystone.list.nocreate) return null;
		return (

				{this.renderCreateButton()}
				{this.renderCreateForm()}

		);
	}

});

exports.render = function() {
	React.render(<View />, document.getElementById('list-view'));
};
<commit_msg>Fixing icon spacing<commit_after>var React = require('react'),
	CreateForm = require('../../components/CreateForm');

var View = React.createClass({

	// TODO: Handle auto-display of create form when validation failed

	getInitialState: function() {
		return {
			createIsVisible: false
		};
	},

	toggleCreate: function(visible) {
		this.setState({
			createIsVisible: visible
		});
	},

	renderCreateButton: function() {
		if (Keystone.list.autocreate) {
			return (

						Create {Keystone.list.singular}

			);
		}
		return (

				<button type="button" className="btn btn-default btn-create btn-create-item" onClick={this.toggleCreate.bind(this, true)}>

					Create {Keystone.list.singular}
				</button>

		);
	},

	renderCreateForm: function() {
		if (!this.state.createIsVisible) return null;
		return <CreateForm list={Keystone.list} onCancel={this.toggleCreate.bind(this, false)} />
	},

	render: function() {
		if (Keystone.list.nocreate) return null;
		return (

				{this.renderCreateButton()}
				{this.renderCreateForm()}

		);
	}

});

exports.render = function() {
	React.render(<View />, document.getElementById('list-view'));
};
<|endoftext|>


<commit_before>var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var files = require('../files.js');
var _ = require('underscore');
var utils = require('../utils.js');
var fs = require('fs');
var path = require('path');

// Given a sandbox, that has the app as its currend cwd, read the versions file
// and check that it contains the plugins that we are looking for. We don't
// check the order, we just want to make sure that the right dependencies are
// in.
//
// sand: a sandbox, that has the main app directory as its cwd.
// platforms: an array of platforms
var checkCordovaPlatforms = function(sand, platforms) {
  // XXX parse this
  var lines = selftest.execFileSync('cordova', ['platform', 'list'],
    { cwd: path.join(sand.cwd, '.meteor', 'local', 'cordova-build') }).split("\n");

  lines.sort();
  plugins = _.clone(plugins).sort();

  var i = 0;
  _.each(lines, function(line) {
    if (!line || line === '') return;
    // XXX do it
    i++;
  });
  selftest.expectEqual(plugins.length, i);
};

// Given a sandbox, that has the app as its cwd, read the cordova platforms
// file and check that it contains exactly the platforms specified, in order.
//
// sand: a sandbox, that has the main app directory as its cwd.
// platforms: an array of platforms in order.
var checkUserPlatforms = function(sand, platforms) {
  var lines = sand.read(".meteor/cordova-platforms").split("\n");
  // XXX do it
  selftest.expectEqual(platforms.length, i);
};

// Add plugins to an app. Change the contents of the plugins and their
// dependencies, make sure that the app still refreshes.
selftest.define("add cordova platforms", function () {
  var s = new Sandbox();
  var run;

  // Starting a run
  s.createApp("myapp", "package-tests");
  s.cd("myapp");
  s.set("METEOR_TEST_TMP", files.mkdtemp());

  run = s.run("run", "android");
  run.matchErr("platform is not added");
  run.matchErr("meteor add-platform android");
  run.expectExit(1);

  run = s.run("add-platform", "android");
  run.match("added");

  run = s.run("run", "android");
  // XXX uncomment this once we get run android to work
  // run.waitSecs(30);
  // run.match("myapp");
  // run.match("proxy");
  // run.match("MongoDB");
  // run.match("your app");
  // run.waitSecs(5);
  // run.match("running at");
  // run.match("localhost");

  run = s.run("remove-platform", "android");
  run.match("removed");
  run = s.run("run", "android");
  run.matchErr("platform is not added");
  run.matchErr("meteor add-platform android");
  run.expectExit(1);
});
<commit_msg>Revert "Update tests to match new command"<commit_after>var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var files = require('../files.js');
var _ = require('underscore');
var utils = require('../utils.js');
var fs = require('fs');
var path = require('path');

// Given a sandbox, that has the app as its currend cwd, read the versions file
// and check that it contains the plugins that we are looking for. We don't
// check the order, we just want to make sure that the right dependencies are
// in.
//
// sand: a sandbox, that has the main app directory as its cwd.
// platforms: an array of platforms
var checkCordovaPlatforms = function(sand, platforms) {
  // XXX parse this
  var lines = selftest.execFileSync('cordova', ['platform', 'list'],
    { cwd: path.join(sand.cwd, '.meteor', 'local', 'cordova-build') }).split("\n");

  lines.sort();
  plugins = _.clone(plugins).sort();

  var i = 0;
  _.each(lines, function(line) {
    if (!line || line === '') return;
    // XXX do it
    i++;
  });
  selftest.expectEqual(plugins.length, i);
};

// Given a sandbox, that has the app as its cwd, read the cordova platforms
// file and check that it contains exactly the platforms specified, in order.
//
// sand: a sandbox, that has the main app directory as its cwd.
// platforms: an array of platforms in order.
var checkUserPlatforms = function(sand, platforms) {
  var lines = sand.read(".meteor/cordova-platforms").split("\n");
  // XXX do it
  selftest.expectEqual(platforms.length, i);
};

// Add plugins to an app. Change the contents of the plugins and their
// dependencies, make sure that the app still refreshes.
selftest.define("add cordova platforms", function () {
  var s = new Sandbox();
  var run;

  // Starting a run
  s.createApp("myapp", "package-tests");
  s.cd("myapp");
  s.set("METEOR_TEST_TMP", files.mkdtemp());

  run = s.run("run", "android");
  run.matchErr("platform is not added");
  run.matchErr("meteor add platform:android");
  run.expectExit(1);

  run = s.run("add", "platform:android");
  run.match("added");

  run = s.run("run", "android");
  // XXX uncomment this once we get run android to work
  // run.waitSecs(30);
  // run.match("myapp");
  // run.match("proxy");
  // run.match("MongoDB");
  // run.match("your app");
  // run.waitSecs(5);
  // run.match("running at");
  // run.match("localhost");

  run = s.run("remove", "platform:android");
  run.match("removed");
  run = s.run("run", "android");
  run.matchErr("platform is not added");
  run.matchErr("meteor add platform:android");
  run.expectExit(1);
});
<|endoftext|>


<commit_before>Google Technical Interview. Software Engineer Role

10 min Intro
10 min Resume Project Talk
  - Asked for detailed information on (Stack, challenges, decisions, etc..)
compare binary search trees vs hash tables
  - advantages vs disadvantages
  - why use one over the other?
30 min on algorithm

<commit_msg>add algorithm<commit_after>Google Technical Interview. Software Engineer Role

10 min Intro
10 min Resume Project Talk
  - Asked for detailed information on (Stack, challenges, decisions, etc..)
compare binary search trees vs hash tables
  - advantages vs disadvantages
  - why use one over the other?
30 min on algorithm

// given a data set of time stamps and image id's where each occurence is a vote
// return the highest voted image id at the kth timestamp

// ex. input
// [[2, A].
//  [3, B]
//  [4, C],
//  [1, B],
//  [6, B].
//  [7, B]
//  [2, C],
//  [9, A],
// ], 3

// output
// B

function rate(data, time){

  // write code here
}
<|endoftext|>


<commit_before>var assert = require('assert')
var abend = require('abend')
var cadence = require('cadence')
var coalesce = require('nascent.coalesce')
var WildMap = require('wildmap')
var nop = require('nop')
var url = require('url')
var Destructor = require('destructible')
var Monotonic = require('monotonic').asString
var Request = require('./request')

// Evented message queue.
var Procession = require('procession')

var Multiplexer = require('conduit/multiplexer')

function Rendezvous () {
    this._connections = new WildMap
    this._destructor = new Destructor
    this._destructor.markDestroyed(this, 'destroyed')
    this._instance = '0'
    this.paths = []
}

Rendezvous.prototype.listener = function (callback, request, response) {
    this.middleware(request, response, callback)
}

Rendezvous.prototype.middleware = function (request, response, next) {
    var parsed = url.parse(request.url)
    var path = parsed.path.split('/')
    var connection = this._connections.match(path).pop()
    if (connection) {
        var request = new Request(connection.multiplexer, request, response, function (header) {
            var location = url.parse(header.url)
            var path = location.pathname
            location.pathname = location.pathname.substring(connection.path.length)
            location = url.format(location)
            header.addHTTPHeader('x-rendezvous-actual-path', path)
        })
        request.consume(function (error) { if (error) next(error) })
    } else {
        next()
    }
}

Rendezvous.prototype.upgrade = function (request, socket) {
    if (this.destroyed) {
        socket.destroy()
        return
    }
    var path = request.headers['sec-conduit-rendezvous-path']
    if (path == null) {
        return false
    }
    var paths = this.paths, connections = this._connections, magazine = this._magazine

    var instance = this._instance = Monotonic.increment(this._instance, 0)

    var parts = path.split('/')

    connections.get(parts).forEach(function (connection) {
        if (connection.path == path) {
            connection.close.call(null)
        }
    })
    var connection = {
        path: path,
        close: close,
        socket: socket,
        instance: instance,
        multiplexer: new Multiplexer(socket, socket)
    }
    // TODO Instead of `abend`, some sort of cleanup and recovery.
    connection.multiplexer.listen(abend)
    connections.add(parts, connection)
    paths.push(path)

    socket.on('error', close)
    socket.on('close', close)
    socket.on('end', close)

    function close () {
        // TODO Why is this called twice?
        connection.multiplexer.destroy()
        if (!socket.destroyed) {
            socket.destroy()
        }
        var current = connections.get(parts).filter(function (connection) {
            return connection.path == path
        }).shift()
        if (current && current.instance == instance) {
            connections.remove(parts, connection)
            paths.splice(paths.indexOf(path), 1)
        }
    }

    return true
}

// TODO Maybe close is different from destroy?
Rendezvous.prototype._close = cadence(function (async) {
    async.forEach(function (path) {
        this._connections.get(path.split('/')).forEach(function (connection) {
            connection.multiplexer.destroy()
            connection.socket.destroy()
        })
    })(this.paths.slice(0, this.paths.length))
})

Rendezvous.prototype.close = function (callback) {
    this._close(coalesce(callback, abend))
}

module.exports = Rendezvous
<commit_msg>Fix URL rewriting.<commit_after>var assert = require('assert')
var abend = require('abend')
var cadence = require('cadence')
var coalesce = require('nascent.coalesce')
var WildMap = require('wildmap')
var nop = require('nop')
var url = require('url')
var Destructor = require('destructible')
var Monotonic = require('monotonic').asString
var Request = require('./request')

// Evented message queue.
var Procession = require('procession')

var Multiplexer = require('conduit/multiplexer')

function Rendezvous () {
    this._connections = new WildMap
    this._destructor = new Destructor
    this._destructor.markDestroyed(this, 'destroyed')
    this._instance = '0'
    this.paths = []
}

Rendezvous.prototype.listener = function (callback, request, response) {
    this.middleware(request, response, callback)
}

Rendezvous.prototype.middleware = function (request, response, next) {
    var parsed = url.parse(request.url)
    var path = parsed.path.split('/')
    var connection = this._connections.match(path).pop()
    if (connection) {
        var request = new Request(connection.multiplexer, request, response, function (header) {
            var location = url.parse(header.url)
            var path = location.pathname
            location.pathname = location.pathname.substring(connection.path.length)
            request.url = url.format(location)
            header.addHTTPHeader('x-rendezvous-actual-path', path)
        })
        request.consume(function (error) { if (error) next(error) })
    } else {
        next()
    }
}

Rendezvous.prototype.upgrade = function (request, socket) {
    if (this.destroyed) {
        socket.destroy()
        return
    }
    var path = request.headers['sec-conduit-rendezvous-path']
    if (path == null) {
        return false
    }
    var paths = this.paths, connections = this._connections, magazine = this._magazine

    var instance = this._instance = Monotonic.increment(this._instance, 0)

    var parts = path.split('/')

    connections.get(parts).forEach(function (connection) {
        if (connection.path == path) {
            connection.close.call(null)
        }
    })
    var connection = {
        path: path,
        close: close,
        socket: socket,
        instance: instance,
        multiplexer: new Multiplexer(socket, socket)
    }
    // TODO Instead of `abend`, some sort of cleanup and recovery.
    connection.multiplexer.listen(abend)
    connections.add(parts, connection)
    paths.push(path)

    socket.on('error', close)
    socket.on('close', close)
    socket.on('end', close)

    function close () {
        // TODO Why is this called twice?
        connection.multiplexer.destroy()
        if (!socket.destroyed) {
            socket.destroy()
        }
        var current = connections.get(parts).filter(function (connection) {
            return connection.path == path
        }).shift()
        if (current && current.instance == instance) {
            connections.remove(parts, connection)
            paths.splice(paths.indexOf(path), 1)
        }
    }

    return true
}

// TODO Maybe close is different from destroy?
Rendezvous.prototype._close = cadence(function (async) {
    async.forEach(function (path) {
        this._connections.get(path.split('/')).forEach(function (connection) {
            connection.multiplexer.destroy()
            connection.socket.destroy()
        })
    })(this.paths.slice(0, this.paths.length))
})

Rendezvous.prototype.close = function (callback) {
    this._close(coalesce(callback, abend))
}

module.exports = Rendezvous
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

var url = require('url');
var path = require('path');
var declareOpts = require('../lib/declareOpts');
var FileWatcher = require('../FileWatcher');
var Packager = require('../Packager');
var Activity = require('../Activity');
var AssetServer = require('../AssetServer');
var Promise = require('bluebird');
var _ = require('underscore');
var exec = require('child_process').exec;
var fs = require('fs');

module.exports = Server;

var validateOpts = declareOpts({
  projectRoots: {
    type: 'array',
    required: true,
  },
  blacklistRE: {
    type: 'object', // typeof regex is object
  },
  moduleFormat: {
    type: 'string',
    default: 'haste',
  },
  polyfillModuleNames: {
    type: 'array',
    default: [],
  },
  cacheVersion: {
    type: 'string',
    default: '1.0',
  },
  resetCache: {
    type: 'boolean',
    default: false,
  },
  transformModulePath: {
    type:'string',
    required: false,
  },
  nonPersistent: {
    type: 'boolean',
    default: false,
  },
  assetRoots: {
    type: 'array',
    required: false,
  },
  assetExts: {
    type: 'array',
    default: ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'],
  },
});

function Server(options) {
  var opts = validateOpts(options);

  this._projectRoots = opts.projectRoots;
  this._packages = Object.create(null);
  this._changeWatchers = [];

  var assetGlobs = opts.assetExts.map(function(ext) {
    return '**/*.' + ext;
  });

  var watchRootConfigs = opts.projectRoots.map(function(dir) {
    return {
      dir: dir,
      globs: [
        '**/*.js',
        '**/*.json',
      ].concat(assetGlobs),
    };
  });

  if (opts.assetRoots != null) {
    watchRootConfigs = watchRootConfigs.concat(
      opts.assetRoots.map(function(dir) {
        return {
          dir: dir,
          globs: assetGlobs,
        };
      })
    );
  }

  this._fileWatcher = options.nonPersistent
    ? FileWatcher.createDummyWatcher()
    : new FileWatcher(watchRootConfigs);

  this._assetServer = new AssetServer({
    projectRoots: opts.projectRoots,
    assetExts: opts.assetExts,
  });

  var packagerOpts = Object.create(opts);
  packagerOpts.fileWatcher = this._fileWatcher;
  packagerOpts.assetServer = this._assetServer;
  this._packager = new Packager(packagerOpts);

  var onFileChange = this._onFileChange.bind(this);
  this._fileWatcher.on('all', onFileChange);

  var self = this;
  this._debouncedFileChangeHandler = _.debounce(function(filePath) {
    self._rebuildPackages(filePath);
    self._informChangeWatchers();
  }, 50);
}

Server.prototype._onFileChange = function(type, filepath, root) {
  var absPath = path.join(root, filepath);
  this._packager.invalidateFile(absPath);
  // Make sure the file watcher event runs through the system before
  // we rebuild the packages.
  this._debouncedFileChangeHandler(absPath);
};

Server.prototype._rebuildPackages = function() {
  var buildPackage = this.buildPackage.bind(this);
  var packages = this._packages;

  Object.keys(packages).forEach(function(optionsJson) {
    var options = JSON.parse(optionsJson);
    // Wait for a previous build (if exists) to finish.
    packages[optionsJson] = (packages[optionsJson] || Promise.resolve()).finally(function() {
      // With finally promise callback we can't change the state of the promise
      // so we need to reassign the promise.
      packages[optionsJson] = buildPackage(options).then(function(p) {
        // Make a throwaway call to getSource to cache the source string.
        p.getSource({
          inlineSourceMap: options.inlineSourceMap,
          minify: options.minify,
        });
        return p;
      });
    });
    return packages[optionsJson];
  });
};

Server.prototype._informChangeWatchers = function() {
  var watchers = this._changeWatchers;
  var headers = {
    'Content-Type': 'application/json; charset=UTF-8',
  };

  watchers.forEach(function(w) {
    w.res.writeHead(205, headers);
    w.res.end(JSON.stringify({ changed: true }));
  });

  this._changeWatchers = [];
};

Server.prototype.end = function() {
  Promise.all([
    this._fileWatcher.end(),
    this._packager.kill(),
  ]);
};

var packageOpts = declareOpts({
  sourceMapUrl: {
    type: 'string',
    required: false,
  },
  entryFile: {
    type: 'string',
    required: true,
  },
  dev: {
    type: 'boolean',
    default: true,
  },
  minify: {
    type: 'boolean',
    default: false,
  },
  runModule: {
    type: 'boolean',
    default: true,
  },
  inlineSourceMap: {
    type: 'boolean',
    default: false,
  },
});

Server.prototype.buildPackage = function(options) {
  var opts = packageOpts(options);

  return this._packager.package(
    opts.entryFile,
    opts.runModule,
    opts.sourceMapUrl,
    opts.dev
  );
};

Server.prototype.buildPackageFromUrl = function(reqUrl) {
  var options = getOptionsFromUrl(reqUrl);
  return this.buildPackage(options);
};

Server.prototype.getDependencies = function(main) {
  return this._packager.getDependencies(main);
};

Server.prototype._processDebugRequest = function(reqUrl, res) {
  var ret = '<!doctype html>';
  var pathname = url.parse(reqUrl).pathname;
  var parts = pathname.split('/').filter(Boolean);
  if (parts.length === 1) {
    ret += '
Cached Packages
';
    ret += '
Dependency Graph
';
    res.end(ret);
  } else if (parts[1] === 'packages') {
    ret += '
 Cached Packages
';
    Promise.all(Object.keys(this._packages).map(function(optionsJson) {
      return this._packages[optionsJson].then(function(p) {
        ret += '

' + optionsJson + '
';
        ret += p.getDebugInfo();
      });
    }, this)).then(
      function() { res.end(ret); },
      function(e) {
        res.wrteHead(500);
        res.end('Internal Error');
        console.log(e.stack);
      }
    );
  } else if (parts[1] === 'graph'){
    ret += '
 Dependency Graph
';
    ret += this._packager.getGraphDebugInfo();
    res.end(ret);
  } else {
    res.writeHead('404');
    res.end('Invalid debug request');
    return;
  }
};

Server.prototype._processOnChangeRequest = function(req, res) {
  var watchers = this._changeWatchers;

  watchers.push({
    req: req,
    res: res,
  });

  req.on('close', function() {
    for (var i = 0; i < watchers.length; i++) {
      if (watchers[i] && watchers[i].req === req) {
        watchers.splice(i, 1);
        break;
      }
    }
  });
};

Server.prototype._processAssetsRequest = function(req, res) {
  var urlObj = url.parse(req.url, true);
  var assetPath = urlObj.pathname.match(/^\/assets\/(.+)$/);
  this._assetServer.get(assetPath[1])
    .then(
      function(data) {
        res.end(data);
      },
      function(error) {
        console.error(error.stack);
        res.writeHead('404');
        res.end('Asset not found');
      }
    ).done();
};

Server.prototype._processProfile = function(req, res) {
  console.log('Dumping profile information...');
  var dumpName = '/tmp/dump_' + Date.now() + '.json';
  var prefix = process.env.TRACE_VIEWER_PATH || '';
  var cmd = path.join(prefix, 'trace2html') + ' ' + dumpName;
  fs.writeFileSync(dumpName, req.rawBody);
  exec(cmd, function (error) {
    if (error) {
      if (error.code === 127) {
        console.error(
          '\n** Failed executing `' + cmd + '` **\n\n' +
          'Google trace-viewer is required to visualize the data, do you have it installled?\n\n' +
          'You can get it at:\n\n' +
          '  https://github.com/google/trace-viewer\n\n' +
          'If it\'s not in your path,  you can set a custom path with:\n\n' +
          '  TRACE_VIEWER_PATH=/path/to/trace-viewer\n\n' +
          'NOTE: Your profile data was kept at:\n\n' +
          '  ' + dumpName
        );
      } else {
        console.error('Unknown error', error);
      }
      res.end();
      return;
    } else {
      exec('rm ' + dumpName);
      exec('open ' + dumpName.replace(/json$/, 'html'), function (error) {
        if (error) {
          console.error(error);
        }
        res.end();
      });
    }
  });
};

Server.prototype.processRequest = function(req, res, next) {
  var urlObj = url.parse(req.url, true);
  var pathname = urlObj.pathname;

  var requestType;
  if (pathname.match(/\.bundle$/)) {
    requestType = 'bundle';
  } else if (pathname.match(/\.map$/)) {
    requestType = 'map';
  } else if (pathname.match(/^\/debug/)) {
    this._processDebugRequest(req.url, res);
    return;
  } else if (pathname.match(/^\/onchange\/?$/)) {
    this._processOnChangeRequest(req, res);
    return;
  } else if (pathname.match(/^\/assets\//)) {
    this._processAssetsRequest(req, res);
    return;
  } else if (pathname.match(/^\/profile\/?$/)) {
    this._processProfile(req, res);
    return;
  } else {
    next();
    return;
  }

  var startReqEventId = Activity.startEvent('request:' + req.url);
  var options = getOptionsFromUrl(req.url);
  var optionsJson = JSON.stringify(options);
  var building = this._packages[optionsJson] || this.buildPackage(options);

  this._packages[optionsJson] = building;
  building.then(
    function(p) {
      if (requestType === 'bundle') {
        res.end(p.getSource({
          inlineSourceMap: options.inlineSourceMap,
          minify: options.minify,
        }));
        Activity.endEvent(startReqEventId);
      } else if (requestType === 'map') {
        res.end(JSON.stringify(p.getSourceMap()));
        Activity.endEvent(startReqEventId);
      }
    },
    function(error) {
      handleError(res, error);
    }
  ).done();
};

function getOptionsFromUrl(reqUrl) {
  // `true` to parse the query param as an object.
  var urlObj = url.parse(reqUrl, true);
  // node v0.11.14 bug see https://github.com/facebook/react-native/issues/218
  urlObj.query = urlObj.query || {};

  var pathname = decodeURIComponent(urlObj.pathname);

  // Backwards compatibility. Options used to be as added as '.' to the
  // entry module name. We can safely remove these options.
  var entryFile = pathname.replace(/^\//, '').split('.').filter(function(part) {
    if (part === 'includeRequire' || part === 'runModule' ||
        part === 'bundle' || part === 'map') {
      return false;
    }
    return true;
  }).join('.') + '.js';

  return {
    sourceMapUrl: pathname.replace(/\.bundle$/, '.map'),
    entryFile: entryFile,
    dev: getBoolOptionFromQuery(urlObj.query, 'dev', true),
    minify: getBoolOptionFromQuery(urlObj.query, 'minify'),
    runModule: getBoolOptionFromQuery(urlObj.query, 'runModule', true),
    inlineSourceMap: getBoolOptionFromQuery(
      urlObj.query,
      'inlineSourceMap',
      false
    ),
  };
}

function getBoolOptionFromQuery(query, opt, defaultVal) {
  if (query[opt] == null && defaultVal != null) {
    return defaultVal;
  }

  return query[opt] === 'true' || query[opt] === '1';
}

function handleError(res, error) {
  res.writeHead(error.status || 500, {
    'Content-Type': 'application/json; charset=UTF-8',
  });

  if (error.type === 'TransformError' || error.type === 'NotFoundError') {
    error.errors = [{
      description: error.description,
      filename: error.filename,
      lineNumber: error.lineNumber,
    }];
    console.error(error);
    res.end(JSON.stringify(error));
  } else {
    console.error(error.stack || error);
    res.end(JSON.stringify({
      type: 'InternalError',
      message: 'react-packager has encountered an internal error, ' +
        'please check your terminal error output for more details',
    }));
  }
}
<commit_msg>[ReactNative][easy] fix server 500 response typo<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

var url = require('url');
var path = require('path');
var declareOpts = require('../lib/declareOpts');
var FileWatcher = require('../FileWatcher');
var Packager = require('../Packager');
var Activity = require('../Activity');
var AssetServer = require('../AssetServer');
var Promise = require('bluebird');
var _ = require('underscore');
var exec = require('child_process').exec;
var fs = require('fs');

module.exports = Server;

var validateOpts = declareOpts({
  projectRoots: {
    type: 'array',
    required: true,
  },
  blacklistRE: {
    type: 'object', // typeof regex is object
  },
  moduleFormat: {
    type: 'string',
    default: 'haste',
  },
  polyfillModuleNames: {
    type: 'array',
    default: [],
  },
  cacheVersion: {
    type: 'string',
    default: '1.0',
  },
  resetCache: {
    type: 'boolean',
    default: false,
  },
  transformModulePath: {
    type:'string',
    required: false,
  },
  nonPersistent: {
    type: 'boolean',
    default: false,
  },
  assetRoots: {
    type: 'array',
    required: false,
  },
  assetExts: {
    type: 'array',
    default: ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'],
  },
});

function Server(options) {
  var opts = validateOpts(options);

  this._projectRoots = opts.projectRoots;
  this._packages = Object.create(null);
  this._changeWatchers = [];

  var assetGlobs = opts.assetExts.map(function(ext) {
    return '**/*.' + ext;
  });

  var watchRootConfigs = opts.projectRoots.map(function(dir) {
    return {
      dir: dir,
      globs: [
        '**/*.js',
        '**/*.json',
      ].concat(assetGlobs),
    };
  });

  if (opts.assetRoots != null) {
    watchRootConfigs = watchRootConfigs.concat(
      opts.assetRoots.map(function(dir) {
        return {
          dir: dir,
          globs: assetGlobs,
        };
      })
    );
  }

  this._fileWatcher = options.nonPersistent
    ? FileWatcher.createDummyWatcher()
    : new FileWatcher(watchRootConfigs);

  this._assetServer = new AssetServer({
    projectRoots: opts.projectRoots,
    assetExts: opts.assetExts,
  });

  var packagerOpts = Object.create(opts);
  packagerOpts.fileWatcher = this._fileWatcher;
  packagerOpts.assetServer = this._assetServer;
  this._packager = new Packager(packagerOpts);

  var onFileChange = this._onFileChange.bind(this);
  this._fileWatcher.on('all', onFileChange);

  var self = this;
  this._debouncedFileChangeHandler = _.debounce(function(filePath) {
    self._rebuildPackages(filePath);
    self._informChangeWatchers();
  }, 50);
}

Server.prototype._onFileChange = function(type, filepath, root) {
  var absPath = path.join(root, filepath);
  this._packager.invalidateFile(absPath);
  // Make sure the file watcher event runs through the system before
  // we rebuild the packages.
  this._debouncedFileChangeHandler(absPath);
};

Server.prototype._rebuildPackages = function() {
  var buildPackage = this.buildPackage.bind(this);
  var packages = this._packages;

  Object.keys(packages).forEach(function(optionsJson) {
    var options = JSON.parse(optionsJson);
    // Wait for a previous build (if exists) to finish.
    packages[optionsJson] = (packages[optionsJson] || Promise.resolve()).finally(function() {
      // With finally promise callback we can't change the state of the promise
      // so we need to reassign the promise.
      packages[optionsJson] = buildPackage(options).then(function(p) {
        // Make a throwaway call to getSource to cache the source string.
        p.getSource({
          inlineSourceMap: options.inlineSourceMap,
          minify: options.minify,
        });
        return p;
      });
    });
    return packages[optionsJson];
  });
};

Server.prototype._informChangeWatchers = function() {
  var watchers = this._changeWatchers;
  var headers = {
    'Content-Type': 'application/json; charset=UTF-8',
  };

  watchers.forEach(function(w) {
    w.res.writeHead(205, headers);
    w.res.end(JSON.stringify({ changed: true }));
  });

  this._changeWatchers = [];
};

Server.prototype.end = function() {
  Promise.all([
    this._fileWatcher.end(),
    this._packager.kill(),
  ]);
};

var packageOpts = declareOpts({
  sourceMapUrl: {
    type: 'string',
    required: false,
  },
  entryFile: {
    type: 'string',
    required: true,
  },
  dev: {
    type: 'boolean',
    default: true,
  },
  minify: {
    type: 'boolean',
    default: false,
  },
  runModule: {
    type: 'boolean',
    default: true,
  },
  inlineSourceMap: {
    type: 'boolean',
    default: false,
  },
});

Server.prototype.buildPackage = function(options) {
  var opts = packageOpts(options);

  return this._packager.package(
    opts.entryFile,
    opts.runModule,
    opts.sourceMapUrl,
    opts.dev
  );
};

Server.prototype.buildPackageFromUrl = function(reqUrl) {
  var options = getOptionsFromUrl(reqUrl);
  return this.buildPackage(options);
};

Server.prototype.getDependencies = function(main) {
  return this._packager.getDependencies(main);
};

Server.prototype._processDebugRequest = function(reqUrl, res) {
  var ret = '<!doctype html>';
  var pathname = url.parse(reqUrl).pathname;
  var parts = pathname.split('/').filter(Boolean);
  if (parts.length === 1) {
    ret += '
Cached Packages
';
    ret += '
Dependency Graph
';
    res.end(ret);
  } else if (parts[1] === 'packages') {
    ret += '
 Cached Packages
';
    Promise.all(Object.keys(this._packages).map(function(optionsJson) {
      return this._packages[optionsJson].then(function(p) {
        ret += '

' + optionsJson + '
';
        ret += p.getDebugInfo();
      });
    }, this)).then(
      function() { res.end(ret); },
      function(e) {
        res.writeHead(500);
        res.end('Internal Error');
        console.log(e.stack);
      }
    );
  } else if (parts[1] === 'graph'){
    ret += '
 Dependency Graph
';
    ret += this._packager.getGraphDebugInfo();
    res.end(ret);
  } else {
    res.writeHead('404');
    res.end('Invalid debug request');
    return;
  }
};

Server.prototype._processOnChangeRequest = function(req, res) {
  var watchers = this._changeWatchers;

  watchers.push({
    req: req,
    res: res,
  });

  req.on('close', function() {
    for (var i = 0; i < watchers.length; i++) {
      if (watchers[i] && watchers[i].req === req) {
        watchers.splice(i, 1);
        break;
      }
    }
  });
};

Server.prototype._processAssetsRequest = function(req, res) {
  var urlObj = url.parse(req.url, true);
  var assetPath = urlObj.pathname.match(/^\/assets\/(.+)$/);
  this._assetServer.get(assetPath[1])
    .then(
      function(data) {
        res.end(data);
      },
      function(error) {
        console.error(error.stack);
        res.writeHead('404');
        res.end('Asset not found');
      }
    ).done();
};

Server.prototype._processProfile = function(req, res) {
  console.log('Dumping profile information...');
  var dumpName = '/tmp/dump_' + Date.now() + '.json';
  var prefix = process.env.TRACE_VIEWER_PATH || '';
  var cmd = path.join(prefix, 'trace2html') + ' ' + dumpName;
  fs.writeFileSync(dumpName, req.rawBody);
  exec(cmd, function (error) {
    if (error) {
      if (error.code === 127) {
        console.error(
          '\n** Failed executing `' + cmd + '` **\n\n' +
          'Google trace-viewer is required to visualize the data, do you have it installled?\n\n' +
          'You can get it at:\n\n' +
          '  https://github.com/google/trace-viewer\n\n' +
          'If it\'s not in your path,  you can set a custom path with:\n\n' +
          '  TRACE_VIEWER_PATH=/path/to/trace-viewer\n\n' +
          'NOTE: Your profile data was kept at:\n\n' +
          '  ' + dumpName
        );
      } else {
        console.error('Unknown error', error);
      }
      res.end();
      return;
    } else {
      exec('rm ' + dumpName);
      exec('open ' + dumpName.replace(/json$/, 'html'), function (error) {
        if (error) {
          console.error(error);
        }
        res.end();
      });
    }
  });
};

Server.prototype.processRequest = function(req, res, next) {
  var urlObj = url.parse(req.url, true);
  var pathname = urlObj.pathname;

  var requestType;
  if (pathname.match(/\.bundle$/)) {
    requestType = 'bundle';
  } else if (pathname.match(/\.map$/)) {
    requestType = 'map';
  } else if (pathname.match(/^\/debug/)) {
    this._processDebugRequest(req.url, res);
    return;
  } else if (pathname.match(/^\/onchange\/?$/)) {
    this._processOnChangeRequest(req, res);
    return;
  } else if (pathname.match(/^\/assets\//)) {
    this._processAssetsRequest(req, res);
    return;
  } else if (pathname.match(/^\/profile\/?$/)) {
    this._processProfile(req, res);
    return;
  } else {
    next();
    return;
  }

  var startReqEventId = Activity.startEvent('request:' + req.url);
  var options = getOptionsFromUrl(req.url);
  var optionsJson = JSON.stringify(options);
  var building = this._packages[optionsJson] || this.buildPackage(options);

  this._packages[optionsJson] = building;
  building.then(
    function(p) {
      if (requestType === 'bundle') {
        res.end(p.getSource({
          inlineSourceMap: options.inlineSourceMap,
          minify: options.minify,
        }));
        Activity.endEvent(startReqEventId);
      } else if (requestType === 'map') {
        res.end(JSON.stringify(p.getSourceMap()));
        Activity.endEvent(startReqEventId);
      }
    },
    function(error) {
      handleError(res, error);
    }
  ).done();
};

function getOptionsFromUrl(reqUrl) {
  // `true` to parse the query param as an object.
  var urlObj = url.parse(reqUrl, true);
  // node v0.11.14 bug see https://github.com/facebook/react-native/issues/218
  urlObj.query = urlObj.query || {};

  var pathname = decodeURIComponent(urlObj.pathname);

  // Backwards compatibility. Options used to be as added as '.' to the
  // entry module name. We can safely remove these options.
  var entryFile = pathname.replace(/^\//, '').split('.').filter(function(part) {
    if (part === 'includeRequire' || part === 'runModule' ||
        part === 'bundle' || part === 'map') {
      return false;
    }
    return true;
  }).join('.') + '.js';

  return {
    sourceMapUrl: pathname.replace(/\.bundle$/, '.map'),
    entryFile: entryFile,
    dev: getBoolOptionFromQuery(urlObj.query, 'dev', true),
    minify: getBoolOptionFromQuery(urlObj.query, 'minify'),
    runModule: getBoolOptionFromQuery(urlObj.query, 'runModule', true),
    inlineSourceMap: getBoolOptionFromQuery(
      urlObj.query,
      'inlineSourceMap',
      false
    ),
  };
}

function getBoolOptionFromQuery(query, opt, defaultVal) {
  if (query[opt] == null && defaultVal != null) {
    return defaultVal;
  }

  return query[opt] === 'true' || query[opt] === '1';
}

function handleError(res, error) {
  res.writeHead(error.status || 500, {
    'Content-Type': 'application/json; charset=UTF-8',
  });

  if (error.type === 'TransformError' || error.type === 'NotFoundError') {
    error.errors = [{
      description: error.description,
      filename: error.filename,
      lineNumber: error.lineNumber,
    }];
    console.error(error);
    res.end(JSON.stringify(error));
  } else {
    console.error(error.stack || error);
    res.end(JSON.stringify({
      type: 'InternalError',
      message: 'react-packager has encountered an internal error, ' +
        'please check your terminal error output for more details',
    }));
  }
}
<|endoftext|>


<commit_before>var crypto = require('crypto'),
    mime = require('mime'),
    uuid = require('node-uuid'),
    moment = require('moment'),
    config = require('./../s3/config');

module.exports = {
  index : function(req, res){
  },

  signed : function(req, res){
    /* JSON View for obtaining CORS policy, signature, key, redirect and mime-type, then signs policy as a sha1 digest */

    var mime_type = mime.lookup(req.query.title); // Uses node-mime to detect mime-type based on file extension
    var expire = moment().utc().add('hour', 1).toJSON("YYYY-MM-DDTHH:mm:ss Z"); // Set policy expire date +30 minutes in UTC
    // Creates the JSON policy according to Amazon S3's CORS uploads specfication (http://aws.amazon.com/articles/1434)
    var policy = JSON.stringify({
                  "expiration": expire,
                    "conditions": [
                      {"bucket": config.aws_bucket},
                      ["starts-with", "$key", config.bucket_dir],
                      {"acl": "public-read"},
                      {"success_action_status": "201"},
                      ["starts-with", "$Content-Type", mime_type],
                      ["content-length-range", 0, config.max_filesize]
                    ]
                  });

    var base64policy = new Buffer(policy).toString('base64'); // Create base64 policy
    var signature = crypto.createHmac('sha1', config.aws_secret).update(base64policy).digest('base64'); // Create signature
    var file_key = uuid.v4(); // Generate uuid for filename
    console.log('key')
    console.log(config.aws_key);
    // Return JSON View
    res.json({
               aws_bucket: config.aws_bucket, // Passes to view to set as vars
               aws_key: config.aws_key,
               redirect_host: config.redirect_host,
               bucket_dir: config.bucket_dir,
               host: config.host,
               policy: base64policy,
               signature: signature,
               key: config.bucket_dir + file_key + "_" + req.query.title,
               success_action_redirect: "/"
               contentType: mime_type
            })
  }
}<commit_msg>add uploader<commit_after>var crypto = require('crypto'),
    mime = require('mime'),
    uuid = require('node-uuid'),
    moment = require('moment'),
    config = require('./../s3/config');

module.exports = {
  index : function(req, res){
  },

  signed : function(req, res){
    /* JSON View for obtaining CORS policy, signature, key, redirect and mime-type, then signs policy as a sha1 digest */

    var mime_type = mime.lookup(req.query.title); // Uses node-mime to detect mime-type based on file extension
    var expire = moment().utc().add('hour', 1).toJSON("YYYY-MM-DDTHH:mm:ss Z"); // Set policy expire date +30 minutes in UTC
    // Creates the JSON policy according to Amazon S3's CORS uploads specfication (http://aws.amazon.com/articles/1434)
    var policy = JSON.stringify({
                  "expiration": expire,
                    "conditions": [
                      {"bucket": config.aws_bucket},
                      ["starts-with", "$key", config.bucket_dir],
                      {"acl": "public-read"},
                      {"success_action_status": "201"},
                      ["starts-with", "$Content-Type", mime_type],
                      ["content-length-range", 0, config.max_filesize]
                    ]
                  });

    var base64policy = new Buffer(policy).toString('base64'); // Create base64 policy
    var signature = crypto.createHmac('sha1', config.aws_secret).update(base64policy).digest('base64'); // Create signature
    var file_key = uuid.v4(); // Generate uuid for filename
    console.log('key')
    console.log(config.aws_key);
    // Return JSON View
    res.json({
               aws_bucket: config.aws_bucket, // Passes to view to set as vars
               aws_key: config.aws_key,
               redirect_host: config.redirect_host,
               bucket_dir: config.bucket_dir,
               host: config.host,
               policy: base64policy,
               signature: signature,
               key: config.bucket_dir + file_key + "_" + req.query.title,
               success_action_redirect: "/",
               contentType: mime_type
            })
  }
}<|endoftext|>


<commit_before>module.exports = [{
	name : "3-Ländereck",
	url : "https://map.freifunk-3laendereck.net/nodes.json"
}, {
	"name" : "Aachen",
	"url" : "http://map.freifunk-aachen.de/nodes.json"
}, {
	"name" : "Bielefeld",
	"url" : "http://map.freifunk-bielefeld.de/nodes.json"
}, {
	name : "Chemnitz",
	url : "http://map.chemnitz.freifunk.net/nodes.json"
}, {
	name : "Berlin",
	url : "http://openwifimap.net/api/view_nodes_spatial?bbox=13.11286926269531%2C52.41666021079324%2C13.689651489257812%2C52.619308406611545"
}, {
	"name" : "Darmstadt",
	"url" : "http://map.darmstadt.freifunk.net/nodes.json"
}, {
	"name" : "Dortmund",
	"url" : "http://map.ffdo.de/data/nodes.json"
}, {
	"name" : "Dresden",
	"url" : "http://info.freifunk-dresden.de/info/nodes.json"
}, {
	"name" : "Flensburg",
	"url ": "http://map.freifunk-flensburg.de/data/nodelist.json"
},{
	"name" : "Frankfurt am Main",
	"url" : "http://map.ffm.freifunk.net/nodes.json"
}, {
	"name" : "Freiburg",
	"url" : "http://freiburg.freifunk.net/ffmap-d3/nodes.json"
}, {
	name : "Gera/Greiz",
	url : "http://freifunk-gera-greiz.de/meshviewer/data/nodelist.json"
}, {
	name : "Gronau",
	url : "http://freifunk.liztv.net/batmap/json.php?lat=52.210773525324925&lon=7.047603455200169&f="
}, {
	"name" : "Göttingen",
	"url" : "https://cccgoe.de/map/nodes.json"
}, {
	"name" : "Gütersloh",
	"url" : "http://stats.guetersloh.freifunk.net/map/nodes.json"
}, {
	"name" : "Hamburg",
	"url" : "https://map.hamburg.freifunk.net/nodes.json"
}, {
	"name" : "Hannover",
	"url" : "http://hannover.freifunk.net/karte/nodes.json"
}, {
	"name" : "Hildesheim",
	"url" : "http://map.freifunk-hi.de/json/nodes.json"
}, {
	name : "Hennef",
	url : "http://map.freifunk-hennef.de/data/nodes.json"
}, {
	"name" : "Ingolstadt",
	"url" : "https://freifunk-ingolstadt.de/map/nodes.json"
}, {
	"name" : "Jena",
	"url" : "https://freifunk-jena.de/ffmap/nodes.json"
}, {
	"name" : "Karlsruhe",
	"url" : "http://www.freifunk-karlsruhe.de/map/nodes.json"
}, {
	name : "Kassel",
	url : "http://map.ffks.de/meshviewer/nodes.json"
}, {
	"name" : "Kiel",
	"url" : "http://map.freifunk.in-kiel.de/json/nodes.json"
}, {
	"name" : "Köln/Bonn",
	"url" : "http://map.kbu.freifunk.net/nodes.json"
}, {
	name : "Leipzig",
	url : "http://db.leipzig.freifunk.net/uptime/mapbrowserdata/"
}, {
	"name" : "Lüneburg",
	"url" : "http://freifunk-lueneburg.de/karte/nodes.json"
}, {
	"name" : "Magdeburg",
	"url" : "http://map.md.freifunk.net/nodes.json"
}, {
	"name" : "Mainz",
	"url" : "http://map.freifunk-mainz.de/nodes.json"
}, {
	"name" : "Möhne",
	"url" : "http://map.freifunk-moehne.de/data/nodes.json"
}, {
	"name" : "München",
	"url" : "http://map.freifunk-muenchen.de/nodes.json"
}, {
	"name" : "Münster",
	"url" : "https://freifunk-muenster.de/map/nodes.json"
}, {
	name : "Münsterland",
	url : "https://freifunk-muensterland.de/map/data/nodelist.json"
}, {
	name : "Müritz",
	url : "http://map.4830.org/mueritz/tng/nodes.json"
}, {
	"name" : "Ostholstein",
	"url" : "http://ostholstein.freifunk.net/map/nodes.json"
}, {
	"name" : "Paderborn",
	"url" : "http://map.paderborn.freifunk.net/nodes.json"
}, {
	name : "Pinneberg",
	url : "http://meshviewer.pinneberg.freifunk.net/data/nodes.json"
}, {
	"name" : "Radevormwald",
	"url" : "http://map.gm.wupper.freifunk-rheinland.net/nodes.json"
}, {
	"name" : "Rhein Neckar",
	"url" : "http://map.freifunk-rhein-neckar.de/nodes.json"
}, {
	"name" : "Rheinland",
	"url" : "http://ffmap.freifunk-rheinland.net/nodes.json"
}, {
	name : "Rothenburg ob der Tauber",
	url : "http://netmon.freifunk-rothenburg.de/meshviewer/data/nodelist.json"
}, {
	name : "Ruhr/Straelen",
	url : "http://map.el.freifunk.ruhr/nodes.json"
}, {
	"name" : "Ruhrgebiet",
	"url" : "http://map.freifunk-ruhrgebiet.de/nodes.json"
}, {
	name : "Stormarn",
	url : "http://map.ffod.org/data/nodes.json"
}, {
	name : "Stuttgart",
	url : "http://netinfo.freifunk-stuttgart.de/map/json/global_map.json"
}, {
	name : "Trier",
	url : "http://map.freifunk-trier.starletp9.de/nodes.json"
}, {
	"name" : "Uelzen",
	"url" : "http://map.freifunk-uelzen.de/nodes.json"
}, {
	"name" : "Westpfalz",
	"url" : "http://map.freifunk-westpfalz.de/nodes.json"
}, {
	"name" : "Wien",
	"url" : "https://map.funkfeuer.at/wien/data.php"
}, {
	"name" : "Wiesbaden",
	"url" : "http://map.wiesbaden.freifunk.net/nodes.json"
}, {
	name : "Witten",
	url : "http://ffmap.freifunk-witten.de/nodes.json"
}, {
	"name" : "Wuppertal",
	"url" : "http://map.freifunk-wuppertal.net/nodes.json"
}];
<commit_msg>     <commit_after>module.exports = [{
	name : "3-Ländereck",
	url : "https://map.freifunk-3laendereck.net/nodes.json"
}, {
	"name" : "Aachen",
	"url" : "http://map.freifunk-aachen.de/nodes.json"
}, {
	"name" : "Bielefeld",
	"url" : "http://map.freifunk-bielefeld.de/nodes.json"
}, {
	name : "Chemnitz",
	url : "http://map.chemnitz.freifunk.net/nodes.json"
}, {
	name : "Berlin",
	url : "http://openwifimap.net/api/view_nodes_spatial?bbox=13.11286926269531%2C52.41666021079324%2C13.689651489257812%2C52.619308406611545"
}, {
	"name" : "Darmstadt",
	"url" : "http://map.darmstadt.freifunk.net/nodes.json"
}, {
	"name" : "Dortmund",
	"url" : "http://map.ffdo.de/data/nodes.json"
}, {
	"name" : "Dresden",
	"url" : "http://info.freifunk-dresden.de/info/nodes.json"
}, {
	"name" : "Flensburg",
	"url ": "http://map.freifunk-flensburg.de/data/nodelist.json"
},{
	"name" : "Frankennetz",
	"url" : "http://95.85.40.145:5984/libremap-dev/_design/libremap-api/_rewrite/routers_by_location?bbox=9%2C48%2C14%2C51"
},{
	"name" : "Frankfurt am Main",
	"url" : "http://map.ffm.freifunk.net/nodes.json"
}, {
	"name" : "Freiburg",
	"url" : "http://freiburg.freifunk.net/ffmap-d3/nodes.json"
}, {
	name : "Gera/Greiz",
	url : "http://freifunk-gera-greiz.de/meshviewer/data/nodelist.json"
}, {
	name : "Gronau",
	url : "http://freifunk.liztv.net/batmap/json.php?lat=52.210773525324925&lon=7.047603455200169&f="
}, {
	"name" : "Göttingen",
	"url" : "https://cccgoe.de/map/nodes.json"
}, {
	"name" : "Gütersloh",
	"url" : "http://stats.guetersloh.freifunk.net/map/nodes.json"
}, {
	"name" : "Hamburg",
	"url" : "https://map.hamburg.freifunk.net/nodes.json"
}, {
	"name" : "Hannover",
	"url" : "http://hannover.freifunk.net/karte/nodes.json"
}, {
	"name" : "Hildesheim",
	"url" : "http://map.freifunk-hi.de/json/nodes.json"
}, {
	name : "Hennef",
	url : "http://map.freifunk-hennef.de/data/nodes.json"
}, {
	"name" : "Ingolstadt",
	"url" : "https://freifunk-ingolstadt.de/map/nodes.json"
}, {
	"name" : "Jena",
	"url" : "https://freifunk-jena.de/ffmap/nodes.json"
}, {
	"name" : "Karlsruhe",
	"url" : "http://www.freifunk-karlsruhe.de/map/nodes.json"
}, {
	name : "Kassel",
	url : "http://map.ffks.de/meshviewer/nodes.json"
}, {
	"name" : "Kiel",
	"url" : "http://map.freifunk.in-kiel.de/json/nodes.json"
}, {
	"name" : "Köln/Bonn",
	"url" : "http://map.kbu.freifunk.net/nodes.json"
}, {
	name : "Leipzig",
	url : "http://db.leipzig.freifunk.net/uptime/mapbrowserdata/"
}, {
	"name" : "Lüneburg",
	"url" : "http://freifunk-lueneburg.de/karte/nodes.json"
}, {
	"name" : "Magdeburg",
	"url" : "http://map.md.freifunk.net/nodes.json"
}, {
	"name" : "Mainz",
	"url" : "http://map.freifunk-mainz.de/nodes.json"
}, {
	"name" : "Möhne",
	"url" : "http://map.freifunk-moehne.de/data/nodes.json"
}, {
	"name" : "München",
	"url" : "http://map.freifunk-muenchen.de/nodes.json"
}, {
	"name" : "Münster",
	"url" : "https://freifunk-muenster.de/map/nodes.json"
}, {
	name : "Münsterland",
	url : "https://freifunk-muensterland.de/map/data/nodelist.json"
}, {
	name : "Müritz",
	url : "http://map.4830.org/mueritz/tng/nodes.json"
}, {
	"name" : "Ostholstein",
	"url" : "http://ostholstein.freifunk.net/map/nodes.json"
}, {
	"name" : "Paderborn",
	"url" : "http://map.paderborn.freifunk.net/nodes.json"
}, {
	name : "Pinneberg",
	url : "http://meshviewer.pinneberg.freifunk.net/data/nodes.json"
}, {
	"name" : "Radevormwald",
	"url" : "http://map.gm.wupper.freifunk-rheinland.net/nodes.json"
}, {
	"name" : "Rhein Neckar",
	"url" : "http://map.freifunk-rhein-neckar.de/nodes.json"
}, {
	"name" : "Rheinland",
	"url" : "http://ffmap.freifunk-rheinland.net/nodes.json"
}, {
	name : "Rothenburg ob der Tauber",
	url : "http://netmon.freifunk-rothenburg.de/meshviewer/data/nodelist.json"
}, {
	name : "Ruhr/Straelen",
	url : "http://map.el.freifunk.ruhr/nodes.json"
}, {
	"name" : "Ruhrgebiet",
	"url" : "http://map.freifunk-ruhrgebiet.de/nodes.json"
}, {
	name : "Stormarn",
	url : "http://map.ffod.org/data/nodes.json"
}, {
	name : "Stuttgart",
	url : "http://netinfo.freifunk-stuttgart.de/map/json/global_map.json"
}, {
	name : "Trier",
	url : "http://map.freifunk-trier.starletp9.de/nodes.json"
}, {
	"name" : "Uelzen",
	"url" : "http://map.freifunk-uelzen.de/nodes.json"
}, {
	"name" : "Westpfalz",
	"url" : "http://map.freifunk-westpfalz.de/nodes.json"
}, {
	"name" : "Wien",
	"url" : "https://map.funkfeuer.at/wien/data.php"
}, {
	"name" : "Wiesbaden",
	"url" : "http://map.wiesbaden.freifunk.net/nodes.json"
}, {
	name : "Witten",
	url : "http://ffmap.freifunk-witten.de/nodes.json"
}, {
	"name" : "Wuppertal",
	"url" : "http://map.freifunk-wuppertal.net/nodes.json"
}];
<|endoftext|>


<commit_before>var Q = require("q");
var request = require("request");
//
function schedSessions(schedRequest){
	var deferred = Q.defer();
	console.log("===before option prep");
	var options = new prepRequest(schedRequest);
	console.log("===after option prep",options);
  request(options,function(err,response,body){
      deferred.resolve(body);
			console.log("===list count:",response);
	});
  return deferred.promise;
}

function prepRequest(schedRequest){
	console.log("===before switch");
	switch(schedRequest){
		case "SessionCount":
			console.log("===in case");
			var options = {
				"method" : "POST",
				"url" : "https://sciensiotestevent2016.sched.org/api/session/count",
				"qs" : {
					"api_key" : process.env.SCHED_TOKEN
				},
				"headers" : {
					"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
				}
			};
			break;
		case "SessionList":
			var options = {
				"method" : "POST",
				"url" : "https://sciensiotestevent2016.sched.org/api/session/list",
				"qs" : {
					"api_key" : process.env.SCHED_TOKEN,
					"format" : "json",
          "page" : "1",
          "limit" : "10"
          "strip_html" : "Y"
				},
				"headers" : {
					"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
				}
			};
			break;
		default:
			var options = '';
	}
	return options;
}

exports.schedSessions = schedSessions;
<commit_msg>missed coma<commit_after>var Q = require("q");
var request = require("request");
//
function schedSessions(schedRequest){
	var deferred = Q.defer();
	console.log("===before option prep");
	var options = new prepRequest(schedRequest);
	console.log("===after option prep",options);
  request(options,function(err,response,body){
      deferred.resolve(body);
			console.log("===list count:",response);
	});
  return deferred.promise;
}

function prepRequest(schedRequest){
	console.log("===before switch");
	switch(schedRequest){
		case "SessionCount":
			console.log("===in case");
			var options = {
				"method" : "POST",
				"url" : "https://sciensiotestevent2016.sched.org/api/session/count",
				"qs" : {
					"api_key" : process.env.SCHED_TOKEN
				},
				"headers" : {
					"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
				}
			};
			break;
		case "SessionList":
			var options = {
				"method" : "POST",
				"url" : "https://sciensiotestevent2016.sched.org/api/session/list",
				"qs" : {
					"api_key" : process.env.SCHED_TOKEN,
					"format" : "json",
          "page" : "1",
          "limit" : "10",
          "strip_html" : "Y"
				},
				"headers" : {
					"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
				}
			};
			break;
		default:
			var options = '';
	}
	return options;
}

exports.schedSessions = schedSessions;
<|endoftext|>