Пример #1
0
  }))).forEach(function (line, row) {
    var column = scroll.column;
    row += scroll.row;

    var renderableLineEnding = self._renderableLineEnding((line.match(textUtil._lineRegExp) || [''])[0]);
    line = line
      .replace(/\t+/g, self._renderableTabString.bind(self))
      .replace(/ +/g, self._renderableSpace.bind(self))
      .replace(textUtil._lineRegExp, renderableLineEnding)
      .replace(Editor._nonprintableRegExp, '\ufffd');

    line = markup.parse(line)
      .slice(column, column + size.column)
      .push(_.repeat(' ', size.column).join(''))
      .tag(defaultStyle);

    self.textBuf.findMarkers({intersectsRow: row}).sort(Editor.markerCmp).forEach(function (marker) {
      var range = self.visiblePos(marker.getRange());
      if (range.intersectsRow(row)) {
        var markerStyle;
        switch (marker.properties.type) {
          case 'selection': markerStyle = selectionStyle; break;
          case 'match': case 'findMatch': markerStyle = matchStyle; break;
          case 'syntax': markerStyle = marker.properties.syntax
            .map(function (syntax) {
              if (!(syntax in style)) logger.debug("unstyled syntax:", syntax);
              return style[syntax] || '';
            })
            .join(''); break;
          default: throw new Error("unknown marker: " + marker.properties.type);
        }
        line = markup(line, markerStyle,
          row === range.start.row ? range.start.column - column : 0,
          row === range.end.row   ? range.end.column   - column : Infinity);
      }
    });

    if (cursorOnBracket && row === visibleCursor.row) {
      line = markup(line, bracketStyle,
        visibleCursor.column - column,
        visibleCursor.column - column + 1);
    }
    if (visibleMatchingBracket && row === visibleMatchingBracket.row) {
      line = markup(line, bracketStyle,
        visibleMatchingBracket.column - column,
        visibleMatchingBracket.column - column + 1);
    }

    bufferContent.push(line + '{/}');

    var gutterLine = (_.repeat(' ', lineNumberWidth).join('') + (row + 1)).slice(-lineNumberWidth);
    gutterLine += _.repeat(' ', gutterWidth).join('');

    if (currentLineStyle && row === visibleCursor.row) {
      gutterLine = markup(gutterLine, currentLineStyle);
    }

    gutterContent.push(gutterLine + '{/}');
  });
Пример #2
0
Editor.prototype._renderableTabString = function (match) {
  return !this.buffer.options.visibleWhiteSpace
    ? _.repeat(' ', this.buffer.options.tabSize * match.length).join('')
    : markup(_.repeat(
        _.repeat('\u2500', this.buffer.options.tabSize - 1).join('') +
        (this.buffer.options.tabSize ? '\u2574' : '')
      , match.length).join(''), this.options.style.whiteSpace)
};
Пример #3
0
    .forEach(function (line, y) {
      var x = scroll.x;
      y += scroll.y;

      var renderableLineEnding = self._renderableLineEnding((line.match(textUtil._lineRegExp) || [''])[0]);
      line = line
        .replace(/\t+/g, self._renderableTabString.bind(self))
        .replace(/ +/g, self._renderableSpace.bind(self))
        .replace(textUtil._lineRegExp, renderableLineEnding)
        .replace(Editor._nonprintableRegExp, '\ufffd');

      var markupScrollX = markup.index(line, x);
      line = markup.getOpenTags(line.slice(0, markupScrollX)).join('') +
        line.slice(markupScrollX, markup.index(line, x + size.x)) +
        _.repeat(' ', size.x).join('');

      if (!self.data.hideSelection && selectionStyle && visibleSelection.start.y <= y && y <= visibleSelection.end.y) {
        line = markup(line, selectionStyle,
          y === visibleSelection.start.y ? visibleSelection.start.x - x : 0,
          y === visibleSelection.end.y ? visibleSelection.end.x - x : Infinity);
      }

      if (cursorOnBracket && y === visibleCursor.y) {
        line = markup(line, bracketStyle,
          visibleCursor.x - x,
          visibleCursor.x - x + 1);
      }
      if (visibleMatchingBracket && y === visibleMatchingBracket.y) {
        line = markup(line, bracketStyle,
          visibleMatchingBracket.x - x,
          visibleMatchingBracket.x - x + 1);
      }

      visibleMatches.forEach(function (match) {
        if (match.start.y <= y && y <= match.end.y) {
          line = markup(line, matchStyle,
            y === match.start.y ? match.start.x - x : 0,
            y === match.end.y ? match.end.x - x : Infinity);
        }
      });

      bufferContent.push(line + '{/}');

      var gutterLine = (_.repeat(' ', lineNumberWidth).join('') + (y + 1)).slice(-lineNumberWidth);
      gutterLine += _.repeat(' ', gutterWidth).join('');

      if (currentLineStyle && y === visibleCursor.y) {
        gutterLine = markup(gutterLine, currentLineStyle);
      }

      gutterContent.push(gutterLine + '{/}');
    });
