Esempio n. 1
0
  mockagent.get(pixabayUrl, function(res) {
    const query = url.parse(this.url, true).query;

    let hits = [];

    if (query.page === '1') {
      hits = range(0, 20);
    } else if (query.page === '2') {
      hits = range(20, 25);
    }

    const noError = !!hits.length;

    const error =  'ERROR: "page"/"per_page" is out of valid range.';

    const response = {
      totalHits: noError ? 25 : undefined,
      hits: noError ? hits : undefined,
      error: noError ? null : error
    };

    res.xhr = {
      status: noError ? 200 : 400,
      responseText: noError ? JSON.stringify(response) : error
    };

    return res;
  });
Esempio n. 2
0
function barify(cur, tot) {
	return (
		'[' +
    range(0, cur).map(() => '=').join('') +
    range(cur, tot).map(() => '-').join('') +
    ']'
	)
}
Esempio n. 3
0
  return steps.reduce((prev, next, stepIndex) => {
    const stack = getStack(steps, stepIndex);
    const transFrameNum = round(FPS * TRANSITION_TIME);
    const delayFrameNum = round(FPS * DELAY_TIME);
    const transFrames = range(transFrameNum).map(frame =>
      computeFrame(layout, stack, frame / (transFrameNum - 1)));
    const lastFrame = transFrames[transFrames.length - 1];
    const delayFrames = range(delayFrameNum).map(() => lastFrame);

    return [
      ...prev,
      ...transFrames,
      ...delayFrames,
    ];
  }, []);
Esempio n. 4
0
// Iterate over tiles
async function main () {
  const results = featureCollection([])
  console.log('tiles:', slippyGrid.count(geojson, 14, 14))
  for (let tile of slippyGrid.all(geojson, 14, 14)) {
    tile = mercator.tileToGoogle(tile)
    const [x, y, z] = tile
    console.log(tile)
    const url = slippyTile(tile, 'https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt')
    const response = await axios.get(url, {
      headers: {},
      responseType: 'arraybuffer'
    }).catch(e => console.log(tile, 'not found'))

    // Store Results
    if (response && response.data) {
      const vt = new VectorTile(new Protobuf(response.data))
      const images = vt.layers['mapillary-images']

      if (images) {
        range(images.length).map(i => {
          const feature = images.feature(i).toGeoJSON(x, y, z)
          results.features.push(feature)
        })
      }
    }
  }
  const date = moment().format('YYYY-MM-DD')
  const filename = path.join(__dirname, 'mapillary', date + '.geojson')
  write.sync(filename, results)
}
Esempio n. 5
0
	/*
		Gets the keys/indices for this property.

		Implementation note: Subclasses should implement this method in such a way as not to trigger a mapping.
	*/
	keys() {
		if (!this._keys) {
			this._keys = range(this.length);
		}

		return this._keys;
	}
Esempio n. 6
0
function extractCodeBlocks (text) {
  var lines = text.split('\n')
  var matches = text.match(blockOpener) || []
  return range(matches.length).map(function (index) {
    return extractCodeBlock(lines, index)
  })
}
Esempio n. 7
0
module.exports = function (opts) {
  opts = opts || {}
  var start = typeof opts.start === 'number' ?
    opts.start :
    0
  var end = typeof opts.end === 'number' ?
    opts.end :
    100
  var count = typeof opts.count === 'number' ?
    opts.count :
    1
  if (end <= start) {
    throw new Error('Expected end number to be bigger that start number')
  }
  var numbers = range(start, end)
  if (count > numbers.length) {
    throw new Error('You cannot get more than ' + numbers.length + ' numbers')
  }
  var result = []
  while (count--) {
    numbers = shuffle(numbers)
    result.push(numbers.pop())
  }
  return result
}
Esempio n. 8
0
test('init state', function (t) {
  var rows = 19
  var cols = 19
  var keys = range(2).map(function (index) {
    return Keys.generate()
  })
  var players = pluck(keys, 'id')

  var initMsg = {
    content: {
      type: 'Init',
      players: players,
      rules: {
        rows: rows,
        cols: cols
      }
    }
  }

  var state = initState(initMsg)

  t.deepEqual(state, {
    players: players,
    board: new Board({ rows: rows, cols: cols })
  })

  t.end()
})
Esempio n. 9
0
 this.cubeMatrix = range(numRows).map((r) => {
   return range(numCubesInRow).map((c) => {
     var cube = new Cube(r + c)
     cube.mesh.position.set(c, r, 0)
     this.scene.add(cube.mesh)
     return cube
   })
 })
