<commit_before>var clip = new ZeroClipboard.Client();
var level = new Array(30);
var insp;
var levelParam;
var afterEditorLoad;
var canvasContext;
var minimap;
var context;
var tool;

function setLevel(lvl) {
  level = lvl;

  drawCanvas(camx, camy);
}

function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if (null == results)
    return "";
  else
    return results[1];
}

var UpdateMap = UndoableAction.extend({
  init: function(value, options) {
    var self = this;
    self.value = value;
    // console.log('Redrawing map...');

    this._super(function() {
      // console.log('map up');
      self.oldValue = UpdateMap.priorOldValue;
      setLevel(getLevelCopy(self.value));
      reloadMap();
      UpdateMap.priorOldValue = self.value;

      // reportLevel(self.value, 'new');
      // reportLevel(level, 'current');
      // reportLevel(self.oldValue, 'old');
    }, function() {
      // console.log('map down');
      setLevel(self.oldValue); // setLevel(getLevelCopy(self.oldValue));
      reloadMap();
      UpdateMap.priorOldValue = getLevelCopy(self.oldValue);
    });

    self.do();
  }
});

var canvas, tool, px, py, tcolor, brush, camx, camy;
var tool_default = 'rock';
var total_brushes = 10;
var brushes = new Array(total_brushes);
var brushes_img = new Array(total_brushes);

// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
window.addEventListener('load', function () {

  // Load the default brush, #1
  //img.src = '1.png';
  //var img = new Image();
  brush = '1';

  camx = 0;
  camy = 0;
  px = -100;
  py = -100;

  levelParam = gup("level");
  clip.setHandCursor(true);
  clip.glue('d_clip_button', 'd_clip_container');

  function init () {
    // Find the elements
    canvas = document.getElementById('imageView');
    for (var i = 0; i < total_brushes; i++) {
      brushes[i] = document.getElementById('brush'+i);
      brushes[i].addEventListener('mousedown', ev_brush, false);
      brushes_img[i] = new Image();
      brushes_img[i].src = i + '.png';
      }

  // init the global level data structure
  for (var i = 0; i < 30; i++) {
    level[i] = "0000000000000000000000000000000000000000";
    }

  if(levelParam.length == 1200)
  {
  for (var c = 0; c < 1200; c += 40)
    {
    level[c/40] = levelParam.substr(c,40);
    }
  }

    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

    // Pencil tool instance.
    tool = new tool_pencil();

    canvas.addEventListener('mousedown', ev_canvas, false);
    canvas.addEventListener('mousemove', ev_canvas, false);
    canvas.addEventListener('mouseup',   ev_canvas, false);

    drawCanvas(camx,camy);
  }

  function replaceOneChar(s, c, n) {
    (s = s.split(''))[n] = c;
    return s.join('');
  };

function ev_brush (ev) {
  brush = this.src.substr(this.src.length - 5, 1);
}

  // This painting tool works like a drawing pencil which tracks the mouse
  // movements.
  function tool_pencil () {
    tool = this;
    this.started = false;

    // This is called when you start holding down the mouse button.
    this.mousedown = function (ev) {
        level[Math.floor(ev._y/32)+camy] = replaceOneChar(level[Math.floor(ev._y/32)+camy], brush, [Math.floor(ev._x/32)+camx]);
        tool.started = true;
        drawCanvas(camx,camy);
    };

    // This function is called every time you move the mouse. Obviously, it only
    // draws if the tool.started state is set to true (when you are holding down
    // the mouse button).
    this.mousemove = function (ev) {

    //context.strokeStyle = '#fff';
    //context.strokeRect((Math.floor(px/32))*32, Math.floor(py/32)*32, 32, 32);

    px = ev._x;
    py = ev._y;

    if (!tool.started) {
    // move the camera when you hit the edge of the screen
      if (ev._x > 600 && camx < 20) {
        camx += 1;
        //drawCanvas(camx,camy);
      }
      else if (ev._x < 40 && camx > 0) {
          camx -= 1;
         // drawCanvas(camx,camy);
        }
      if (ev._y > 440 && camy < 15) {
        camy += 1;
       // drawCanvas(camx,camy);
      }
      else if (ev._y < 40 && camy > 0) {
          camy -= 1;
         // drawCanvas(camx,camy);
        }
     }

      if (tool.started) {
        level[Math.floor(ev._y/32)+camy] = replaceOneChar(level[Math.floor(ev._y/32)+camy], brush, [Math.floor(ev._x/32)+camx]);
        }
       drawCanvas(camx,camy);
       context.lineWidth = 2;
    context.strokeStyle = '#800';
    context.strokeRect((Math.floor(ev._x/32))*32, Math.floor(ev._y/32)*32, 32, 32);

    };

    // This is called when you release the mouse button.
    this.mouseup = function (ev) {
      if (canvasContext) genMiniMap();
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
      }
    };
  }

  // The general-purpose event handler. This function just determines the mouse
  // position relative to the canvas element.
  function ev_canvas (ev) {
    if (ev.layerX || ev.layerX == 0) { // Firefox
      ev._x = ev.layerX;
      ev._y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
      ev._x = ev.offsetX;
      ev._y = ev.offsetY;
    }

    // Call the event handler of the tool.
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }

  }

  function genMiniMap () {
      minimap = canvasContext.getImageData(0, 0, 640*2, 480*2);
      var pix = minimap.data;

      // Loop over pixels, skipping every Nth since we're shrinking the image
      for (var i = 0, n = pix.length; i < n; i += 4)
          if (i % 32 == 0)
          {
          pix[(i/8)  ] = pix[i  ]; // r
          pix[(i/8)+1] = pix[i+1]; // g
          pix[(i/8)+2] = pix[i+2]; // b
          pix[(i/8)+3] = pix[i+3]; // a
          }
  }

  init();

  if (!UpdateMap.priorOldValue) {
    UpdateMap.priorOldValue = getLevelCopy();
  }

  if (afterEditorLoad) {
    afterEditorLoad();
  }

}, false); }

function drawCanvas(cx, cy) {
  for (var y = cy; y < cy+15; y++)
    for (var x = cx; x < cx+20; x++)
      context.drawImage(brushes_img[parseInt(level[y][x])], (x-camx)*32, (y-camy)*32);

  levelParam = "";
  for (var i = 0; i < 30; i++) {
    levelParam += level[i];
  }

  setLongURL(window.location.protocol + "//" + window.location.host + window.location.pathname + "?level=" + levelParam);

  if (minimap) context.putImageData(minimap,480,0,0,0,160,120);

  context.strokeStyle = '#000';
  context.strokeRect(480,0,160,120);
  context.strokeRect(480+((camx*32)/8),0+((camy*32)/8),640/8,480/8);
}

function redrawMap() {
  new UpdateMap(getLevelCopy());
}

// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
<commit_msg>Fixing image path bug<commit_after>var clip = new ZeroClipboard.Client();
var level = new Array(30);
var insp;
var levelParam;
var afterEditorLoad;
var canvasContext;
var minimap;
var context;
var tool;

function setLevel(lvl) {
  level = lvl;

  drawCanvas(camx, camy);
}

function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if (null == results)
    return "";
  else
    return results[1];
}

var UpdateMap = UndoableAction.extend({
  init: function(value, options) {
    var self = this;
    self.value = value;
    // console.log('Redrawing map...');

    this._super(function() {
      // console.log('map up');
      self.oldValue = UpdateMap.priorOldValue;
      setLevel(getLevelCopy(self.value));
      reloadMap();
      UpdateMap.priorOldValue = self.value;

      // reportLevel(self.value, 'new');
      // reportLevel(level, 'current');
      // reportLevel(self.oldValue, 'old');
    }, function() {
      // console.log('map down');
      setLevel(self.oldValue); // setLevel(getLevelCopy(self.oldValue));
      reloadMap();
      UpdateMap.priorOldValue = getLevelCopy(self.oldValue);
    });

    self.do();
  }
});

var canvas, tool, px, py, tcolor, brush, camx, camy;
var tool_default = 'rock';
var total_brushes = 10;
var brushes = new Array(total_brushes);
var brushes_img = new Array(total_brushes);

// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
window.addEventListener('load', function () {

  // Load the default brush, #1
  //img.src = '1.png';
  //var img = new Image();
  brush = '1';

  camx = 0;
  camy = 0;
  px = -100;
  py = -100;

  levelParam = gup("level");
  clip.setHandCursor(true);
  clip.glue('d_clip_button', 'd_clip_container');

  function init () {
    // Find the elements
    canvas = document.getElementById('imageView');
    for (var i = 0; i < total_brushes; i++) {
      brushes[i] = document.getElementById('brush'+i);
      brushes[i].addEventListener('mousedown', ev_brush, false);
      brushes_img[i] = new Image();
      brushes_img[i].src = brushes[i].src;
      }

  // init the global level data structure
  for (var i = 0; i < 30; i++) {
    level[i] = "0000000000000000000000000000000000000000";
    }

  if(levelParam.length == 1200)
  {
  for (var c = 0; c < 1200; c += 40)
    {
    level[c/40] = levelParam.substr(c,40);
    }
  }

    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

    // Pencil tool instance.
    tool = new tool_pencil();

    canvas.addEventListener('mousedown', ev_canvas, false);
    canvas.addEventListener('mousemove', ev_canvas, false);
    canvas.addEventListener('mouseup',   ev_canvas, false);

    drawCanvas(camx,camy);
  }

  function replaceOneChar(s, c, n) {
    (s = s.split(''))[n] = c;
    return s.join('');
  };

function ev_brush (ev) {
  brush = this.src.substr(this.src.length - 5, 1);
}

  // This painting tool works like a drawing pencil which tracks the mouse
  // movements.
  function tool_pencil () {
    tool = this;
    this.started = false;

    // This is called when you start holding down the mouse button.
    this.mousedown = function (ev) {
        level[Math.floor(ev._y/32)+camy] = replaceOneChar(level[Math.floor(ev._y/32)+camy], brush, [Math.floor(ev._x/32)+camx]);
        tool.started = true;
        drawCanvas(camx,camy);
    };

    // This function is called every time you move the mouse. Obviously, it only
    // draws if the tool.started state is set to true (when you are holding down
    // the mouse button).
    this.mousemove = function (ev) {

    //context.strokeStyle = '#fff';
    //context.strokeRect((Math.floor(px/32))*32, Math.floor(py/32)*32, 32, 32);

    px = ev._x;
    py = ev._y;

    if (!tool.started) {
    // move the camera when you hit the edge of the screen
      if (ev._x > 600 && camx < 20) {
        camx += 1;
        //drawCanvas(camx,camy);
      }
      else if (ev._x < 40 && camx > 0) {
          camx -= 1;
         // drawCanvas(camx,camy);
        }
      if (ev._y > 440 && camy < 15) {
        camy += 1;
       // drawCanvas(camx,camy);
      }
      else if (ev._y < 40 && camy > 0) {
          camy -= 1;
         // drawCanvas(camx,camy);
        }
     }

      if (tool.started) {
        level[Math.floor(ev._y/32)+camy] = replaceOneChar(level[Math.floor(ev._y/32)+camy], brush, [Math.floor(ev._x/32)+camx]);
        }
       drawCanvas(camx,camy);
       context.lineWidth = 2;
    context.strokeStyle = '#800';
    context.strokeRect((Math.floor(ev._x/32))*32, Math.floor(ev._y/32)*32, 32, 32);

    };

    // This is called when you release the mouse button.
    this.mouseup = function (ev) {
      if (canvasContext) genMiniMap();
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
      }
    };
  }

  // The general-purpose event handler. This function just determines the mouse
  // position relative to the canvas element.
  function ev_canvas (ev) {
    if (ev.layerX || ev.layerX == 0) { // Firefox
      ev._x = ev.layerX;
      ev._y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
      ev._x = ev.offsetX;
      ev._y = ev.offsetY;
    }

    // Call the event handler of the tool.
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }

  }

  function genMiniMap () {
      minimap = canvasContext.getImageData(0, 0, 640*2, 480*2);
      var pix = minimap.data;

      // Loop over pixels, skipping every Nth since we're shrinking the image
      for (var i = 0, n = pix.length; i < n; i += 4)
          if (i % 32 == 0)
          {
          pix[(i/8)  ] = pix[i  ]; // r
          pix[(i/8)+1] = pix[i+1]; // g
          pix[(i/8)+2] = pix[i+2]; // b
          pix[(i/8)+3] = pix[i+3]; // a
          }
  }

  init();

  if (!UpdateMap.priorOldValue) {
    UpdateMap.priorOldValue = getLevelCopy();
  }

  if (afterEditorLoad) {
    afterEditorLoad();
  }

}, false); }