Пример #4
0
Header.prototype.render = function () {
  var self = this;

  var style = self.options.style;
  var editor = self.parent.editor;
  var cursor = editor.cursor();

  var left = ' \u270b ';
  var originalPath = self.parent.path();
  var markupPath = originalPath ? blessed.escape(originalPath) : 'new file';
  if (editor.changeStack.dirty() || !originalPath) {
    markupPath = markup(markupPath+'*', style.changed);
  }
  left += markupPath;

  var right = [(cursor.y+1)+','+(cursor.x+1) + ' ('+editor.lines().length+')'];
  if (!self.parent.insertMode()) right.unshift(markup('OVR', style.overwrite));
  var message = self.message();
  if (message) {
    if (self._blink()) message = markup(message, style.blink);
    right.unshift(message);
  }
  right = right.join('  ') + ' ';

  var remainingWidth = self.width - self.iwidth - markup.strip(left + right).length;
  self.setContent(markup(
    left + _.repeat(' ', remainingWidth).join('') + right
  , style.main));

  return blessed.Box.prototype.render.apply(self, arguments);
};
Пример #5
0
 _parseGeoNamesCitiesCsv: function(pathToCsv, callback) {
   DEBUG && console.log('Started parsing cities .csv (this  may take a ' +
       'while)');
   var data = [];
   var lenI = GEONAMES_COLUMNS.length;
   var that = this;
   lazy.readFile(pathToCsv).lines().each(function(line) {
     var lineObj = {};
     line = line.split('\t');
     for (var i = 0; i < lenI; i++) {
       var column = line[i] || null;
       lineObj[GEONAMES_COLUMNS[i]] = column;
     }
     data.push(lineObj);
   }).onComplete(function() {
     DEBUG && console.log('Finished parsing cities .csv');
     DEBUG && console.log('Started building cities k-d tree (this may take ' +
         'a while)');
     var dimensions = [
       'latitude',
       'longitude'
     ];
     that._kdTree = kdTree.createKdTree(data, that._distanceFunc, dimensions);
     DEBUG && console.log('Finished building cities k-d tree');
     return callback();
   });
 },