Esempio n. 10
0
 _generateNodes () {
   return range(this.opts.size).map(() => {
     return new Node({
       boundingBoxSize: this.opts.boundingBoxSize,
       color: this.opts.color
     })
   })
 }
test('allows lengths between min and max inclusively', t => {
  range(MIN, MAX + 1).forEach(n => {
    t.deepEqual(
      hasLengthBetween(repeat('a', n)),
      undefined
    );
  });
});
Esempio n. 12
0
 getTransitionData() {
   const n = random(4, 10)
   return range(n).map((i) => {
     return {
       x: i,
       y: random(2, 10)
     };
   });
 }
Esempio n. 13
0
    placeImages() {
        const columnsCount = this.getColumnsCount();
        
        this.setColumnWidth(columnsCount);
        this.columns = range(columnsCount).map(() => { return []; })

        this.images.forEach((image, index) => {
            this.columns[index % columnsCount].push(image);
        });
    }
Esempio n. 14
0
 constructor(props) {
   super(props);
   this.state = {
     topDeltaY: 0,
     mouseY: 0,
     isPressed: false,
     originalPosOfLastPressed: 0,
     order: range(itemsCount),
   };
 };
 it('creates a path with as many segments as its non-empty arguments', wrapDone(function () {
     var ranges = range(2).map(function () {
         return range(random(1, 10));
     });
     expect(ranges.length).to.equal(2);
     ranges.forEach(function (range) {
         var path = makePath.apply(null, range);
         var segmentMatch = path.match(/(\/\w+)/g);
         expect(segmentMatch.length).to.equal(range.length, segmentMatch);
     });
 }));
Esempio n. 16
0
    /**
     * Implements the CA rules
     */
    tickCell( cell, grid ) {
        let count = 0

        // Count up alive neighbours
        range( cell.x - 1, cell.x + 2 ).forEach( x => {
            range( cell.y - 1, cell.y + 2 ).forEach( y => {

                // Check out of bounds
                if ( x < 0 || y < 0 || x > CONFIG.GRID_SIZE - 1 || y > CONFIG.GRID_SIZE - 1 ) {
                    return
                }

                // Check self
                if ( x === cell.x && y === cell.y ) {
                    return
                }

                // If the grid is true then its alive so count it up
                if ( grid[ x ][ y ] ) {
                    count++
                }
            })
        })

        // Alive
        if ( cell.value ) {
            // Under-population - die
            if ( count < 2 ) {
                return false
            }

            // Stable
            if ( count >= 2 && count <= 3 ) {
                return true
            }

            // Over-population
            if ( count > 3 ) {
                return false
            }

            throw new Error( 'appStore::tickCell - this should be unreachable' )
        }

        // Dead
        // Reproduction
        if ( count === 3 ) {
            return true
        }

        // This should be false, denoting a dead cell
        return cell.value
    }
Esempio n. 17
0
  pipes.forEach((pipe) => {
    const x = (canvas.width / 2 - scale(BIRD_RADIUS)) - (scale(bird.x) - scale(pipe.x));
    let y = canvas.height - scale(pipe.y) + scale(HOLE_HEIGHT);

    const bottomPipeBottom = canvas.height - (y + spriteHeight);

    if(bottomPipeBottom > scale(GROUND_HEIGHT)) {

      range(Math.ceil((bottomPipeBottom - scale(GROUND_HEIGHT)) / shaftHeight)).forEach((i) => {
        ctx.save();
        ctx.translate(x, y + spriteHeight + shaftHeight * i);

        drawSprite(ctx, sprites.pipe3, 0, 0, pipeWidth, shaftHeight)
        ctx.restore();
      })
    }

    ctx.save();
    ctx.translate(x, y);
    drawSprite(ctx, sprite, 0, 0, pipeWidth, spriteHeight)
    ctx.restore();

    ctx.save();

    y = canvas.height - scale(pipe.y) - sprite2Height;

    if(y > 0) {
      range(Math.ceil(y / shaftHeight)).forEach((i) => {
        ctx.save();
        ctx.translate(x, y - i * shaftHeight - shaftHeight);
        drawSprite(ctx, sprites.pipe3, 0, 0, pipeWidth, shaftHeight)
        ctx.restore();
      })
    }

    ctx.translate(x, y);
    drawSprite(ctx, sprite2, 0, 0, pipeWidth, sprite2Height)
    ctx.restore();
  })