function drawCanvas(cx, cy) {
  for (var y = cy; y < cy+15; y++)
    for (var x = cx; x < cx+20; x++)
      context.drawImage(brushes_img[parseInt(level[y][x])], (x-camx)*32, (y-camy)*32);

  levelParam = "";
  for (var i = 0; i < 30; i++) {
    levelParam += level[i];
  }

  setLongURL(window.location.protocol + "//" + window.location.host + window.location.pathname + "?level=" + levelParam);

  if (minimap) context.putImageData(minimap,480,0,0,0,160,120);

  context.strokeStyle = '#000';
  context.strokeRect(480,0,160,120);
  context.strokeRect(480+((camx*32)/8),0+((camy*32)/8),640/8,480/8);
}

function redrawMap() {
  new UpdateMap(getLevelCopy());
}

// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";

import classnames from "../classnames";

class AutocompleteSuggestion extends React.Component {
  /**
   * propTypes
   * @property {string} text Current user input text.
   * @property {string} suggestion Suggestion text of this component.
   * @property {boolean} selected Whether this suggestion is currently selected.
   * @property {Function} submit Submit function when the user clicks the suggestion.
   */
  static get propTypes() {
    return {
      text: PropTypes.string,
      suggestion: PropTypes.string,
      selected: PropTypes.bool,
      submit: PropTypes.func
    };
  }

  handleClick = () => {
    this.props.submit(this.props.suggestion);
  };

  render() {
    const { text, suggestion, selected } = this.props;

    let prefix = null;
    let prefixLen = 0;
    if (suggestion.substr(0, text.length) === text) {
      prefix = (

          {text}

      );
      prefixLen = text.length;
    }

    const className = classnames({
      "sj-suggestion": true,
      "sj-suggestion-selected": selected
    });

    return (

        {prefix}
        {suggestion.substr(prefixLen)}

    );
  }
}

export default AutocompleteSuggestion;
<commit_msg>ui: AutocompleteSuggestion make required props required<commit_after>import React from "react";
import PropTypes from "prop-types";

import classnames from "../classnames";

class AutocompleteSuggestion extends React.Component {
  /**
   * propTypes
   * @property {string} text Current user input text.
   * @property {string} suggestion Suggestion text of this component.
   * @property {boolean} selected Whether this suggestion is currently selected.
   * @property {Function} submit Submit function when the user clicks the suggestion.
   */
  static get propTypes() {
    return {
      text: PropTypes.string.isRequired,
      suggestion: PropTypes.string.isRequired,
      selected: PropTypes.bool.isRequired,
      submit: PropTypes.func.isRequired
    };
  }

  handleClick = () => {
    this.props.submit(this.props.suggestion);
  };

  render() {
    const { text, suggestion, selected } = this.props;

    let prefix = null;
    let prefixLen = 0;
    if (suggestion.substr(0, text.length) === text) {
      prefix = (

          {text}

      );
      prefixLen = text.length;
    }

    const className = classnames({
      "sj-suggestion": true,
      "sj-suggestion-selected": selected
    });

    return (

        {prefix}
        {suggestion.substr(prefixLen)}

    );
  }
}

export default AutocompleteSuggestion;
<|endoftext|>


<commit_before>/*
 * gulp-shopify-sass: lib/compiler.js
 */

// TODO: not done
/*
 * Goal: create scss syntax parser to replace RegExp, in order to add extra features, such as
 *       1. Regonize @import in comments and do not replace it
 *       2. Support includePaths option to minimize @import path length in each file
 */

'use strict';

var fs        = require('fs');
var path      = require('path');
var clonedeep = require('lodash.clonedeep');
var vfile     = require('vinyl-file');
// var vinyl     = require('vinyl');
/**
 * Get options
 *
 * @param {Object} options
 * @api private
 */

function getOptions(opts, cb) {
  var options = clonedeep(opts || {});

  // TODO: preprocess options

  // options.sourceComments = options.sourceComments || true;
  // if (options.hasOwnProperty('file')) {
  //   options.file = getInputFile(options);
  // }
  // options.outFile = getOutputFile(options);
  // options.includePaths = buildIncludePaths(options);

  // context object represents node-sass environment
  options.context = { options: options, callback: cb };

  return options;
}

/**
 * Get input file
 *
 * @param {Object} options
 * @api private
 */

function getInputFile(options) {
  return options.file ? path.resolve(options.file) : null;
}

/**
 * Get output file
 *
 * @param {Object} options
 * @api private
 */

function getOutputFile(options) {
  var outFile = options.outFile;

  if (!outFile || typeof outFile !== 'string' || (!options.data && !options.file)) {
    return null;
  }

  return path.resolve(outFile);
}

/**
 * Build an includePaths string
 * from the options.includePaths array and the SASS_PATH environment variable
 *
 * @param {Object} options
 * @api private
 */

function buildIncludePaths(options) {
  options.includePaths = options.includePaths || [];

  if (process.env.hasOwnProperty('SASS_PATH')) {
    options.includePaths = options.includePaths.concat(
      process.env.SASS_PATH.split(path.delimiter)
    );
  }

  return options.includePaths.join(path.delimiter);
}

// @param:  {string}  dir                 full path and name
// @return: {boolean}
function checkFileExist (dir) {
  try {
    fs.accessSync(dir , fs.F_OK);

    return true;
  } catch (e) {
    return false;
  }
}

// @param:  dirs                 dirs where to search the file
// @param:  file                 @import file to search
// @return: string | boolean
function analyseDirs (dirs, file) {
  // possible extension array
  const dirReg = new RegExp(/(.*\/)?(.+)$/g);
  const filenameReg = new RegExp(/^(\_)?(?:(.*(?=.scss))(.*)|(.*))$/i);

  // split whole path into path the filename
  let pathAndName = dirReg.exec(file);

  const filepath = pathAndName[1] || '';
  let filename = pathAndName[2] || '';

  // [0] original filename
  // [1] '_' if exist in the filename, otherwise undefined
  // [2] filename if it has extension .scss or .scss.liquid, otherwise undefined
  // [3] file extension if filename has extionsion .scss or .scss.liquid, otherwise undefined
  // [4] filename if it doesn't have extension, otherwise undefined
  let filenameFrags = filenameReg.exec(filename);

  // move filename[4] to filename[2] is filename[2] is undefined
  filenameFrags[2] = filenameFrags[2] || filenameFrags[4];

  let prefixs = filenameFrags[1] ? [filenameFrags[1]] : ['', '_'];
  let suffixs = filenameFrags[3] ? [filenameFrags[3]] : ['.scss', '.scss.liquid'];

  // remove original name, all index will reduce 1
  filenameFrags.shift();

  // remove filename[4] since it's been moved to [2]
  filenameFrags.pop()

  // check all possible combimations
  let dir, fullPath;
  for (let i_dir in dirs) {
    for (let i_prefix in prefixs) {
      for (let i_suffix in suffixs) {
        filenameFrags[0] = prefixs[i_prefix];
        filenameFrags[2] = suffixs[i_suffix];
        filename = filenameFrags.join('');
        fullPath = path.join(dirs[i_dir], filepath, filename);

        if (checkFileExist(fullPath)) {
          return fullPath;
        }
      }
    }
  }

  return new Error('Unable to import "' + file + '": file not found.');
}