Пример #6
0
Path.prototype.stream = function() {
  var labels = this.getLabels();
  var objects = this.getObjects();

  return lazy.range(0, this.size()).map(function(i) {
    // todo: verify
    return [labels[i], objects[i]];
  });
};
Пример #7
0
Editor.prototype.realPos = function (pos) {
  return {
    x: this.line(pos.y)
      .replace(Editor._tabRegExp, _.repeat('\t', this.options.tabSize).join(''))
      .slice(0, Math.max(pos.x, 0))
      .replace(new RegExp('\\t{1,'+this.options.tabSize+'}', 'g'), '\t')
      .length,
    y: pos.y
  };
};
Пример #8
0
Editor.prototype.visiblePos = function (pos) {
  var self = this;
  if (pos instanceof Range) return new Range(self.visiblePos(pos.start), self.visiblePos(pos.end));
  pos = Point.fromObject(pos, true);
  pos.column = self.lineWithEndingForRow(pos.row)
    .slice(0, Math.max(pos.column, 0))
    .replace(Editor._tabRegExp, _.repeat('\t', self.buffer.options.tabSize).join(''))
    .length;
  return pos;
};
Пример #9
0
Editor.prototype.realPos = function (pos) {
  var self = this;
  if (pos instanceof Range) return new Range(self.realPos(pos.start), self.realPos(pos.end));
  pos = self.textBuf.clipPosition(Point.fromObject(pos, true));
  pos.column = this.lineWithEndingForRow(pos.row)
    .replace(Editor._tabRegExp, _.repeat('\t', this.buffer.options.tabSize).join(''))
    .slice(0, Math.max(pos.column, 0))
    .replace(new RegExp('\\t{1,'+this.buffer.options.tabSize+'}', 'g'), '\t')
    .length;
  return pos;
};
Пример #10
0
function iterate(stepper, start) {
  var current;

  return Lazy.generate(function () {
    if (current === undefined) {
      current = start;
    } else {
      current = stepper(current);
    }
    return current;
  });
}
Пример #11
0
Editor.prototype.findAll = function (pattern, start, end) {
  var self = this;
  var start = start || Coordinate.origin();
  return _
    .generate(function () {
      var match = self.find(pattern, start, end);
      if (!match) return;
      start = _(match.start).toObject(); start.x++;
      return match;
    })
    .takeWhile(Boolean)
    .toArray();
};
Пример #12
0
Editor.prototype.visiblePos = function (pos) {
  var self = this;
  if ('start' in pos && 'end' in pos) {
    return {start: self.visiblePos(pos.start), end: self.visiblePos(pos.end)};
  }
  return {
    x: self.line(pos.y)
      .slice(0, Math.max(pos.x, 0))
      .replace(Editor._tabRegExp, _.repeat('\t', self.options.tabSize).join(''))
      .length,
    y: pos.y
  };
};
Пример #13
0
function writeFile(fileName, json, lineSep, fieldSep, skipEmpty) {
  if (!json.header) {
    var header = {};
    _(json.items || []).each(function (obj) { _(obj).each(function (value, key) { header[key] = 1; }); });
    json.header = _(obj).keys(header);
  }
  var defaults = _(json.header).zip(_.generate(function () { return ''; }, json.header.length).value()).toObject();
  fs.writeFileSync(fileName, json.header.join(fieldSep));
  _(json.items || []).each(function (item) {
    var picked = _(item).pick(json.header).defaults(defaults).values();
    if (skipEmpty && picked.compact().isEmpty()) return;
    fs.appendFileSync(fileName, lineSep + picked.join(fieldSep));
  });
}
Пример #14
0
 _parseGeoNamesAlternateNamesCsv: function(pathToCsv, callback) {
   var that = this;
   that._alternateNames = {};
   lazy.readFile(pathToCsv).split('\n').each(function(line) {
     line = line.split('\t');
     // Load postal codes
     if (line[2] === 'post') {
       if (!that._alternateNames[line[1]]) {
         that._alternateNames[line[1]] = {};
       }
       // Key on second column which is the geoNameId
       that._alternateNames[line[1]][line[2]] = line[3];
     }
   }).onComplete(function() {
     return callback();
   });
 },
Пример #15
0
 _parseGeoNamesAdmin2CodesCsv: function(pathToCsv, callback) {
   var that = this;
   var lenI = GEONAMES_ADMIN_CODES_COLUMNS.length;
   lazy.readFile(pathToCsv).lines().each(function(line) {
     line = line.split('\t');
     for (var i = 0; i < lenI; i++) {
       var value = line[i] || null;
       if (i === 0) {
         that._admin2Codes[value] = {};
       } else {
         that._admin2Codes[line[0]][GEONAMES_ADMIN_CODES_COLUMNS[i]] = value;
       }
     }
   }).onComplete(function() {
     return callback();
   });
 },