Esempio n. 18
0
    constructor() {
        this[ _state ] = 'appStore'

        // Generates initial grid of cells - seed
        let grid = range( 0, CONFIG.GRID_SIZE, 0 ).map( row => {
            return range( 0, CONFIG.GRID_SIZE, 0 ).map( cell => false )
        })

        appState.create( this[ _state ], {
            grid: grid,
            app: {
                running: false
            }
        })

        // Next animation frame
        this.frame = null

        // Handles app actions
        dispatcher.register( dispatch => {
            if ( dispatch.type === ACTIONS.UPDATE_CELL ) {
                this.updateCell( Object.assign( dispatch.payload, {
                    value: !dispatch.payload.value
                }))

                return
            }

            if ( dispatch.type === ACTIONS.START ) {
                if ( this.frame ) {
                    return
                }

                this.cursor( [ 'app', 'running' ] ).update( cursor => true )
                this.tick()
                return
            }

            if ( dispatch.type === ACTIONS.STOP ) {
                if ( !this.frame ) {
                    return
                }

                raf.cancel( this.frame )
                this.frame = null
                this.cursor( [ 'app', 'running' ] ).update( cursor => false )
            }
        })
    }
Esempio n. 19
0
        return data.reduce((res, entry) => {
            var parts = entry.split(" ");

            if (!isValidMonth(parts[0])) {
                // Month is missing but it's probably the same as in the
                // previous entry.
                let prev = res[res.length-1];
                if (prev) {
                    parts.unshift(prev.start.format("MMM").toUpperCase());
                } else {
                    // If this is the first one use the current month
                    parts.unshift(moment().format("MMM").toUpperCase());
                }
            }

            var [month, days, ...hours] = parts;

            if (days.includes("-")) {
                let [start, end] = days.split("-").map(d => parseInt(d, 10));
                days = range(start, end+1);
            } else {
                days = [parseInt(days, 10)];
            }

            days = days.map(d => String(d));

            hours = hours.map(h => {
                var [start, end] = h.split("-");
                return {start, end};
            });


            days.forEach(day => {
                hours.forEach(h => {
                    var start = parseUTCTime({month, day, time: h.start});
                    var end = parseUTCTime({month, day, time: h.end});
                    res.push({start, end});
                });
            });

            return res;

        }, []);
Esempio n. 20
0
        range( cell.x - 1, cell.x + 2 ).forEach( x => {
            range( cell.y - 1, cell.y + 2 ).forEach( y => {

                // Check out of bounds
                if ( x < 0 || y < 0 || x > CONFIG.GRID_SIZE - 1 || y > CONFIG.GRID_SIZE - 1 ) {
                    return
                }

                // Check self
                if ( x === cell.x && y === cell.y ) {
                    return
                }

                // If the grid is true then its alive so count it up
                if ( grid[ x ][ y ] ) {
                    count++
                }
            })
        })
Esempio n. 21
0
  render() {
    const {mouseY, isPressed, originalPosOfLastPressed, order} = this.state;

    return (
      <div className="demo8">
        {range(itemsCount).map(i => {
          const style = originalPosOfLastPressed === i && isPressed
            ? {
                scale: spring(1.1, springConfig),
                shadow: spring(16, springConfig),
                y: mouseY,
              }
            : {
                scale: spring(1, springConfig),
                shadow: spring(1, springConfig),
                y: spring(order.indexOf(i) * 100, springConfig),
              };
          return (
            <Motion style={style} key={i}>
              {({scale, shadow, y}) =>
                <div
                  onMouseDown={this.handleMouseDown.bind(null, i, y)}
                  onTouchStart={this.handleTouchStart.bind(null, i, y)}
                  className="demo8-item"
                  style={{
                    boxShadow: `rgba(0, 0, 0, 0.2) 0px ${shadow}px ${2 * shadow}px 0px`,
                    transform: `translate3d(0, ${y}px, 0) scale(${scale})`,
                    WebkitTransform: `translate3d(0, ${y}px, 0) scale(${scale})`,
                    zIndex: i === originalPosOfLastPressed ? 99 : i,
                  }}>
                  {order.indexOf(i) + 1}
                </div>
              }
            </Motion>
          );
        })}
      </div>
    );
  };