// @param:  {object}  options
// @return: {boolean} async
function importReplacer (options, sync, prev) {

  var rex = /@import\s*(?:(?:'([^']+)')|(?:"([^"]+)"))\s*;\s*$/gmi;
  var contents = options.data;
  var dirname = path.dirname(options.file);
  var imports = {};
  var match;
  var dirs = options.includePaths.slice(0);

  if (typeof options.file !== 'undefined') {
    // Add the current file path to where to search
    dirs.unshift(path.dirname(options.file));
    // Define prev file as the current file path
    var prev = options.file;
  }

  while(match = rex.exec(contents)) {

    // [1] single quotes filename
    // [2] double quotes filename
    var importFile = match[1] || match[2];

    const fileExistCheck = {
      import: importFile,
      fullPath: analyseDirs(dirs, importFile)
    };

    // if file exists, replace it
    if(fileExistCheck) {
      imports[match[0]] = fileExistCheck;
    }
  }

  // replace @import with import file contents
  if (sync) {
    for(let filename in imports) {
      let importPath = imports[filename].import;
      let filePath = imports[filename].fullPath;
      let fileObj;
      let fileContents;

      if (options.importer) {
        fileObj = options.importer(importPath, prev);
      }
      else {
        fileObj = {file: filePath};
      }

      if (fileObj.content)
        fileContents = fileObj.content;
      else
        fileContents = vfile.readSync(fileObj.file);

      let newFileContent = importReplacer({
        data: fileContents,
        includePaths: dirs,
        importer: options.importer
      }, true, filename);
        file: fileObj.file,

      contents = contents.replace(new RegExp(filename, 'g'), function() {
        // http://stackoverflow.com/a/28103073
        return newFileContent
      });
    }

    return contents;
  } else {

    let prevPromise = Promise.resolve(contents);

    for(let filename in imports) {
      let filePath = imports[filename].fullPath;
      let importPath = imports[filename].import;
      prevPromise = prevPromise.then(contents => {

        if (options.importer) {
          var fileDatasPromise = new Promise ((resolve, reject) => {
            let ret = options.importer(importPath, prev, resolve);
            if (ret) {
              resolve(ret);
            }
          });
        }
        else {
          var fileDatasPromise = Promise.resolve({file: filePath});
        }

        return fileDatasPromise.then(fileObj => {
          let fileContents;

          if (fileObj.content)
            fileContents = fileObj.content;
          else
            fileContents = vfile.readSync(fileObj.file);

          // Do the same for the file just read
          return importReplacer({
            includePaths: dirs,
            importer: options.importer
          }, false, filename);
            data: fileContents,
            file: fileObj.file,
        }).then(newFileContent => {
          return contents.replace(new RegExp(filename, 'g'), function() {
            // http://stackoverflow.com/a/28103073
            return newFileContent
          });
        });
      });
    }

    return prevPromise;
  }
}

/**
 * Render
 *
 * @param {Object}    opts
 * @param {Function}  cb
 * @api public
 */

module.exports.render = function(opts, cb, errorCb) {
  var options = getOptions(opts, cb);

  importReplacer(options, false).then(cb, errorCb);
};

/**
 * Render sync
 *
 * @param {Object} options
 * @api public
 */

module.exports.renderSync = function(options) {
  // var options = getOptions(opts);
  // var importer = options.importer;
  // var status = importReplacer(options);

  return importReplacer(options, true);

  // var result = options.result;

  // if (status) {
  //   result.stats = endStats(result.stats);
  //   return result;
  // }

  // throw assign(new Error(), JSON.parse(result.error));
};
<commit_msg>Pass option object to sub files<commit_after>/*
 * gulp-shopify-sass: lib/compiler.js
 */

// TODO: not done
/*
 * Goal: create scss syntax parser to replace RegExp, in order to add extra features, such as
 *       1. Regonize @import in comments and do not replace it
 *       2. Support includePaths option to minimize @import path length in each file
 */

'use strict';

var util      = require('util');
var fs        = require('fs');
var path      = require('path');
var clonedeep = require('lodash.clonedeep');
var vfile     = require('vinyl-file');
// var vinyl     = require('vinyl');
/**
 * Get options
 *
 * @param {Object} options
 * @api private
 */

function getOptions(opts, cb) {
  var options = clonedeep(opts || {});

  // TODO: preprocess options

  // options.sourceComments = options.sourceComments || true;
  // if (options.hasOwnProperty('file')) {
  //   options.file = getInputFile(options);
  // }
  // options.outFile = getOutputFile(options);
  // options.includePaths = buildIncludePaths(options);

  // context object represents node-sass environment
  options.context = { options: options, callback: cb };

  return options;
}

/**
 * Get input file
 *
 * @param {Object} options
 * @api private
 */

function getInputFile(options) {
  return options.file ? path.resolve(options.file) : null;
}

/**
 * Get output file
 *
 * @param {Object} options
 * @api private
 */

function getOutputFile(options) {
  var outFile = options.outFile;

  if (!outFile || typeof outFile !== 'string' || (!options.data && !options.file)) {
    return null;
  }

  return path.resolve(outFile);
}

/**
 * Build an includePaths string
 * from the options.includePaths array and the SASS_PATH environment variable
 *
 * @param {Object} options
 * @api private
 */

function buildIncludePaths(options) {
  options.includePaths = options.includePaths || [];

  if (process.env.hasOwnProperty('SASS_PATH')) {
    options.includePaths = options.includePaths.concat(
      process.env.SASS_PATH.split(path.delimiter)
    );
  }

  return options.includePaths.join(path.delimiter);
}

// @param:  {string}  dir                 full path and name
// @return: {boolean}
function checkFileExist (dir) {
  try {
    fs.accessSync(dir , fs.F_OK);

    return true;
  } catch (e) {
    return false;
  }
}

// @param:  dirs                 dirs where to search the file
// @param:  file                 @import file to search
// @return: string | boolean
function analyseDirs (dirs, file) {
  // possible extension array
  const dirReg = new RegExp(/(.*\/)?(.+)$/g);
  const filenameReg = new RegExp(/^(\_)?(?:(.*(?=.scss))(.*)|(.*))$/i);

  // split whole path into path the filename
  let pathAndName = dirReg.exec(file);

  const filepath = pathAndName[1] || '';
  let filename = pathAndName[2] || '';

  // [0] original filename
  // [1] '_' if exist in the filename, otherwise undefined
  // [2] filename if it has extension .scss or .scss.liquid, otherwise undefined
  // [3] file extension if filename has extionsion .scss or .scss.liquid, otherwise undefined
  // [4] filename if it doesn't have extension, otherwise undefined
  let filenameFrags = filenameReg.exec(filename);

  // move filename[4] to filename[2] is filename[2] is undefined
  filenameFrags[2] = filenameFrags[2] || filenameFrags[4];

  let prefixs = filenameFrags[1] ? [filenameFrags[1]] : ['', '_'];
  let suffixs = filenameFrags[3] ? [filenameFrags[3]] : ['.scss', '.scss.liquid'];

  // remove original name, all index will reduce 1
  filenameFrags.shift();

  // remove filename[4] since it's been moved to [2]
  filenameFrags.pop()

  // check all possible combimations
  let dir, fullPath;
  for (let i_dir in dirs) {
    for (let i_prefix in prefixs) {
      for (let i_suffix in suffixs) {
        filenameFrags[0] = prefixs[i_prefix];
        filenameFrags[2] = suffixs[i_suffix];
        filename = filenameFrags.join('');
        fullPath = path.join(dirs[i_dir], filepath, filename);

        if (checkFileExist(fullPath)) {
          return fullPath;
        }
      }
    }
  }

  return new Error('Unable to import "' + file + '": file not found.');
}

// @param:  {object}  options
// @return: {boolean} async
function importReplacer (options, sync, prev) {

  var rex = /@import\s*(?:(?:'([^']+)')|(?:"([^"]+)"))\s*;\s*$/gmi;
  var contents = options.data;
  var dirname = path.dirname(options.file);
  var imports = {};
  var match;
  var dirs = options.includePaths.slice(0);

  if (typeof options.file !== 'undefined') {
    // Add the current file path to where to search
    dirs.unshift(path.dirname(options.file));
    // Define prev file as the current file path
    var prev = options.file;
  }

  while(match = rex.exec(contents)) {

    // [1] single quotes filename
    // [2] double quotes filename
    var importFile = match[1] || match[2];

    const fileExistCheck = {
      import: importFile,
      fullPath: analyseDirs(dirs, importFile)
    };

    // if file exists, replace it
    if(fileExistCheck) {
      imports[match[0]] = fileExistCheck;
    }
  }

  // replace @import with import file contents
  if (sync) {
    for(let filename in imports) {
      let importPath = imports[filename].import;
      let filePath = imports[filename].fullPath;
      let fileObj;
      let fileContents;

      if (options.importer) {
        fileObj = options.importer(importPath, prev);
      }
      else {
        fileObj = {file: filePath};
      }

      if (fileObj.content)
        fileContents = fileObj.content;
      else
        fileContents = vfile.readSync(fileObj.file);

      let newFileContent = importReplacer(util._extend(options, {
        data: fileContents,
        file: fileObj.file,
        includePaths: dirs
      }), sync, filename);

      contents = contents.replace(new RegExp(filename, 'g'), function() {
        // http://stackoverflow.com/a/28103073
        return newFileContent
      });
    }

    return contents;
  } else {

    let prevPromise = Promise.resolve(contents);

    for(let filename in imports) {
      let filePath = imports[filename].fullPath;
      let importPath = imports[filename].import;
      prevPromise = prevPromise.then(contents => {

        if (options.importer) {
          var fileDatasPromise = new Promise ((resolve, reject) => {
            let ret = options.importer(importPath, prev, resolve);
            if (ret) {
              resolve(ret);
            }
          });
        }
        else {
          var fileDatasPromise = Promise.resolve({file: filePath});
        }

        return fileDatasPromise.then(fileObj => {
          let fileContents;

          if (fileObj.content)
            fileContents = fileObj.content;
          else
            fileContents = vfile.readSync(fileObj.file);

          // Do the same for the file just read
          return importReplacer(util._extend(options, {
            data: fileContents,
            file: fileObj.file,
            includePaths: dirs
          }), sync, filename);
        }).then(newFileContent => {
          return contents.replace(new RegExp(filename, 'g'), function() {
            // http://stackoverflow.com/a/28103073
            return newFileContent
          });
        });
      });
    }

    return prevPromise;
  }
}

/**
 * Render
 *
 * @param {Object}    opts
 * @param {Function}  cb
 * @api public
 */

module.exports.render = function(opts, cb, errorCb) {
  var options = getOptions(opts, cb);

  importReplacer(options, false).then(cb, errorCb);
};

/**
 * Render sync
 *
 * @param {Object} options
 * @api public
 */

module.exports.renderSync = function(options) {
  // var options = getOptions(opts);
  // var importer = options.importer;
  // var status = importReplacer(options);

  return importReplacer(options, true);

  // var result = options.result;

  // if (status) {
  //   result.stats = endStats(result.stats);
  //   return result;
  // }

  // throw assign(new Error(), JSON.parse(result.error));
};
<|endoftext|>


<commit_before>/*global describe, it, before, beforeEach, after, afterEach, should, sinon */

var Readable = require("stream").Readable;
var TokenFilter = require("../");