Пример #16
0
  _parseGeoNamesAllCountriesCsv: function(pathToCsv, callback) {
    DEBUG && console.log('Started parsing all countries.txt (this  may take ' +
        'a while)');
    var lenI = GEONAMES_COLUMNS.length;
    var that = this;
    // Indexes
    var featureCodeIndex = GEONAMES_COLUMNS.indexOf('featureCode');
    var countryCodeIndex = GEONAMES_COLUMNS.indexOf('countryCode');
    var admin1CodeIndex = GEONAMES_COLUMNS.indexOf('admin1Code');
    var admin2CodeIndex = GEONAMES_COLUMNS.indexOf('admin2Code');
    var admin3CodeIndex = GEONAMES_COLUMNS.indexOf('admin3Code');
    var admin4CodeIndex = GEONAMES_COLUMNS.indexOf('admin4Code');
    var nameIndex = GEONAMES_COLUMNS.indexOf('name');
    var asciiNameIndex = GEONAMES_COLUMNS.indexOf('asciiName');
    var geoNameIdIndex = GEONAMES_COLUMNS.indexOf('geoNameId');

    var counter = 0;
    that._admin3Codes = {};
    that._admin4Codes = {};
    lazy.readFile(pathToCsv).split('\n').each(function(line) {
      line = line.split('\t');
      var featureCode = line[featureCodeIndex];
      if ((featureCode === 'ADM3') || (featureCode === 'ADM4')) {
        var lineObj = {
          name: line[nameIndex],
          asciiName: line[asciiNameIndex],
          geoNameId: line[geoNameIdIndex]
        };
        var key = line[countryCodeIndex] + '.' + line[admin1CodeIndex] + '.' +
            line[admin2CodeIndex] + '.' + line[admin3CodeIndex];
        if (featureCode === 'ADM3') {
          that._admin3Codes[key] = lineObj;
        } else if (featureCode === 'ADM4') {
          that._admin4Codes[key + '.' + line[admin4CodeIndex]] = lineObj;
        }
      }
      if (counter % 100000 === 0) {
        DEBUG && console.log('Parsing progress all countries ' + counter);
      }
      counter++;
    }).onComplete(function() {
      DEBUG && console.log('Finished parsing all countries.txt');
      return callback();
    });
  },
Пример #17
0
 render: function() {
   var style = Lazy(this.props.style).defaults(this.props.defaultStyle).toObject();
   var stepWidth = this.props.width / this.props.nbSteps;
   var steps = Lazy.range(this.props.startStep, this.props.nbSteps + this.props.startStep).toArray();
   return (
     <g className="grid v-grid">
       {
         steps.map((stepNum, idx) => {
           var translateX = stepNum * stepWidth;
           return (
             <g key={idx} transform={'translate(' + translateX + ', 0)'}>
               <line style={style} y2={this.props.height} />
             </g>
           );
         })
       }
     </g>
   );
 },
Пример #18
0
  _parseGeoNamesCitiesCsv: function(pathToCsv, callback) {
    DEBUG && console.log('Started parsing cities.txt (this  may take a ' +
        'while)');
    var data = [];
    var lenI = GEONAMES_COLUMNS.length;
    var that = this;
    var latitudeIndex = GEONAMES_COLUMNS.indexOf('latitude');
    var longitudeIndex = GEONAMES_COLUMNS.indexOf('longitude');

    lazy.readFile(pathToCsv).split('\n').each(function(line) {
      var lineObj = {};
      line = line.split('\t');
      for (var i = 0; i < lenI; i++) {
        var column = line[i] || null;
        lineObj[GEONAMES_COLUMNS[i]] = column;
      }

      var lng = lineObj[GEONAMES_COLUMNS[latitudeIndex]];
      var lat = lineObj[GEONAMES_COLUMNS[longitudeIndex]];
      //dont add lineObj without lat/lng pair
      if (lng !== null && lng !== undefined && !isNaN(lng) &&
          lat !== null && lat !== undefined && !isNaN(lat)) {
        data.push(lineObj);
      } else {
        DEBUG && console.log('found null or undefined geo coords:', lineObj);
      }
    }).onComplete(function() {
      DEBUG && console.log('Finished parsing cities.txt');
      DEBUG && console.log('Started building cities k-d tree (this may take ' +
          'a while)');
      var dimensions = [
        'latitude',
        'longitude'
      ];
      that._kdTree = kdTree.createKdTree(data, that._distanceFunc, dimensions);
      DEBUG && console.log('Finished building cities k-d tree');
      return callback();
    });
  },