Esempio n. 22
0
Row.prototype.toMarkdown = function (colgroup) {
  var out = []
  out.push('|')
  var index = 0
  this.cells.forEach(function (cell) {
    var align = colgroup.getAlignAt(index)
    var size = colgroup.getFormatedSizeAt(index, cell.colspan)
    out.push(cell.toMarkdown(align, size))
    out.push(repeat('|', cell.colspan))
    index += cell.colspan
  })

  // Add missing empty cells
  // TODO: Refactor: move this in the Table normalization process ?
  if (index < colgroup.columns.length) {
    range(index, colgroup.columns.length).forEach(function (index) {
      out.push(' ' + repeat(' ', colgroup.getFormatedSizeAt(index)) + ' |')
    })
  }

  return out.join('')
}
Esempio n. 23
0
  render(props, state) {
    const now = new Date();
    const end = state.year + mod((now.getFullYear() - state.year), 10) + 1;
    const start = end - 10;
    const YEARS = range(start, end);

    const open = () => this.setState({
      open: true,
      undo: { month: state.month, year: state.year }
    });
    const cancel = () => this.setState({
      open: false,
      month: state.undo.month,
      year: state.undo.year
    });
    const close = () => this.setState({ open: false });
    const toggle = () => this.setState({
      open: !state.open,
      undo: { month: state.month, year: state.year }
    });
    const prev = () => this.setState({ year: state.year - 10 });
    const next = () => this.setState({ year: state.year + 10 });
    const change = event => {
      if (this._input.checkValidity()) {
        const text = event.target.value.trim();
        const date = dateParse(text);
        if (date) {
          this.setState({
            month: MONTHS[date.getMonth()],
            year: date.getFullYear()
          });
        }
      }
    };
    const tabListener = event => {
      if (event.keyCode === 9) { // TAB
        this.setState({ open: false });
      }
      return true;
    };

    const value = state.month && state.year ? `${state.month} ${state.year}` : props.value;

    return (
      <div className="date_month">
        <header>
          <div className="input-group">
            <input
              className="form-control"
              name={props.name}
              onClick={open}
              onFocus={open}
              onInput={change}
              onKeyDown={tabListener}
              pattern={DATE_PATTERN}
              ref={component => this._input = component}
              required={props.required}
              type="text"
              value={value}
            />
            <span class="input-group-append">
              <button class="btn btn-secondary active px-2 toggle" tabIndex="-1" onClick={toggle} type="button">
                <i aria-hidden="true" class="fa fa-calendar-o fa-fw icon-calendar-o icon-fw icon"></i>
              </button>
            </span>
          </div>
        </header>
        {state.open ?
          <div className="picker">
            <div className="row">
              <div className="month col">
                <ul>
                  {MONTHS.map(month => <Label selected={state.month === month} label={month} onClick={() => this.setMonth(month)} />)}
                </ul>
              </div>

              <div className="year col text-center">
                <header className="btn-group btn-group-sm btn-group-justified">
                  <button id="prev" onClick={prev} className="btn btn-link">
                    <i aria-hidden="true" class="fa fa-angle-left fa-fw icon-angle-left icon-fw icon"></i>
                  </button>
                  <button id="next" onClick={next} className="btn btn-link">
                    <i aria-hidden="true" class="fa fa-angle-right fa-fw icon-angle-right icon-fw icon"></i>
                  </button>
                </header>
                <ul>
                  {YEARS.map(year => <Label selected={state.year === year} label={year} onClick={() => this.setYear(year)} />)}
                </ul>
              </div>
            </div>
            <footer className="text-center">
              <div className="btn-group">
                <button id="save" className="btn btn-sm btn-secondary" onClick={close}>OK</button>
                <button id="cancel" className="btn btn-sm btn-secondary" onClick={cancel}>Cancel</button>
              </div>
            </footer>
          </div> : null}
      </div>);
  }
Esempio n. 24
0
 generateRandomData() {
   return range(1, 7).map(() => ({x: " ", y: random(1, 10)}));
 }
Esempio n. 25
0
function postsGen(number) {
  return range(1, number + 1).map(postWithId);
}
Esempio n. 26
0
 .subscribe(({acc, parts}) => {
   for (var index of range(1, parts + 1)) {
     document.getElementById('part_' + index).style.color = (!acc || acc === index) ? 'black' : 'gray'
   }
 })
 var ranges = range(2).map(function () {
     return range(random(1, 10));
 });
Esempio n. 28
0
  map(connectionTimestamps, (timestamp) => {
    if (locked.length === 0) {
      return
    }

    unlockATrack(timestamp)
    unlockATrack(timestamp + 1)
  })

  return unlocked
}


const unlocked = {}
map(range(nTracks), index => {
  unlocked[index] = false
})
map(unlockedIndexes, index => {
  unlocked[index] = true
})

function getLocked() {
  return map(unlocked, (isUnlocked, index) => {
    return !isUnlocked && index
  }).filter(index => index !== false)
}


/* eslint-disable */
function hashTimestamp(input) {
Esempio n. 29
0
test.beforeEach(t => {
  numbers = range(1, 100);
});
Esempio n. 30
0
function times (i, work, callback) {
  parallel(range(i).map((i) => (callback) => work(i, callback)), callback)
}