describe("filtering", function () {
    describe("instantiation", function () {
        it("works as factory", function () {
            var instance;
            should.not.throw(function () {
                // jshint newcap:false
                instance = TokenFilter();
            });
            instance.should.be.instanceOf(TokenFilter);
            // sinon.stub(TokenFilter, "readConfig");
        });
    });
    describe("without context", function () {
        it("reads config from JSON file", function (done) {
            var instance = new TokenFilter({
                filters: ["test/fixtures/config.json"]
            });
            instance.on("context", function (context) {
                should.exist(context);
                context.should.deep.equal({
                    "foo": "bar"
                });
                done();
            });
        });
        it("reads config from properties file", function (done) {
            var instance = new TokenFilter({
                filters: ["test/fixtures/config.properties"]
            });
            instance.on("context", function (context) {
                should.exist(context);
                context.should.deep.equal({
                    "foo": "bar"
                });
                done();
            });
        });
        it("reads config from both file types", function (done) {
            var instance = new TokenFilter({
                filters: [
                    "test/fixtures/config.json",
                    "test/fixtures/config.properties"
                ]
            });
            instance.on("context", function (context) {
                should.exist(context);
                context.should.deep.equal({
                    "foo": "bar"
                });
                done();
            });
        });
        it("replaces tokens in stream");
    });
    describe("with context", function () {
        it("replaces tokens in stream");
    });
});
<commit_msg>Better tests.<commit_after>/*global describe, it, before, beforeEach, after, afterEach, should, sinon */

var fs = require("graceful-fs");
var Transform = require("stream").Transform;

var TokenFilter = require("../");