Пример #19
0
   style: React.PropTypes.object,
   width: React.PropTypes.number.isRequired,
 },
 getDefaultProps() {
   return {
     defaultStyle: {
       shapeRendering: 'crispedges',
       stroke: '#e5e5e5',
     },
     startStep: 0,
   };
 },
 render() {
   var style = Lazy(this.props.style).defaults(this.props.defaultStyle).toObject();
   var stepHeight = this.props.height / this.props.nbSteps;
   var steps = Lazy.range(this.props.startStep, this.props.nbSteps + this.props.startStep).toArray();
   return (
     <g className="grid h-grid">
       {
         steps.map((stepNum, idx) => {
           var translateY = - stepNum * stepHeight;
           return (
             <g key={idx} transform={'translate(0, ' + translateY + ')'}>
               <line style={style} x2={this.props.width} />
             </g>
           );
         })
       }
     </g>
   );
 },
 renderSvg: function() {
   var width = this.state.chartContainerWidth - 15 * 2; // Substract Bootstrap panel left and right paddings.
   var height = this.props.height || width / this.props.aspectRatio;
   this.gridHeight = height - this.props.xAxisHeight - this.props.legendHeight;
   var yAxisWidth = this.state.yAxisWidth === null ? this.props.defaultYAxisWidth : this.state.yAxisWidth;
   this.gridWidth = width - yAxisWidth - this.props.marginRight;
   var xValue = this.findXFromY(this.props.value);
   var xSnapValues = Lazy.range(0, 105, this.props.xSnapIntervalValue).concat(xValue).sort().toArray();
   return (
     <svg height={height} width={width}>
       <g transform={`translate(${yAxisWidth}, ${height - this.props.xAxisHeight})`}>
         <HGrid
           height={this.gridHeight}
           nbSteps={this.props.yNbSteps}
           startStep={1}
           width={this.gridWidth}
         />
         <XAxis
           formatNumber={this.props.xFormatNumber}
           height={this.props.xAxisHeight}
           label='% de la population'
           labelFontSize={this.props.labelsFontSize}
           maxValue={this.props.xMaxValue}
           unit='%'
           width={this.gridWidth}
         />
       </g>
       <g transform={`translate(${yAxisWidth}, ${this.props.legendHeight})`}>
         <VGrid
           height={this.gridHeight}
           nbSteps={this.props.xSteps}
           startStep={1}
           width={this.gridWidth}
         />
         <YAxis
           formatNumber={this.props.yFormatNumber}
           height={this.gridHeight}
           maxValue={this.props.yMaxValue}
           nbSteps={this.props.yNbSteps}
           ref='yAxis'
           unit='€'
         />
         <Curve
           points={this.props.points}
           pointToPixel={this.gridPointToPixel}
           style={{stroke: 'rgb(31, 119, 180)'}}
         />
         <Curve
           points={[this.props.points.last(), this.lastPoint]}
           pointToPixel={this.gridPointToPixel}
           style={{
             stroke: 'rgb(31, 119, 180)',
             strokeDasharray: '5 5',
           }}
         />
         <Point
           pointToPixel={this.gridPointToPixel}
           style={{
             fill: xValue > this.pointsXMaxValue ? 'none' : this.props.pointColor,
             stroke: this.props.pointColor,
           }}
           x={xValue}
           y={this.props.value}
         />
         <HoverLegend
           height={this.gridHeight}
           onHover={this.handleHoverLegendHover}
           pixelToPoint={this.gridPixelToPoint}
           pointToPixel={this.gridPointToPixel}
           pointsXMaxValue={this.pointsXMaxValue}
           snapPoint={this.state.snapPoint}
           width={this.gridWidth}
           xFormatNumber={this.props.xFormatNumber}
           xMaxValue={this.props.xMaxValue}
           xSnapValues={xSnapValues}
           yFormatNumber={this.props.yFormatNumber}
         />
       </g>
       <g transform={`translate(${yAxisWidth}, 0)`}>
         <Legend color='rgb(31, 119, 180)'>{this.props.curveLabel}</Legend>
         <g transform={`translate(${12 * 0.7 * this.props.curveLabel.length}, 0)`}>
           <Legend color={this.props.pointColor}>{this.props.pointLabel}</Legend>
         </g>
       </g>
     </svg>
   );
 },
Пример #21
0
const lazyEvery = () => lazy.every(predicate);
var Lazy = require('lazy.js')

// 生成无穷队列
var fibonacci = Lazy.generate(function() {
  var x = 1,
      y = 1;
  return function() {
    var prev = x;
    x = y;
    y += prev;
    return prev;
  };
}());

// Output: undefined
var length = fibonacci.length();

// Output: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
fibonacci.take(10).toArray();

/*--------------------------*/

var uniqueRandsFrom1To1000 = Lazy.generate(Math.random)
  .map(function(e) { return Math.floor(e * 1000) + 1; })
  .uniq()
  .take(300);

// Output: see for yourself!
uniqueRandsFrom1To1000.each(function(e) { console.log(e); }); 
Пример #23
0
const lazyLast = () => lazy.last();
Пример #24
0
var _ = require('lazy.js');

var square = function square (n) {
  return Math.pow(n, 2);
};

var sum = function sum (n, m) {
  return n + m;
};

var sumOfSquares = function sumOfSquares (range) {
  return range.map(square).reduce(sum);
};

var squareOfSum = function squareOfSum (range) {
  return square(range.reduce(sum), 2);
};

var difference = function difference (range) {
  return squareOfSum(range) - sumOfSquares(range);
};

console.log(difference(_.range(1,11)));
console.log(difference(_.range(1,101)));
Пример #25
0
/**
 * Performs a lazy, time-space animation given its arguments.
 * @param  {function} animator animates a particular state of the generated sequence
 * @param  {function} stepper  takes a state and returns the next state 
 * @param  {function} stopper  takes a state and returns a boolean that instructs the loop whether to continue animating. 
 * @param  {state} start       an object representing the initial state of your animated object 
 * @param  {number} wait       optional - the interval time between animations. animate will use requestAnimationFrame if this is not passed in
 */
function animate(animator, stepper, stopper, start, wait) {
  _animate(animator, Lazy.takeWhile(not(stopper), iterate(stepper, start))); 
}
Пример #26
0
var Lazy = require('lazy.js')

Lazy.range(3)         // sequence: [0, 1, 2]
Lazy.range(1, 4)      // sequence: [1, 2, 3]
Lazy.range(2, 10, 2)  // sequence: [2, 4, 6, 8]
Lazy.range(5, 1, 2)   // sequence: []
Lazy.range(5, 15, -2) // sequence: []
Lazy.range(3, 10, 3)  // sequence: [3, 6, 9]
Lazy.range(5, 2)      // sequence: [5, 4, 3]
Lazy.range(7, 2, -2)  // sequence: [7, 5, 3]
Lazy.range(3, 5, 0)   // sequence: []
Пример #27
0
Editor.prototype._renderableSpace = function (match) {
  return !this.buffer.options.visibleWhiteSpace
    ? match
    : markup(_.repeat('\u00b7', match.length).join(''), this.options.style.whiteSpace);
};
Пример #28
0
Editor.prototype._getTabString = function () {
  return this.options.useSpaces
    ? _.repeat(' ', this.options.tabSize).join('')
    : '\t';
};
     if (! hidden && hasValue) {
       var newVariableSequence = Lazy(variable).omit(['children']);
       newVariableSequence = newVariableSequence.assign({
         baseValues: baseValues,
         depth: depth,
         hasChildren: hasChildren,
         isCollapsed: isCollapsed,
         isSubtotal: hasChildren && depth > 0,
         values: variable.values,
       });
       var newVariable = newVariableSequence.toObject();
       newVariables.push(newVariable);
     }
     return newVariables;
   };
   var initBaseValues = Lazy.repeat(0, rootVariable.values.length).toArray();
   var variables = walk(rootVariable, initBaseValues, 0, false);
   return variables;
 },
 handleChartDownload() {
   var newProps = Lazy(this.refs.chart.props).omit(['ref']).assign({
     attribution: this.props.downloadAttribution,
     height: null,
     width: 800,
   }).toObject();
   var svgString = React.renderComponentToStaticMarkup(BaremeChart(newProps));
   saveAs(
     new Blob([svgString], {type: "image/svg+xml"}),
     this.formatMessage(this.getIntlMessage('baremeFilename'), {extension: 'svg'})
   );
 },
Пример #30
0
Editor.prototype._getTabString = function () {
  var self = this;
  return self.buffer.options.useSpaces
    ? _.repeat(' ', self.buffer.options.tabSize).join('')
    : '\t';
};