describe("TokenFilter", function () {
    describe("instantiation", function () {
        beforeEach(function () {
            sinon.stub(TokenFilter, "readConfig");
        });
        afterEach(function () {
            TokenFilter.readConfig.restore();
        });
        it("should be a subclass of stream.Transform", function () {
            (new TokenFilter()).should.be.instanceOf(Transform);
        });
        it("should initialize properties", function () {
            var instance = new TokenFilter();
            instance.should.have.property("tokenRegex").that.is.an.instanceOf(RegExp);
            instance.should.have.property("replaceToken").that.is.a("function");
            instance.should.have.property("_encoding", "utf8");
            instance.should.have.property("_queue").that.is.an("array");
        });
        it("should work as a factory", function () {
            var instance;
            should.not.throw(function () {
                // jshint newcap:false
                instance = TokenFilter();
            });
            instance.should.be.instanceOf(TokenFilter);
        });
    });
    describe("#readConfig()", function () {
        beforeEach(function () {
            sinon.stub(fs, "readFile");
        });
        afterEach(function () {
            fs.readFile.restore();
        });
        it("should return callback early when no pending filters", function (done) {
            TokenFilter.readConfig({}, done);
        });
        it("should pass readError to callback", function (done) {
            var stubReadError = new Error("stubReadError");
            fs.readFile.withArgs("unreadable").yields(stubReadError);
            TokenFilter.readConfig({
                filters: ["unreadable"]
            }, function (readError) {
                should.exist(readError);
                readError.should.have.property("message", "stubReadError");
                done();
            });
        });
        it("should pass parseError to callback", function (done) {
            fs.readFile.withArgs("bad.json").yields(null, "bad.json");
            TokenFilter.readConfig({
                filters: ["bad.json"]
            }, function (parseError) {
                should.exist(parseError);
                parseError.should.be.an.instanceOf(SyntaxError);
                done();
            });
        });
        it("should mix multiple filters into one context", function (done) {
            fs.readFile.withArgs("good.json").yields(null, '{ "good": true }');
            fs.readFile.withArgs("good.properties").yields(null, "good = mixed");
            TokenFilter.readConfig({
                filters: ["good.json", "good.properties"]
            }, function (err, context) {
                should.not.exist(err);
                should.exist(context);
                context.should.deep.equal({ "good": "mixed" });
                done();
            });
        });
    });
    describe("context", function () {
        beforeEach(function () {
            sinon.stub(TokenFilter, "readConfig");
        });
        afterEach(function () {
            TokenFilter.readConfig.restore();
        });
        describe("when absent", function () {
            it("should call #readConfig()", function () {
                var instance = new TokenFilter();
                TokenFilter.readConfig.should.have.callCount(1);
            });
            it("should pass config and bound callback to #readConfig()", function () {
                var instance = new TokenFilter();
                TokenFilter.readConfig.should.have.been.calledWith(
                    sinon.match.object,
                    sinon.match.func
                );
            });
        });
        describe("when present", function () {
            it("immediately emits context event");
        });
        describe("after filtering", function () {
            it("should be emitted in context event", function (done) {
                TokenFilter.readConfig.yieldsAsync(null, { "foo": "bar" });
                var instance = new TokenFilter();
                instance.once("context", function (context) {
                    should.exist(context);
                    context.should.deep.equal({
                        "foo": "bar"
                    });
                    done();
                });
            });
            it("should store context in instance property", function (done) {
                TokenFilter.readConfig.yieldsAsync(null, { "foo": "bar" });
                var instance = new TokenFilter();
                instance.once("context", function (context) {
                    instance.should.have.property("context").that.deep.equals(context);
                    done();
                });
            });
            it("should set _passThrough state when context missing", function (done) {
                TokenFilter.readConfig.yieldsAsync();
                var instance = new TokenFilter();
                instance.once("context", function (context) {
                    instance.should.have.property("_passThrough").that.equals(true);
                    done();
                });
            });
            it("should set _passThrough state when context empty", function (done) {
                TokenFilter.readConfig.yieldsAsync(null, {});
                var instance = new TokenFilter();
                instance.once("context", function (context) {
                    instance.should.have.property("_passThrough").that.equals(true);
                    done();
                });
            });
            it("should emit error from readConfig()", function (done) {
                TokenFilter.readConfig.yieldsAsync("boom");
                var instance = new TokenFilter();
                instance.once("error", function (error) {
                    should.exist(error);
                    error.should.equal("boom");
                    done();
                });
            });
        });
    });
    describe("piping", function () {
        it("replaces tokens in stream");
    });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var Spooky = require("spooky");
var request = require('request');
var curl = require('curlrequest');
var express = require("express");
var LineByLineReader = require('line-by-line');
var app = express();

var Greeting = 'Hello ghost';
var counter = 0;
var currentIp = 0;
var visitedIp = [];
var localIps = [];
var herokuAppsUrls = [];

//Read lines of ip use them to make request before resulting to gimmeproxy
function getLocalProxy1(){
	lr = new LineByLineReader('rawProxy.txt');
	lr.on('error', function (err) {
		console.log('error while reading file');
		Greeting = err;
	});

	lr.on('line', function (line) {
		localIps.push(line.toString());
	});

	lr.on('end', function () {
		var nr = [];
		var i;
		for(i=0; i<localIps.length; i++){
			if(localIps[i].length>30){
				var temp = localIps[i].substr(localIps[i].indexOf('\t')).trim();
				temp = temp.substr(0 , temp.indexOf('\tflag'));
				temp=temp.trim();
				var ip = temp.substr(0 , temp.indexOf(' ')).trim();
				var port = temp.substr(temp.indexOf('\t')).trim();
				nr.push(ip+':'+port);
			}
		}

		localIps = nr;
		//
		getLocalProxy();
	});
};

//Read lines of ip use them to make request before resulting to gimmeproxy
function getLocalProxy(){
	lr = new LineByLineReader('proxies.txt');
	lr.on('error', function (err) {
		console.log('error while reading file');
		Greeting = err;
	});

	lr.on('line', function (line) {
		localIps.push(line.toString());
	});

	lr.on('end', function () {
		console.log(localIps);

		pingGhostWhite();
	});
}

function pingGhostWhite(){
    console.log('heroku ping here');
    //Read lines of ip use them to make request before resulting to gimmeproxy
	ha = new LineByLineReader('herokuapps.txt');
	ha.on('error', function (err) {
		console.log('error while reading file');
	});

	ha.on('line', function (line) {
		herokuAppsUrls.push(line.toString());
	});

	ha.on('end', function () {
	   console.log(herokuAppsUrls);

	   //do pinging
	   var currentUrl = 0;
	   function doPing(){
	       if(currentUrl < herokuAppsUrls.length){
		        request.get(herokuAppsUrls[currentUrl] , function(err , response , body){
					 if(err){
						 console.log(err);
						 currentUrl++;
						 doPing();
					 }
					 else {
					     Greeting = herokuAppsUrls[currentUrl]+' test done';
						 console.log(herokuAppsUrls[currentUrl]+' test done');
						 currentUrl++;
						 doPing();
					 }
				 });
		   }
		   else{
		      console.log('Pinging done');
			  runGhostProxy();
		      return;
		   }
	   };

	   doPing();
	});
}

//

var runGhostProxy = function(){
	console.log('starting ghost');
	function getIp(){
		if(currentIp<localIps.length){
			console.log('getting local ip');
			testIP('http://'+localIps[currentIp]);
		}
		else{
			request.get('http://gimmeproxy.com/api/get/14ae54be70be33b780003ad1f370e8a5/?timeout=0' , function(err , response , body){
				 if(err){
					 console.log('cannot get ip address');
					 runGhostProxy();
				 }
				 else {
					 console.log(JSON.parse(body).curl);
					 testIP(JSON.parse(body).curl);
				 }
			 });
		}
	};
	getIp();

	function testIP(ip){
		 currentIp++;
		 console.log('testing proxy');

		 //check if proxy has already been used for this round
		 if(visitedIp.indexOf(ip)>=0){
			 console.log('ip already visited');
			 runGhostProxy();
		 }
		 else if(!(ip.indexOf('http')>=0 && ip.indexOf('https')<=0)){
			  console.log('Not http proxy');
			  runGhostProxy();
		 }
		 else {
			 var options = {
				url: 'https://fg1.herokuapp.com',
				retries: 5,
				headers: {
					'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
				},
				timeout: 15,
				proxy: ip
			 };

			 curl.request(options, function(err, res) {
				   if(err){
						 console.log('Cannot test proxy');
						 runGhostProxy();
					 }
					 else {
						 if(res){
							 console.log('test done');
							 visitedIp.push(ip);
							 continueT(ip);
						 }
						 else {
							  console.log('invalid proxy');
							  runGhostProxy();
						 }

					 }
			 });
	     }
	}

	function continueT(ip){

		console.log('process starting '+ip);
		var spooky = new Spooky(
			 {
				child: {
					transport: 'http',
					proxy: ip
				},
				casper: {
					logLevel: 'debug',
					verbose: true
				}
			 },
			 function(err){

				 if (err) {
					e = new Error('Failed to initialize SpookyJS');
					e.details = err;
					throw e;
				 }

				//start the main site visiting process
				console.log('here init');
				spooky.start('https://fg2.herokuapp.com');
				spooky.then(function(){
					 this.urls = [
						['https://crd.ht/71wMWN3' , '[value=cr]'],
						//['http://cur.lv/ur5hp' , 'a'],
						//['http://www.linkbucks.com/fk8Y' , 'a']
					];
					this.count= 0;

					this.visitAll = function(detail){
						this.start(detail[0])
						this.thenClick(detail[1] , function() {
								if(this.count==this.urls.length-1){
									phantom.clearCookies();
									this.emit('hi', 'Hello, from ' + this.evaluate(function () {
										return document.title;
									}));
								}
								else{
									 phantom.clearCookies();
									 this.count++;
									 this.visitAll(this.urls[this.count]);
								}

						});
					};
					this.visitAll(this.urls[this.count]);
				});

				spooky.run();

			});

			// logs and listeners
			spooky.on('error', function (e, stack) {
				console.log('here');
				console.error(e);

				if (stack) {
					console.log(stack);
				}
				spooky.destroy();
				runGhostProxy();
			});

			// Uncomment this block to see all of the things Casper has to say.
			// There are a lot.
			// He has opinions.
			spooky.on('console', function (line) {
				console.log(line);
			});

			spooky.on('hi', function (greeting) {
				console.log(greeting);
				counter+=1;
				Greeting = greeting;
				spooky.destroy();
				runGhostProxy();
			});

      }
	  return;
};
//
runGhostProxy();

//app.use(express.logger());
app.get('/', function(request, response) {
    response.send(Greeting+" visited "+counter+" times ");
});

//restarts the app after every 500 visits and 40 minutes of app's uptime
var currentMin = 0;
setInterval(function(){
	currentMin++;
	if((counter>=500 && currentMin>40) || currentMin>40){
	    //ping other apps before restarting
		 process.exit(0);
	}
} , 60000);

var port = process.env.PORT || 5003;
app.listen(port, function() {
    console.log("Listening on " + port);
});<commit_msg>staging change<commit_after>#!/usr/bin/env node

var Spooky = require("spooky");
var request = require('request');
var curl = require('curlrequest');
var express = require("express");
var LineByLineReader = require('line-by-line');
var app = express();

var Greeting = 'Hello ghost';
var counter = 0;
var currentIp = 0;
var visitedIp = [];
var localIps = [];
var herokuAppsUrls = [];

//Read lines of ip use them to make request before resulting to gimmeproxy
function getLocalProxy1(){
	lr = new LineByLineReader('rawProxy.txt');
	lr.on('error', function (err) {
		console.log('error while reading file');
		Greeting = err;
	});

	lr.on('line', function (line) {
		localIps.push(line.toString());
	});

	lr.on('end', function () {
		var nr = [];
		var i;
		for(i=0; i<localIps.length; i++){
			if(localIps[i].length>30){
				var temp = localIps[i].substr(localIps[i].indexOf('\t')).trim();
				temp = temp.substr(0 , temp.indexOf('\tflag'));
				temp=temp.trim();
				var ip = temp.substr(0 , temp.indexOf(' ')).trim();
				var port = temp.substr(temp.indexOf('\t')).trim();
				nr.push(ip+':'+port);
			}
		}

		localIps = nr;
		//
		getLocalProxy();
	});
};

//Read lines of ip use them to make request before resulting to gimmeproxy
function getLocalProxy(){
	lr = new LineByLineReader('proxies.txt');
	lr.on('error', function (err) {
		console.log('error while reading file');
		Greeting = err;
	});

	lr.on('line', function (line) {
		localIps.push(line.toString());
	});

	lr.on('end', function () {
		console.log(localIps);

		pingGhostWhite();
	});
}

function pingGhostWhite(){
    console.log('heroku ping here');
    //Read lines of ip use them to make request before resulting to gimmeproxy
	ha = new LineByLineReader('herokuapps.txt');
	ha.on('error', function (err) {
		console.log('error while reading file');
	});

	ha.on('line', function (line) {
		herokuAppsUrls.push(line.toString());
	});

	ha.on('end', function () {
	   console.log(herokuAppsUrls);

	   //do pinging
	   var currentUrl = 0;
	   function doPing(){
	       if(currentUrl < herokuAppsUrls.length){
		        request.get(herokuAppsUrls[currentUrl] , function(err , response , body){
					 if(err){
						 console.log(err);
						 currentUrl++;
						 doPing();
					 }
					 else {
					     Greeting = herokuAppsUrls[currentUrl]+' test done';
						 console.log(herokuAppsUrls[currentUrl]+' test done');
						 currentUrl++;
						 doPing();
					 }
				 });
		   }
		   else{
		      console.log('Pinging done');
			  runGhostProxy();
		      return;
		   }
	   };

	   doPing();
	});
}

pingGhostWhite();

//

var runGhostProxy = function(){
	console.log('starting ghost');
	function getIp(){
		if(currentIp<localIps.length){
			console.log('getting local ip');
			testIP('http://'+localIps[currentIp]);
		}
		else{
			request.get('http://gimmeproxy.com/api/get//?timeout=0' , function(err , response , body){
				 if(err){
					 console.log('cannot get ip address');
					 runGhostProxy();
				 }
				 else {
					 console.log(JSON.parse(body).curl);
					 testIP(JSON.parse(body).curl);
				 }
			 });
		}
	};
	getIp();

	function testIP(ip){
		 currentIp++;
		 console.log('testing proxy');

		 //check if proxy has already been used for this round
		 if(visitedIp.indexOf(ip)>=0){
			 console.log('ip already visited');
			 runGhostProxy();
		 }
		 else if(!(ip.indexOf('http')>=0 && ip.indexOf('https')<=0)){
			  console.log('Not http proxy');
			  runGhostProxy();
		 }
		 else {
			 var options = {
				url: 'https://fg1.herokuapp.com',
				retries: 5,
				headers: {
					'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
				},
				timeout: 15,
				proxy: ip
			 };

			 curl.request(options, function(err, res) {
				   if(err){
						 console.log('Cannot test proxy');
						 runGhostProxy();
					 }
					 else {
						 if(res){
							 console.log('test done');
							 visitedIp.push(ip);
							 continueT(ip);
						 }
						 else {
							  console.log('invalid proxy');
							  runGhostProxy();
						 }

					 }
			 });
	     }
	}

	function continueT(ip){

		console.log('process starting '+ip);
		var spooky = new Spooky(
			 {
				child: {
					transport: 'http',
					proxy: ip
				},
				casper: {
					logLevel: 'debug',
					verbose: true
				}
			 },
			 function(err){

				 if (err) {
					e = new Error('Failed to initialize SpookyJS');
					e.details = err;
					throw e;
				 }

				//start the main site visiting process
				console.log('here init');
				spooky.start('https://fg2.herokuapp.com');
				spooky.then(function(){
					 this.urls = [
						['https://crd.ht/71wMWN3' , '[value=cr]'],
						//['http://cur.lv/ur5hp' , 'a'],
						//['http://www.linkbucks.com/fk8Y' , 'a']
					];
					this.count= 0;

					this.visitAll = function(detail){
						this.start(detail[0])
						this.thenClick(detail[1] , function() {
								if(this.count==this.urls.length-1){
									phantom.clearCookies();
									this.emit('hi', 'Hello, from ' + this.evaluate(function () {
										return document.title;
									}));
								}
								else{
									 phantom.clearCookies();
									 this.count++;
									 this.visitAll(this.urls[this.count]);
								}

						});
					};
					this.visitAll(this.urls[this.count]);
				});

				spooky.run();

			});

			// logs and listeners
			spooky.on('error', function (e, stack) {
				console.log('here');
				console.error(e);

				if (stack) {
					console.log(stack);
				}
				spooky.destroy();
				runGhostProxy();
			});

			// Uncomment this block to see all of the things Casper has to say.
			// There are a lot.
			// He has opinions.
			spooky.on('console', function (line) {
				console.log(line);
			});

			spooky.on('hi', function (greeting) {
				console.log(greeting);
				counter+=1;
				Greeting = greeting;
				spooky.destroy();
				runGhostProxy();
			});

      }
	  return;
};

//app.use(express.logger());
app.get('/', function(request, response) {
    response.send(Greeting+" visited "+counter+" times ");
});

//restarts the app after every 500 visits and 40 minutes of app's uptime
var currentMin = 0;
setInterval(function(){
	currentMin++;
	if((counter>=500 && currentMin>40) || currentMin>40){
	    //ping other apps before restarting
		 process.exit(0);
	}
} , 60000);

var port = process.env.PORT || 5003;
app.listen(port, function() {
    console.log("Listening on " + port);
});<|endoftext|>


<commit_before>//list of tests
var testFiles = [
	"mouseposition_osgb_test.js",
	"screenposition_osgb_test.js",
	"points_test.js",
	"conversion_test.js",
	"mobile_test.js",
	"params_test.js",
	"config_test.js",
	"os_map_test.js",
	"loader_test.js"
];

testingPaths.loader = '../js/loader'; //this is a hack for testing, so no need for it to appear in app.js
requirejs.config({
    paths: testingPaths,
    shim: {
        sinon: {
            exports: 'sinon'
        },
        loader: {
            exports: 'loadOsMap'
        }
    }
});

if (window.__karma__ == undefined) {
	//we've just opened a qunit page locally for dev purposes
	setupNonKarma();
} else {
	//we're running karma as part of the build
	setupKarma();
}

function setupNonKarma() {
	QUnit.config.autostart = false;

	var tests = [];
	var tests = testFiles.map(function (testFile) {
		return '../' + testFile;
	})

	// Resolve all testModules and then start the Test Runner.
	requirejs(tests, function(){
		QUnit.load();
		QUnit.start();
	});
}

function setupKarma() {

	//hacking in some stuff that would be useful in phantom js
	if (String.prototype.endsWith === undefined) {
		String.prototype.endsWith = function(suffix) {
			return this.indexOf(suffix, this.length - suffix.length) !== -1;
		};
	}

	var tests = [];
	var tests = testFiles.map(function (testFile) {
		return '/base/test/' + testFile;
	});

	requirejs.config({
		baseUrl: '/base/js',

		//load our tests
		deps: tests,

		//kick off tests only once requirejs has finished, but only once
		callback: function() {
			if (window.KARMA_TESTS_STARTED === true) {
				return;
			} else {
				window.KARMA_TESTS_STARTED = true;
				window.__karma__.start();
			}
		}
	});
}
<commit_msg>Trying to get some build stability back<commit_after>//list of tests
var testFiles = [
	//commenting a few until we've resolved the issues with Squire mucking up leaflet plugins
	//"mouseposition_osgb_test.js",
	//"screenposition_osgb_test.js",
	//"points_test.js",
	"conversion_test.js",
	"mobile_test.js",
	"params_test.js",
	"config_test.js",
	"os_map_test.js",
	"loader_test.js"
];

testingPaths.loader = '../js/loader'; //this is a hack for testing, so no need for it to appear in app.js
requirejs.config({
    paths: testingPaths,
    shim: {
        sinon: {
            exports: 'sinon'
        },
        loader: {
            exports: 'loadOsMap'
        }
    }
});

if (window.__karma__ == undefined) {
	//we've just opened a qunit page locally for dev purposes
	setupNonKarma();
} else {
	//we're running karma as part of the build
	setupKarma();
}

function setupNonKarma() {
	QUnit.config.autostart = false;

	var tests = [];
	var tests = testFiles.map(function (testFile) {
		return '../' + testFile;
	})

	// Resolve all testModules and then start the Test Runner.
	requirejs(tests, function(){
		QUnit.load();
		QUnit.start();
	});
}

function setupKarma() {

	//hacking in some stuff that would be useful in phantom js
	if (String.prototype.endsWith === undefined) {
		String.prototype.endsWith = function(suffix) {
			return this.indexOf(suffix, this.length - suffix.length) !== -1;
		};
	}

	var tests = [];
	var tests = testFiles.map(function (testFile) {
		return '/base/test/' + testFile;
	});

	requirejs.config({
		baseUrl: '/base/js',

		//load our tests
		deps: tests,

		//kick off tests only once requirejs has finished, but only once
		callback: function() {
			if (window.KARMA_TESTS_STARTED === true) {
				return;
			} else {
				window.KARMA_TESTS_STARTED = true;
				window.__karma__.start();
			}
		}
	});
}
<|endoftext|>


<commit_before>/*
Documentation for g:convert validator:
sample url: http://localhost:3000/api/validatorGconvert?genes=ATM ATP ATM
output: {"unrecognized":["ATP"],"duplicate":["ATM"],"geneInfo":[{"HGNC_symbol":"ATM","HGNC_id":"HGNC:795"}]}
*/

const request = require('request');
const _ = require('lodash');
const { validOrganism } = require('./validityInfo');
const { validTarget } = require('./validityInfo');

const defaultOptions = {
  'output': 'mini',
  'organism': 'hsapiens',
  'target': 'HGNC'
};

class InvalidInfoError extends Error {
  constructor(invalidOrganism, invalidTarget, message) {
    super(message);
    this.invalidTarget = invalidTarget;
    this.invalidOrganism = invalidOrganism;
  }
}

const gConvertURL = 'https://biit.cs.ut.ee/gprofiler_archive3/r1741_e90_eg37/web/gconvert.cgi';

// convert offical synonyms to gConvert names
const convertGConvertNames = (gConvertName) => {
  if (gConvertName === 'HGNCSYMBOL') { return 'HGNC'; }
  if (gConvertName === 'HGNC') { return 'HGNC_ACC'; }
  if (gConvertName === 'UNIPROT') { return 'UNIPROTSWISSPROT'; }
  if (gConvertName === 'NCBIGENE') { return 'ENTREZGENE_ACC'; }
  return gConvertName;
};

const validatorGconvert = (query, userOptions) => {
  const promise = new Promise((resolve, reject) => {
    const formData = _.assign({}, defaultOptions, userOptions, { query: query });
    console.log(formData);
    formData.organism =  formData.organism.toLowerCase();
    const initialTarget = formData.target.toUpperCase();
    console.log(initialTarget)
    console.log(convertGConvertNames);
    console.log(convertGConvertNames(initialTarget));
    formData.target = convertGConvertNames(initialTarget);
    const invalidInfo = {invalidTarget: '', invalidOrganism: ''};
    if (!validOrganism.includes(formData.organism)) {
      invalidInfo.invalidOrganism = formData.organism;
    }
    if (!validTarget.includes(formData.target)) {
      invalidInfo.invalidTarget = formData.target;
    }
    if (invalidInfo.invalidOrganism != '' || invalidInfo.invalidTarget != '') {
      reject(new InvalidInfoError(invalidInfo.invalidOrganism, invalidInfo.invalidTarget, ''));
    }

    request.post({ url: gConvertURL, formData: formData }, (err, httpResponse, body) => {
      if (err) {
        reject(err);
      }
      const geneInfoList = _.map(body.split('\n'), ele => { return ele.split('\t'); });
      geneInfoList.splice(-1, 1); // remove last element ''

      const unrecognized = [];
      const duplicate = [];
      const geneInfo = [];
      const initialAliasIndex = 1;
      const convertedAliasIndex = 3;
      _.forEach(geneInfoList, info => {
        if (info[convertedAliasIndex] === 'N/A') {
          if (_.filter(unrecognized, ele => ele === info[initialAliasIndex]).length === 0) {
            unrecognized.push(info[initialAliasIndex]);
          }
        } else {
          if (_.filter(geneInfoList, ele => ele[convertedAliasIndex] === info[convertedAliasIndex]).length > 1 && _.filter(duplicate, ele => ele === info[initialAliasIndex]).length === 0) {
            duplicate.push(info[initialAliasIndex]);
          }
          if (_.filter(geneInfo, ele => ele.initialAlias === info[initialAliasIndex]).length === 0) {
            geneInfo.push({ initialAlias: info[initialAliasIndex], convertedAlias: info[convertedAliasIndex] });
          }
        }
      });

      const ret = { options: {target: initialTarget, organism: formData.organism}, unrecognized: unrecognized, duplicate: duplicate, geneInfo: geneInfo };
      resolve(ret);
    });
  });
  return promise;
};

module.exports = { validatorGconvert };
<commit_msg>remove comments<commit_after>/*
Documentation for g:convert validator:
sample url: http://localhost:3000/api/validatorGconvert?genes=ATM ATP ATM
output: {"unrecognized":["ATP"],"duplicate":["ATM"],"geneInfo":[{"HGNC_symbol":"ATM","HGNC_id":"HGNC:795"}]}
*/

const request = require('request');
const _ = require('lodash');
const { validOrganism } = require('./validityInfo');
const { validTarget } = require('./validityInfo');

const defaultOptions = {
  'output': 'mini',
  'organism': 'hsapiens',
  'target': 'HGNC'
};

class InvalidInfoError extends Error {
  constructor(invalidOrganism, invalidTarget, message) {
    super(message);
    this.invalidTarget = invalidTarget;
    this.invalidOrganism = invalidOrganism;
  }
}

const gConvertURL = 'https://biit.cs.ut.ee/gprofiler_archive3/r1741_e90_eg37/web/gconvert.cgi';

// convert offical synonyms to gConvert names
const convertGConvertNames = (gConvertName) => {
  if (gConvertName === 'HGNCSYMBOL') { return 'HGNC'; }
  if (gConvertName === 'HGNC') { return 'HGNC_ACC'; }
  if (gConvertName === 'UNIPROT') { return 'UNIPROTSWISSPROT'; }
  if (gConvertName === 'NCBIGENE') { return 'ENTREZGENE_ACC'; }
  return gConvertName;
};

const validatorGconvert = (query, userOptions) => {
  const promise = new Promise((resolve, reject) => {
    const formData = _.assign({}, defaultOptions, userOptions, { query: query });
    formData.organism =  formData.organism.toLowerCase();
    const initialTarget = formData.target.toUpperCase();
    formData.target = convertGConvertNames(initialTarget);
    const invalidInfo = {invalidTarget: '', invalidOrganism: ''};
    if (!validOrganism.includes(formData.organism)) {
      invalidInfo.invalidOrganism = formData.organism;
    }
    if (!validTarget.includes(formData.target)) {
      invalidInfo.invalidTarget = formData.target;
    }
    if (invalidInfo.invalidOrganism != '' || invalidInfo.invalidTarget != '') {
      reject(new InvalidInfoError(invalidInfo.invalidOrganism, invalidInfo.invalidTarget, ''));
    }

    request.post({ url: gConvertURL, formData: formData }, (err, httpResponse, body) => {
      if (err) {
        reject(err);
      }
      const geneInfoList = _.map(body.split('\n'), ele => { return ele.split('\t'); });
      geneInfoList.splice(-1, 1); // remove last element ''

      const unrecognized = [];
      const duplicate = [];
      const geneInfo = [];
      const initialAliasIndex = 1;
      const convertedAliasIndex = 3;
      _.forEach(geneInfoList, info => {
        if (info[convertedAliasIndex] === 'N/A') {
          if (_.filter(unrecognized, ele => ele === info[initialAliasIndex]).length === 0) {
            unrecognized.push(info[initialAliasIndex]);
          }
        } else {
          if (_.filter(geneInfoList, ele => ele[convertedAliasIndex] === info[convertedAliasIndex]).length > 1 && _.filter(duplicate, ele => ele === info[initialAliasIndex]).length === 0) {
            duplicate.push(info[initialAliasIndex]);
          }
          if (_.filter(geneInfo, ele => ele.initialAlias === info[initialAliasIndex]).length === 0) {
            geneInfo.push({ initialAlias: info[initialAliasIndex], convertedAlias: info[convertedAliasIndex] });
          }
        }
      });

      const ret = { options: {target: initialTarget, organism: formData.organism}, unrecognized: unrecognized, duplicate: duplicate, geneInfo: geneInfo };
      resolve(ret);
    });
  });
  return promise;
};

module.exports = { validatorGconvert };
<|endoftext|>


<commit_before>var batteryStatus = require('../');
var test = require('tape');
var isFunction = require('lodash.isfunction');

test('exports a function', function(t) {
  t.plan(1);
  t.ok(isFunction(batteryStatus));
});

test('returns status', function(t) {
  t.plan(4);
  batteryStatus('BAT0', function(error, status) {
    t.error(error);
    t.ok(status === 'Charging'
      || status === 'Discharging'
      || status === 'Full');
  });
  batteryStatus('BAT1', function(error, status) {
    t.error(error);
    t.ok(status === 'Charging'
      || status === 'Discharging'
      || status === 'Full');
  });
});

test('defaults to BAT0', function(t) {
  t.plan(2);
  batteryStatus(function(error, status) {
    t.error(error);
    t.ok(status === 'Charging'
      || status === 'Discharging'
      || status === 'Full');
  });
});<commit_msg>test: allow "Unknown" status<commit_after>var batteryStatus = require('../');
var test = require('tape');
var isFunction = require('lodash.isfunction');

test('exports a function', function(t) {
  t.plan(1);
  t.ok(isFunction(batteryStatus));
});

test('returns status', function(t) {
  t.plan(4);
  batteryStatus('BAT0', function(error, status) {
    t.error(error);
    t.ok(status === 'Charging'
      || status === 'Discharging'
      || status === 'Full'
      || status === 'Unknown');
  });
  batteryStatus('BAT1', function(error, status) {
    t.error(error);
    t.ok(status === 'Charging'
      || status === 'Discharging'
      || status === 'Full'
      || status === 'Unknown');
  });
});

test('defaults to BAT0', function(t) {
  t.plan(2);
  batteryStatus(function(error, status) {
    t.error(error);
    t.ok(status === 'Charging'
      || status === 'Discharging'
      || status === 'Full'
      || status === 'Unknown');
  });
});
<|endoftext|>


<commit_before>module.exports = {
  root: true,
  parser: "@typescript-eslint/parser",
  plugins: ["@typescript-eslint", "simple-import-sort"],
  extends: [
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  rules: {
    "@typescript-eslint/consistent-type-assertions": 'error',
    "@typescript-eslint/consistent-type-imports": 'error',
    'simple-import-sort/imports': 'error',
    'simple-import-sort/exports': 'error',
  }
};
<commit_msg>chore: add more eslint rules<commit_after>module.exports = {
  root: true,
  parser: "@typescript-eslint/parser",
  plugins: ["@typescript-eslint", "simple-import-sort"],
  extends: [
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  rules: {
    "no-use-before-define": "off",
    "@typescript-eslint/no-use-before-define": "off",
    "@typescript-eslint/consistent-type-assertions": "error",
    "@typescript-eslint/consistent-type-imports": "error",
    "simple-import-sort/imports": "error",
    "simple-import-sort/exports": "error"
  }
};
<|endoftext|>


<commit_before>var Twit = require('twit')

var fs = require('fs'),
    path = require('path'),
    Twit = require('twit'),

    config = require(path.join(__dirname, 'config.js'));

var T = new Twit(config);

var bot = ['2:00 AM'];

var bot = bot[Math.floor(Math.random() * bot.length)];
var post = function () {

T.post('statuses/update', { status: bot }, function(err, data, response) {

console.log('success');

});

}

//post();

var ontime = require('ontime')

ontime({
    cycle: '2:00:00'
}, function (ot) {
    // do your job here

post();
console.log('Hi');
ot.done()
    return
})

//setInterval(post, 10000);

/*setInterval(function() {
T.post('statuses/update', { status: bot }, function(err, data, response) {

console.log('success');

});

 }*/

/*setInterval(
T.post('statuses/update', { status: '....' }, function(err, data, response) {

	console.log(data);
});

}
  //post_tweet (),
  10000
);*/ <commit_msg>set time<commit_after>var Twit = require('twit')

var fs = require('fs'),
    path = require('path'),
    Twit = require('twit'),

    config = require(path.join(__dirname, 'config.js'));

var T = new Twit(config);

var bot = ['Its 2:15 AM'];

var bot = bot[Math.floor(Math.random() * bot.length)];
var post = function () {

T.post('statuses/update', { status: bot }, function(err, data, response) {

console.log('success');

});

}

//post();

var ontime = require('ontime')

ontime({
    cycle: '2:15:00'
}, function (ot) {
    // do your job here

post();
console.log('Hi');
ot.done()
    return
})

//setInterval(post, 10000);

/*setInterval(function() {
T.post('statuses/update', { status: bot }, function(err, data, response) {

console.log('success');

});

 }*/

/*setInterval(
T.post('statuses/update', { status: '....' }, function(err, data, response) {

	console.log(data);
});

}
  //post_tweet (),
  10000
);*/ <|endoftext|>


<commit_before>var express = require("express");
var socketio = require('socket.io');
var backlog = require("../");

createApp().listen(3000, function() {
	console.log("http://localhost:3000");
});

function createApp() {
	var app = express();
	var http = require("http").Server(app);
	app.use(express.static(__dirname));

	var io = socketio(http);
	io.adapter(backlog({
		length: 100,
		peremption: 86400
	}));
	io.on("connection", function(socket) {
		console.log('a user connected', socket.id);
		socket.on('join', function(data) {
			console.log('join', data);
			if (data.mtime) socket.joinArgs = data.mtime;
			socket.join(data.room);
			socket.on("message", function(message) {
				console.log(socket.id, 'message', message);
				var now = new Date();
				var completeMessage = {
					text: message,
					mtime: now.getTime()
				};
				io.to(data.room).emit('message', completeMessage);
			});
		});
		socket.on("disconnect", function() {
			console.log("disconnect", socket.id);
		});
	});
	return http;
}
<commit_msg>Add cache parameter.<commit_after>var express = require("express");
var socketio = require('socket.io');
var backlog = require("../");

createApp().listen(3000, function() {
	console.log("http://localhost:3000");
});

function createApp() {
	var app = express();
	var http = require("http").Server(app);
	app.use(express.static(__dirname));

	var io = socketio(http);
	io.adapter(backlog({
		length: 100,
		peremption: 86400,
		cacheSize: 2
	}));
	io.on("connection", function(socket) {
		console.log('a user connected', socket.id);
		socket.on('join', function(data) {
			console.log('join', data);
			if (data.mtime) socket.joinArgs = data.mtime;
			socket.join(data.room);
			socket.on("message", function(message) {
				console.log(socket.id, 'message', message);
				var now = new Date();
				var completeMessage = {
					text: message,
					mtime: now.getTime()
				};
				io.to(data.room).emit('message', completeMessage);
			});
		});
		socket.on("disconnect", function() {
			console.log("disconnect", socket.id);
		});
	});
	return http;
}
<|endoftext|>


<commit_before>/// <binding AfterBuild='webpack' Clean='clean-temporary' />
"use strict";
const gulp = require("gulp");
const clean = require("gulp-clean");
const webpack = require("webpack-stream");

//The webpack implementation here is sub-optimal: it's not leveraging gulp's streaming capability, instead basically just running webpack.

// Clears the /build folder which is used to stage TypeScript output for webpack bundling.
gulp.task("clean-temporary", () => gulp
	.src("./build/*", { read: false }) //Don't actually need to read these files sicne we're deleting them.
	.pipe(clean())
);

//
gulp.task("webpack", ["clean-temporary"], () => gulp
	.src("./App", { read: false }) //Read by webpack, only a placeholder here.
	.pipe(webpack(require("./webpack.config.js")))
	.pipe(gulp.dest("./wwwroot/build/"))
);<commit_msg>Modified the Gulp webpack-stream process to explicitly load the version of webpack received from npm, rather than the one included by webpack-stream.  This can be reversed when webpack-stream includes the current version.<commit_after>/// <binding AfterBuild='webpack' Clean='clean-temporary' />
"use strict";
const gulp = require("gulp");
const clean = require("gulp-clean");
const webpack = require("webpack-stream");

//The webpack implementation here is sub-optimal: it's not leveraging gulp's streaming capability, instead basically just running webpack.

// Clears the /build folder which is used to stage TypeScript output for webpack bundling.
gulp.task("clean-temporary", () => gulp
	.src("./build/*", { read: false }) //Don't actually need to read these files sicne we're deleting them.
	.pipe(clean())
);

//
gulp.task("webpack", ["clean-temporary"], () => gulp
	.src("./App", { read: false }) //Read by webpack, only a placeholder here.
	.pipe(webpack(require("./webpack.config.js"), require('webpack')))
	.pipe(gulp.dest("./wwwroot/build/"))
);<|endoftext|>


<commit_before>var React = require('react');
var Section = require('./Section');

var Selection = require('../modules/Selection');
var KeyIntent = require('../modules/KeyIntent');

var ContentState = require('../state/ContentState');
var SelectionState = require('../state/SelectionState');
var BaseKey = require('../actions/keys/BaseKey');

require('../stylesheets/Content.scss');

var Content = React.createClass({
  propTypes: {
    onChange: React.PropTypes.func
  },

  getDefaultProps() {
    return {
      onChange() {}
    }
  },
  getInitialState() {
    return {
      content: {sections: []},
      selection: new Selection(document.getSelection())
    }
  },

  // update when store changes
  componentDidMount() {
    ContentState.register(this.setState.bind(this));
    SelectionState.register(this.setState.bind(this));

    this.key = new BaseKey;
  },

  // if content changed, selection may have changed
  componentDidUpdate() {
    if (this.state.selection.reselect() || this.state.selection.rebound()) {
      this.checkSelection();
    }
  },

  checkSelection() {
    SelectionState.set({selection: new Selection(document.getSelection())});
  },

  // handle changes
  onChange(e) {
    this.props.onChange(this.state.content);
  },
  onMouseUp(e) {
    setTimeout(this.checkSelection, 1);
  },

  onBlur(e) {
    setTimeout(this.checkSelection, 1);
  },
  onKeyUp(e) {
    this.checkSelection();
    if (e.keyCode == 91) { this.metaKey = false; }

    this.key.press('Other');
  },
  onKeyDown(e) {
    if (e.keyCode == 91) { this.metaKey = true; }
    e.metaKey = this.metaKey;

    var keyIntent = new KeyIntent(e);
    this.intent = keyIntent.getIntent();
    if (this.intent) {
      if (this.key.press(this.intent)) {
        e.preventDefault();
      }
    }
  },

  render() {
    var sections = this.state.content.sections.map( (sect, i) => {
      sect.meta = sect.meta || {};
      if (i == 0) { sect.meta.first = true; }
      return

    });

    return (

        {sections}

    )
  }
});

module.exports = Content;
<commit_msg>clean up content proptypes<commit_after>var React = require('react');
var Section = require('./Section');

var Selection = require('../modules/Selection');
var KeyIntent = require('../modules/KeyIntent');

var ContentState = require('../state/ContentState');
var SelectionState = require('../state/SelectionState');
var BaseKey = require('../actions/keys/BaseKey');

require('../stylesheets/Content.scss');

var { func } = React.PropTypes;

var Content = React.createClass({
  propTypes: {
    onChange: func
  },

  getDefaultProps() {
    return {
      onChange() {}
    }
  },

  getInitialState() {
    return {
      content: {sections: []},
      selection: new Selection(document.getSelection())
    }
  },

  // update when store changes
  componentDidMount() {
    ContentState.register(this.setState.bind(this));
    SelectionState.register(this.setState.bind(this));

    this.key = new BaseKey;
  },

  // if content changed, selection may have changed
  componentDidUpdate() {
    if (this.state.selection.reselect() || this.state.selection.rebound()) {
      this.checkSelection();
    }
  },

  checkSelection() {
    SelectionState.set({selection: new Selection(document.getSelection())});
  },

  // handle changes
  onChange(e) {
    this.props.onChange(this.state.content);
  },
  onMouseUp(e) {
    setTimeout(this.checkSelection, 1);
  },

  onBlur(e) {
    setTimeout(this.checkSelection, 1);
  },
  onKeyUp(e) {
    this.checkSelection();
    if (e.keyCode == 91) { this.metaKey = false; }

    this.key.press('Other');
  },
  onKeyDown(e) {
    if (e.keyCode == 91) { this.metaKey = true; }
    e.metaKey = this.metaKey;

    var keyIntent = new KeyIntent(e);
    this.intent = keyIntent.getIntent();
    if (this.intent) {
      if (this.key.press(this.intent)) {
        e.preventDefault();
      }
    }
  },

  render() {
    var sections = this.state.content.sections.map( (sect, i) => {
      sect.meta = sect.meta || {};
      if (i == 0) { sect.meta.first = true; }
      return

    });

    return (

        {sections}

    )
  }
});

module.exports = Content;
<|endoftext|>


<commit_before>var XLSX = require('xlsx');
var Workbook = require('./workbook');

///credit http://daveaddey.com/?p=40
function JSDateToExcelDate(inDate) {
  return 25569.0 + ((inDate.getTime() - (inDate.getTimezoneOffset() * 60 * 1000)) / (1000 * 60 * 60 * 24));
}

var workbook = new Workbook(XLSX)
    .addRowsToSheet("Main", [
      ["This is a submerged cell"],
      [
        {"v": "Blank"},
        {"v": "Red", "s": {fill: { fgColor: { rgb: "FFFF0000"}}}},
        {"v": "Green", "s": {fill: { fgColor: { rgb: "FF00FF00"}}}},
        {"v": "Blue", "s": {fill: { fgColor: { rgb: "FF0000FF"}}}}
      ],
      [
        {"v": "Default"},
        {"v": "Arial", "s": {font: {name: "Arial", sz: 24}}},
        {"v": "Times New Roman", "s": {font: {name: "Times New Roman", sz: 16}}},
        {"v": "Courier New", "s": {font: {name: "Courier New", sz: 14}}}
      ],
      [
        {"v": "Normal"},
        {"v": "Bold", "s": {font: {bold: true}, fill: { fgColor: { rgb: "FFFF0000"}}}},
        {"v": "Italic", "s": {font: {italic: true}, fill: { fgColor: { rgb: "FF00FF00"}}}},
        {"v": "Underline", "s": {underline: {bold: true}}},
        {"v": "All", "s": {font: {bold: true ,italic: true, underline: true}}}
      ],
      [
        0.618033989,
        {"v": 0.618033989},
        {"v": 0.618033989, "t": "n"},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.00%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.00%"}, fill: { fgColor: { rgb: "FFFFCC00"}}}
      ],
      [
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.0%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.00%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.000%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.0000%"}},
        {"v": 0, "t": "n", "s": { numFmt: "0.00%;\\(0.00%\\);\\-;@"}, fill: { fgColor: { rgb: "FFFFCC00"}}}
      ],
      [
        {v: (new Date()).toLocaleString()},
        {v: (new Date()), t: 'd'},
        {v: (new Date()),  s: {numFmt: 'd-mmm-yy'}}
      ]
      ,
      [
        {v: "left", "s": { alignment: {horizontal: "left"}}},
        {v: "left", "s": { alignment: {horizontal: "center"}}},
        {v: "left", "s": { alignment: {horizontal: "right"}}}
      ],[
        {v: "vertical", "s": { alignment: {vertical: "top"}}},
        {v: "vertical", "s": { alignment: {vertical: "center"}}},
        {v: "vertical", "s": { alignment: {vertical: "bottom"}}}
      ],[
        {v: "indent", "s": { alignment: {indent: "1"}}},
        {v: "indent", "s": { alignment: {indent: "2"}}},
        {v: "indent", "s": { alignment: {indent: "3"}}}
      ],
      [{
        v: "In publishing and graphic design, lorem ipsum is a filler text commonly used to demonstrate the graphic elements of a document or visual presentation. ",
        s: { alignment: { wrapText: 1, alignment: 'right', vertical: 'center', indent: 1}}
      }
      ],
      [
        {v: 41684.35264774306, s: {numFmt: 'm/d/yy'}},
        {v: 41684.35264774306, s: {numFmt: 'd-mmm-yy'}},
        {v: 41684.35264774306, s: {numFmt: 'h:mm:ss AM/PM'}},
        {v: new Date(),  s: {numFmt: 'm/d/yy'}},
        {v: 42065.02247239584,  s: {numFmt: 'm/d/yy'}},
        {v: new Date(),  s: {numFmt: 'm/d/yy h:mm:ss AM/PM'}}
      ]
    ]).mergeCells("Main", {
      "s": {"c": 0, "r": 0 },
      "e": {"c": 2, "r": 0 }
    }).finalize();

var OUTFILE = '/tmp/wb.xlsx';
XLSX.writeFile(workbook, OUTFILE);
console.log("Results written to " + OUTFILE)
<commit_msg>Added border to merged cell<commit_after>var XLSX = require('xlsx');
var Workbook = require('./workbook');

///credit http://daveaddey.com/?p=40
function JSDateToExcelDate(inDate) {
  return 25569.0 + ((inDate.getTime() - (inDate.getTimezoneOffset() * 60 * 1000)) / (1000 * 60 * 60 * 24));
}

var workbook = new Workbook(XLSX)
    .addRowsToSheet("Main", [
      [ {
        v: "This is a submerged cell",
        s:{
          border: {
            left: {style: 'thick', color: {auto: 1}},
            top: {style: 'thick', color: {auto: 1}},
            bottom: {style: 'thick', color: {auto: 1}}
          }
        }
      },
        {
          v: "Pirate ship",
          s:{
            border: {
              top: {style: 'thick', color: {auto: 1}},
              bottom: {style: 'thick', color: {auto: 1}}
            }
          }
        },
        {
          v: "Sunken treasure",
          s:{
            border: {
              right: {style: 'thick', color: {auto: 1}},
              top: {style: 'thick', color: {auto: 1}},
              bottom: {style: 'thick', color: {auto: 1}}
            }
          }
        }
      ],
      [
        {"v": "Blank"},
        {"v": "Red", "s": {fill: { fgColor: { rgb: "FFFF0000"}}}},
        {"v": "Green", "s": {fill: { fgColor: { rgb: "FF00FF00"}}}},
        {"v": "Blue", "s": {fill: { fgColor: { rgb: "FF0000FF"}}}}
      ],
      [
        {"v": "Default"},
        {"v": "Arial", "s": {font: {name: "Arial", sz: 24}}},
        {"v": "Times New Roman", "s": {font: {name: "Times New Roman", sz: 16}}},
        {"v": "Courier New", "s": {font: {name: "Courier New", sz: 14}}}
      ],
      [
        {"v": "Normal"},
        {"v": "Bold", "s": {font: {bold: true}, fill: { fgColor: { rgb: "FFFF0000"}}}},
        {"v": "Italic", "s": {font: {italic: true}, fill: { fgColor: { rgb: "FF00FF00"}}}},
        {"v": "Underline", "s": {underline: {bold: true}}},
        {"v": "All", "s": {font: {bold: true ,italic: true, underline: true}}}
      ],
      [
        0.618033989,
        {"v": 0.618033989},
        {"v": 0.618033989, "t": "n"},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.00%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.00%"}, fill: { fgColor: { rgb: "FFFFCC00"}}}
      ],
      [
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.0%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.00%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.000%"}},
        {"v": 0.618033989, "t": "n", "s": { "numFmt": "0.0000%"}},
        {"v": 0, "t": "n", "s": { numFmt: "0.00%;\\(0.00%\\);\\-;@"}, fill: { fgColor: { rgb: "FFFFCC00"}}}
      ],
      [
        {v: (new Date()).toLocaleString()},
        {v: (new Date()), t: 'd'},
        {v: (new Date()),  s: {numFmt: 'd-mmm-yy'}}
      ]
      ,
      [
        {v: "left", "s": { alignment: {horizontal: "left"}}},
        {v: "left", "s": { alignment: {horizontal: "center"}}},
        {v: "left", "s": { alignment: {horizontal: "right"}}}
      ],[
        {v: "vertical", "s": { alignment: {vertical: "top"}}},
        {v: "vertical", "s": { alignment: {vertical: "center"}}},
        {v: "vertical", "s": { alignment: {vertical: "bottom"}}}
      ],[
        {v: "indent", "s": { alignment: {indent: "1"}}},
        {v: "indent", "s": { alignment: {indent: "2"}}},
        {v: "indent", "s": { alignment: {indent: "3"}}}
      ],
      [{
        v: "In publishing and graphic design, lorem ipsum is a filler text commonly used to demonstrate the graphic elements of a document or visual presentation. ",
        s: { alignment: { wrapText: 1, alignment: 'right', vertical: 'center', indent: 1}}
      }
      ],
      [
        {v: 41684.35264774306, s: {numFmt: 'm/d/yy'}},
        {v: 41684.35264774306, s: {numFmt: 'd-mmm-yy'}},
        {v: 41684.35264774306, s: {numFmt: 'h:mm:ss AM/PM'}},
        {v: new Date(),  s: {numFmt: 'm/d/yy'}},
        {v: 42065.02247239584,  s: {numFmt: 'm/d/yy'}},
        {v: new Date(),  s: {numFmt: 'm/d/yy h:mm:ss AM/PM'}}
      ],
      [
//          {v: "Apple", s: {border: {top: { style: "thin"}}, left: { style: "thin"}, right: { style: "thin"}, bottom: { style: "thin"}}}
        {
          v: "Border test",
          s: {
            border: {
              diagonalUp: false,
              diagonalDown: true,
              top: { style: "thick", color: {auto: 1}},
              right: { style: "thick", color: {theme: "5"}},
              bottom: { style: "thick", color: {theme: 5, tint: "-0.3"}},
              left: { style: "thick", color: {rgb: "FFFFAA00"}},
              diagonal: {style: "thick", color: {theme: 6}}
            }
          }
        }
      ]
    ]).mergeCells("Main", {
      "s": {"c": 0, "r": 0 },
      "e": {"c": 2, "r": 0 }
    }).finalize();

var OUTFILE = '/tmp/wb.xlsx';
XLSX.writeFile(workbook, OUTFILE);
console.log("Results written to " + OUTFILE)
<|endoftext|>