<commit_before>/*global module:false*/
module.exports = function(grunt) {
    "use strict";

    var jsFiles = [
        'js/*.js',
        'js/collections/*.js',
        'js/models/*.js',
        'js/views/*.js',
        'test/*.js'
    ];

    // Project configuration.
    grunt.initConfig({
        lint: {
            files: jsFiles
        },
        requirejs: {
            compile: {
                options: {
                    name: "main",
                    baseUrl: "js/",
                    mainConfigFile: "js/main.js",
                    out: "dist/compiled.js"
                }
            }
        },
        mincss: {
            compress: {
                files: {
                    'dist/compiled.css': [
                        'css/bootstrap.min.css',
                        'dist/application-embed.css'
                    ]
                }
            }
        },
        imageEmbed: {
            application: {
                src: 'css/application.css',
                dest: 'dist/application-embed.css',
                deleteAfterEncoding : false
            }
        },
        clean: {
            css: {
                files: [
                    'dist/application-embed.css'
                ]
            }
        },
        mocha: {
            all: [ 'test/index.html' ]
        }
    });

    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-contrib-mincss');
    grunt.loadNpmTasks('grunt-image-embed');
    grunt.loadNpmTasks('grunt-cleanx');
    grunt.loadNpmTasks('grunt-mocha');

    grunt.registerTask('package', 'compile:js compile:css');
    grunt.registerTask('compile:js', 'requirejs');
    grunt.registerTask('compile:css', 'imageEmbed mincss clean:css');
    grunt.registerTask('test', 'lint mocha');
};
<commit_msg>[grunt] Add test/** files<commit_after>/*global module:false*/
module.exports = function(grunt) {
    "use strict";

    var jsFiles = [
        'js/*.js',
        'js/collections/*.js',
        'js/models/*.js',
        'js/views/*.js',
        'test/*.js',
        'test/**/*.js'
    ];

    // Project configuration.
    grunt.initConfig({
        lint: {
            files: jsFiles
        },
        requirejs: {
            compile: {
                options: {
                    name: "main",
                    baseUrl: "js/",
                    mainConfigFile: "js/main.js",
                    out: "dist/compiled.js"
                }
            }
        },
        mincss: {
            compress: {
                files: {
                    'dist/compiled.css': [
                        'css/bootstrap.min.css',
                        'dist/application-embed.css'
                    ]
                }
            }
        },
        imageEmbed: {
            application: {
                src: 'css/application.css',
                dest: 'dist/application-embed.css',
                deleteAfterEncoding : false
            }
        },
        clean: {
            css: {
                files: [
                    'dist/application-embed.css'
                ]
            }
        },
        mocha: {
            all: [ 'test/index.html' ]
        }
    });

    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-contrib-mincss');
    grunt.loadNpmTasks('grunt-image-embed');
    grunt.loadNpmTasks('grunt-cleanx');
    grunt.loadNpmTasks('grunt-mocha');

    grunt.registerTask('package', 'compile:js compile:css');
    grunt.registerTask('compile:js', 'requirejs');
    grunt.registerTask('compile:css', 'imageEmbed mincss clean:css');
    grunt.registerTask('test', 'lint mocha');
};
<|endoftext|>


<commit_before>;(function () {
    "use strict";

    function makeCircle(fill) {
        var N = 50; //number of triangles for circle
        var dtheta = 2*pi/N;
        var sind = sin(dtheta), cosd = cos(dtheta);
        var y=0, z=-1, r=1;
        var newy, newz;

        var m;
        m = { pos: [] }
        if (fill) {
            m.index = [];
            m.pos.push( vec(0, 0, 0) );
        }
        for (var i=1; i<1+N; i++) {
            m.pos.push( vec(0,y,z) );
            if (fill) m.index.push( 0,i,(i%N)+1 );
            newy = y*cosd + z*sind;
            newz = z*cosd - y*sind;
            r = sqrt(newy*newy + newz*newz);
            y = newy/r;
            z = newz/r;
        }
        if (!fill) m.pos.push(m.pos[0]);

        return m;
    }

    function circle(args) {
        if (!(this instanceof circle)) return new circle(args);
        args = args || {};
        if (args.canvas !== undefined) {
            this.canvas = args.canvas;
            delete args.canvas;
        } else {
            this.canvas = canvas.selected;
        }
        if (this.canvas) {
            this.canvas.__activate();
        }

        var R = args.radius || 1; delete args.radius;
        args.fill = args.fill || false;
        args.pos = args.pos || vec(0,0,0);
        args.axis = args.axis || vec(1,0,0);
        args.up = args.up || vec(0,1,0);
        //args.normal = vec(1,0,0);
        args.color = args.color || vec(1,1,1);
        args.opacity = args.opacity || 1;
        args.shininess = args.shininess || 1;
        args.emissive = args.emissive || 0;

        var m = makeCircle(args.fill);

        if (args.fill) {
            var v = [];
            for (var i=0; i<m.pos.length; i++) {
                //vec(R*mi.x, R*mi.y, R*mi.z),
                v.push( vertex({    pos: m.pos[i].multiply(R),  normal: vec(1,0,0),
                                    color: args.color,          opacity: args.opacity,
                                    shininess: args.shininess,  emissive: args.emissive
                }) );
            }

            var t = [];
            for (var i=0; i<m.index.length; i+=3) {
                t.push( triangle({ v0: v[m.index[i]], v1: v[m.index[i+1]], v2: v[m.index[i+2]] }) );
            }

            return compound( t, { pos: args.pos, axis: args.axis, up: args.up } );
        } else {
            var p = m.pos;
            for (var i=0; i<p.length; i++) { p[i] = p[i].multiply(R); }
            return curve({radius: 0.02*R, origin: args.pos, pos: p, axis: args.axis, up: args.up,
                        color: args.color, opacity: args.opacity, shininess: args.shininess,
                        emissive: args.emissive })
        }
    }

    var global = window
    function Export( exports ) {
        if (!global.gsast) global.gsast = {}
        for(var id in exports) {
            if (!global[id]) global[id] = exports[id]
            gsast[id] = exports[id]
        }
    }

    var exports = { circle: circle }
    Export(exports)
}) ();
<commit_msg>Error with default value for fill.<commit_after>;(function () {
    "use strict";

    function makeCircle(fill) {
        var N = 50; //number of triangles for circle
        var dtheta = 2*pi/N;
        var sind = sin(dtheta), cosd = cos(dtheta);
        var y=0, z=-1, r=1;
        var newy, newz;

        var m;
        m = { pos: [] }
        if (fill) {
            m.index = [];
            m.pos.push( vec(0, 0, 0) );
        }
        for (var i=1; i<1+N; i++) {
            m.pos.push( vec(0,y,z) );
            if (fill) m.index.push( 0,i,(i%N)+1 );
            newy = y*cosd + z*sind;
            newz = z*cosd - y*sind;
            r = sqrt(newy*newy + newz*newz);
            y = newy/r;
            z = newz/r;
        }
        if (!fill) m.pos.push(m.pos[0]);

        return m;
    }

    function circle(args) {
        if (!(this instanceof circle)) return new circle(args);
        args = args || {};
        if (args.canvas !== undefined) {
            this.canvas = args.canvas;
            delete args.canvas;
        } else {
            this.canvas = canvas.selected;
        }
        if (this.canvas) {
            this.canvas.__activate();
        }

        var R = args.radius || 1; delete args.radius;
        args.fill = args.fill || true;
        args.pos = args.pos || vec(0,0,0);
        args.axis = args.axis || vec(1,0,0);
        args.up = args.up || vec(0,1,0);
        //args.normal = vec(1,0,0);
        args.color = args.color || vec(1,1,1);
        args.opacity = args.opacity || 1;
        args.shininess = args.shininess || 1;
        args.emissive = args.emissive || 0;

        var m = makeCircle(args.fill);

        if (args.fill) {
            var v = [];
            for (var i=0; i<m.pos.length; i++) {
                //vec(R*mi.x, R*mi.y, R*mi.z),
                v.push( vertex({    pos: m.pos[i].multiply(R),  normal: vec(1,0,0),
                                    color: args.color,          opacity: args.opacity,
                                    shininess: args.shininess,  emissive: args.emissive
                }) );
            }

            var t = [];
            for (var i=0; i<m.index.length; i+=3) {
                t.push( triangle({ v0: v[m.index[i]], v1: v[m.index[i+1]], v2: v[m.index[i+2]] }) );
            }

            return compound( t, { pos: args.pos, axis: args.axis, up: args.up } );
        } else {
            var p = m.pos;
            for (var i=0; i<p.length; i++) { p[i] = p[i].multiply(R); }
            return curve({radius: 0.02*R, origin: args.pos, pos: p, axis: args.axis, up: args.up,
                        color: args.color, opacity: args.opacity, shininess: args.shininess,
                        emissive: args.emissive })
        }
    }

    var global = window
    function Export( exports ) {
        if (!global.gsast) global.gsast = {}
        for(var id in exports) {
            if (!global[id]) global[id] = exports[id]
            gsast[id] = exports[id]
        }
    }

    var exports = { circle: circle }
    Export(exports)
}) ();
<|endoftext|>


<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // default font size in pixels for all tabs
    fontSize: 16,

    // font family with optional fallbacks
    fontFamily: '"Operator Mono", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: '#535860',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'UNDERLINE',

    // set to true for blinking cursor
    cursorBlink: true,

    // color of the text
    foregroundColor: '#8c97a9',

    // terminal background color
    backgroundColor: '#1f2126',

    // border color (window, tabs)
    borderColor: '#505864',

    // custom css to embed in the main window
    css: '',

    // custom css to embed in the terminal window
    termCSS: `
    `,

    // set to `true` (without backticks) if you're using a Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows (ignored on macOS)
    showHamburgerMenu: '',

    // set to `false` if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` on windows and Linux (ignored on macOS)
    showWindowControls: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#bf6e7c',
      green: '#88b379',
      yellow: '#d9bd86',
      blue: '#59b3c5',
      magenta: '#b27ecd',
      cyan: '#59b3c5',
      white: '#59b3c5',
      lightBlack: '#535860',
      lightRed: '#bf6e7c',
      lightGreen: '#88b379',
      lightYellow: '#d9bd86',
      lightBlue: '#59b3c5',
      lightMagenta: '#b27ecd',
      lightCyan: '#59b3c5',
      lightWhite: '#e5e5e5'
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    // make sure to use a full path if the binary name doesn't work
    // (e.g `C:\\Windows\\System32\\bash.exe` instead of just `bash.exe`)
    // if you're using powershell, make sure to remove the `--login` below
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: false,

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false

    // if true, on right click selected text will be copied or pasted if no
    // selection is present (true by default on Windows)
    // quickEdit: true

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: []
};
<commit_msg>hyper.js configs.<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // default font size in pixels for all tabs
    fontSize: 15,

    // font family with optional fallbacks
    fontFamily: '"Operator Mono", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',
    uiFontFamily: '"Operator Mono", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: '#5C6370',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'UNDERLINE',

    // set to true for blinking cursor
    cursorBlink: true,

    // color of the text
    foregroundColor: '#abb2bf',

    // terminal background color
    backgroundColor: '#282c34',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '',

    // custom css to embed in the terminal window
    termCSS: '',

    // set to `true` (without backticks) if you're using a Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows (ignored on macOS)
    showHamburgerMenu: '',

    // set to `false` if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` on windows and Linux (ignored on macOS)
    showWindowControls: 'false',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '7px 10px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#0f1011',
      red: '#e06c75',
      green: '#98c379',
      yellow: '#e5c07b',
      blue: '#56b6c2',
      magenta: '#c678dd',
      cyan: '#61afef',
      white: '#3e4451',
      lightBlack: '#5C6370',
      lightRed: '#e06c75',
      lightGreen: '#98c379',
      lightYellow: '#e5c07b',
      lightBlue: '#56b6c2',
      lightMagenta: '#c678dd',
      lightCyan: '#61afef',
      lightWhite: '#ffffff'
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    // make sure to use a full path if the binary name doesn't work
    // (e.g `C:\\Windows\\System32\\bash.exe` instead of just `bash.exe`)
    // if you're using powershell, make sure to remove the `--login` below
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false

    // if true, on right click selected text will be copied or pasted if no
    // selection is present (true by default on Windows)
    // quickEdit: true

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg

  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    'hyperlinks',
    // 'hyperminimal'
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: []
};<|endoftext|>


<commit_before>import {insertCSS} from "../dom"

let svgCollection = null
const svgBuilt = Object.create(null)

const SVG = "http://www.w3.org/2000/svg"
const XLINK = "http://www.w3.org/1999/xlink"

const prefix = "ProseMirror-icon"

const baseURL = /([^#]*)/.exec(document.location)[1]

export function getIcon(name, data) {
  let node = document.createElement("div")
  node.className = prefix
  if (data.path) {
    if (!svgBuilt[name]) buildSVG(name, data)
    let svg = node.appendChild(document.createElementNS(SVG, "svg"))
    svg.style.width = (data.width / data.height) + "em"
    let use = svg.appendChild(document.createElementNS(SVG, "use"))
    use.setAttributeNS(XLINK, "href", baseURL + "#pm-icon-" + name)
  } else if (data.dom) {
    node.appendChild(data.dom.cloneNode(true))
  } else {
    node.appendChild(document.createElement("span")).textContent = data.text || ''
    if (data.style) node.firstChild.style.cssText = data.style
  }
  return node
}

function buildSVG(name, data) {
  if (!svgCollection) {
    svgCollection = document.createElementNS(SVG, "svg")
    svgCollection.style.display = "none"
    document.body.insertBefore(svgCollection, document.body.firstChild)
  }
  let sym = document.createElementNS(SVG, "symbol")
  sym.id = "pm-icon-" + name
  sym.setAttribute("viewBox", "0 0 " + data.width + " " + data.height)
  let path = sym.appendChild(document.createElementNS(SVG, "path"))
  path.setAttribute("d", data.path)
  svgCollection.appendChild(sym)
  svgBuilt[name] = true
}

insertCSS(`
.${prefix} {
  display: inline-block;
  line-height: .8;
  vertical-align: -2px; /* Compensate for padding */
  padding: 2px 8px;
  cursor: pointer;
}

.${prefix} svg {
  fill: currentColor;
  height: 1em;
}

.${prefix} span {
  vertical-align: text-top;
}`)
<commit_msg>Recompute base url every time an icon is created<commit_after>import {insertCSS} from "../dom"

let svgCollection = null
const svgBuilt = Object.create(null)

const SVG = "http://www.w3.org/2000/svg"
const XLINK = "http://www.w3.org/1999/xlink"

const prefix = "ProseMirror-icon"

export function getIcon(name, data) {
  let node = document.createElement("div")
  node.className = prefix
  if (data.path) {
    if (!svgBuilt[name]) buildSVG(name, data)
    let svg = node.appendChild(document.createElementNS(SVG, "svg"))
    svg.style.width = (data.width / data.height) + "em"
    let use = svg.appendChild(document.createElementNS(SVG, "use"))
    use.setAttributeNS(XLINK, "href", /([^#]*)/.exec(document.location)[1] + "#pm-icon-" + name)
  } else if (data.dom) {
    node.appendChild(data.dom.cloneNode(true))
  } else {
    node.appendChild(document.createElement("span")).textContent = data.text || ''
    if (data.style) node.firstChild.style.cssText = data.style
  }
  return node
}

function buildSVG(name, data) {
  if (!svgCollection) {
    svgCollection = document.createElementNS(SVG, "svg")
    svgCollection.style.display = "none"
    document.body.insertBefore(svgCollection, document.body.firstChild)
  }
  let sym = document.createElementNS(SVG, "symbol")
  sym.id = "pm-icon-" + name
  sym.setAttribute("viewBox", "0 0 " + data.width + " " + data.height)
  let path = sym.appendChild(document.createElementNS(SVG, "path"))
  path.setAttribute("d", data.path)
  svgCollection.appendChild(sym)
  svgBuilt[name] = true
}

insertCSS(`
.${prefix} {
  display: inline-block;
  line-height: .8;
  vertical-align: -2px; /* Compensate for padding */
  padding: 2px 8px;
  cursor: pointer;
}

.${prefix} svg {
  fill: currentColor;
  height: 1em;
}

.${prefix} span {
  vertical-align: text-top;
}`)
<|endoftext|>


<commit_before>feelings = new Mongo.Collection( "feelings" );

addthis_share = {
   url: "http://www.mesinto.net",
   title: "Me Sinto"
}

addthis_config = {
  pubid: "ra-54e10de11e511825"

}

if (Meteor.isClient) {

  var scene;

  var sub = Meteor.subscribe( "feelingsSmallSet", function onReady() {
    var array = feelings.find().fetch();
    Session.set("Tile0", array[0].user.profile_image_url_https );
    Session.set("Tile1", array[1].user.profile_image_url_https );
    Session.set("Tile2", array[2].user.profile_image_url_https );
    Session.set("Tile3", array[3].user.profile_image_url_https );
    sub.stop();
  } );

  Tracker.autorun( function() { document.title = i18n( "appName" ); } );

  configInternationalization();

  maxNumberOfContainers = 6;
  var backgroundPhotos = []

  function now() { return +(new Date()); }
  function rand() { return Math.round( Math.random() * 1000000 ); }

  Session.set( "Counter 0", 0 );
  Session.set( "Counter 1", 0 );
  Session.set( "Counter 2", 0 );
  Session.set( "Counter 3", 0 );
  Session.set( "Counter 4", 0 );
  Session.set( "Counter 5", 0 );
  Session.set( "Images", [] );
  Session.setDefault( "WordList", [] );
  Session.setDefault( "WordCounter", [] );

  function buildPlot() {

    d3.select("#demo").selectAll("#vs").remove();
    d3.select("#demo").append("div").attr("id", "vs");

    var modelArray = [];
    var strataArray = [];
    var list = [];

    for(var i = 0; i < maxNumberOfContainers; ++i) {
      list.push( { label : "" } );
    }

    _.each( list, function( word ) {
      strataArray.push( [ { initValue : 10 } ] );
    } );

    var divWidth = parseInt( d3.select("#plotDiv").style('width') ) - 30;
    var viewportWidth = divWidth;
    var chartX = 10;
    var chartY = 50;
    var chartWidth = viewportWidth - 2 * chartX;
    var settings = {
      width  : viewportWidth,
      height : 300,
      data:{
            model: list,
            strata: strataArray,
            stream:{
              provider:'none'
            },
          },
      sedimentation:{
        token:{
          size:{original:20,minimum:3}
        },
        aggregation:{height:180},
        suspension:{
          decay: { power : 1.005 }
        }
      },
      options:{
        layout:false
      },
      chart:{
        x: chartX,
        y: chartY,
        height : 280,
        width : chartWidth,
        type : "StackedAreaChart",
        wallColor : "rgba(230,230,230,0.5)",
        label : true,
        spacer : 1,
      }
    };

    scene = $("#vs").vs(settings).data('visualSedimentation');

  }

  Template.BodyT.rendered = function() {
    $LAB.script( "http://s7.addthis.com/js/250/addthis_widget.js" ).wait();
  }

  Template.VisualSedimentationT.rendered = function() {
    buildPlot();
    Tracker.autorun( updateLegend );
  };
  Tracker.autorun( observeData );

  var backgroundHandler;
  function restartBackgroundLoop() {

    if( _.isUndefined( backgroundHandler ) == false ) {
      clearInterval( backgroundHandler );
    }

    backgroundHandler = setInterval( function() {

      if( _.isEmpty( backgroundPhotos ) ) {
        return;
      }

      backgroundPhotos = _.shuffle( backgroundPhotos );
      Session.set( "Image", backgroundPhotos.pop() );

    }, 20000 );
  }
  restartBackgroundLoop();

  setInterval( function() {

    if( _.isUndefined( scene ) ) {
      return;
    }

    var array = myPop();
    _.each(array, function( p ) {
      setTimeout( function() {
        var counterId = "Counter " + p.category;
        Session.set( counterId, Session.get( counterId ) + 1 );
        scene.addToken( p );
      }, rand() % 5000 );
    } );

  }, 5000 );

  function observeData() {
    var wordList = Session.get( "WordList" );

    Session.set( "DataIsReady", false );
    Meteor.subscribe( "feelings", wordList, function() {
      Session.set( "DataIsReady", true );
      feelings.find({}).observeChanges( {
        added : function( id, tweet ) {

          if( _.size( tweet ) == 1 ) {
            return;
          }

          //
          // Twitter API appends RT @screen_name to retweets.
          // We want to ignore those as they are repeated over
          // and over as background
          //
          if( _.isUndefined( tweet.retweeted_status ) == false ) {
            return;
          }

          obj = buildBackgroundObject( tweet );
          if( _.isEqual( obj.type, "photo" ) == true &&
              backgroundPhotos.length < 1000 ) {
              backgroundPhotos.push( obj )  ;
          }

          var wordList = Session.get( "WordList" )
          var text = tweet.text.toLowerCase();
          _.each( wordList, function( word, idx ) {
            if( text.indexOf( word ) != -1 ) {
              myEnqueue( {
                tweet : tweet,
                size : 60 / maxNumberOfContainers,
                category : idx,
                callback : {
                  onclick : function( token ) {
                    var obj = buildBackgroundObject( token.myobj.m_userData.tweet );
                    Session.set( "Image", obj );
                    restartBackgroundLoop();
                  },
                  mouseover : function( token ) {
                  }
                }
              } );
            }
          } );
        }
      } ) ;
    } );
  }

  function updateLegend() {

    d3.select("svg").select("#legend").remove();

    var wordList = Session.get( "WordList" );
    var textNode = d3.select("svg").append("g").attr("id", "legend");
    var textXDelta = settings.chart.width / maxNumberOfContainers;
    var textX = settings.chart.x + textXDelta * 0.5;
    var textYA = settings.chart.y - 30;
    var textYB = settings.chart.y - 10;

    _.each( wordList, function( word, idx ) {
      textNode
        .append("g")
        .append("text")
        .attr( "font-size", 20)
        .attr( "font-family", "HelveticaNeue-Light")
        .attr( "font-weight", 300)
        .attr( "fill", "white")
        .attr( "text-anchor", "middle")
        .attr( "pointer-events", "all")
        .attr( "cursor", "pointer")
        .text( word )
        .on("click", function( d ) {
          var w = d3.select(this).text().toLowerCase();
          var wordList = Session.get( "WordList" );
          wordList = _.filter( wordList, function( word ) {
            return _.isEqual( word, w ) == false;
          } );
          Session.set( "WordList", wordList );
        } )
        .attr("transform", function() {
          if( idx % 2 == 0 ) {
            return "translate(" + textX + "," + textYA + ")"
          }
          return "translate(" + textX + "," + textYB + ")"
        });
      textX += textXDelta;
    } );
  }

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    var termsCollection = new Mongo.Collection( "commonTerms" );

    Meteor.publish( "feelingsSmallSet", function( ) {
      var options = {
        fields : { "user.profile_image_url_https" : 1 },
        limit : 4
      };
      return feelings.find( { }, options );
    } );

    Meteor.publish( "feelings", function( words, lang ) {

      var list = "";
      _.each( words, function( word ) {
        var query = {};
        var modfiers = {};
        var increment = {};
        query[ word ] = { $exists : true } ;

        var cursor = termsCollection.find( query );
        if( cursor.count() == 0 ) {
          var term = {};
          term[ word ] = 1;
          termsCollection.insert( term );
        } else {
          var array = cursor.fetch();
          increment[ word ] = +1;
          modfiers[ "$inc" ] = increment;
          termsCollection.update( { _id : array[ 0 ]._id }, modfiers );
        }

        list += word + " ";
      } );

      var query = {
        $text : {
          $search : list,
          $language : "en"
        }
      };
      var options = {
        fields : {
          id_str : 1,
          text : 1,
          created_at : 1,
          "entities.media" : 1,
          "user.id_str" : 1,
          "user.screen_name" : 1,
          "user.profile_image_url_https" : 1,
          "retweeted_status.id_str" : 1
        }
      };
      return feelings.find( query, options );
    } );
  });
}
<commit_msg>Render no photo tweets, in case no media is available<commit_after>feelings = new Mongo.Collection( "feelings" );

addthis_share = {
   url: "http://www.mesinto.net",
   title: "Me Sinto"
}

addthis_config = {
  pubid: "ra-54e10de11e511825"

}

if (Meteor.isClient) {

  var scene;

  var sub = Meteor.subscribe( "feelingsSmallSet", function onReady() {
    var array = feelings.find().fetch();
    Session.set("Tile0", array[0].user.profile_image_url_https );
    Session.set("Tile1", array[1].user.profile_image_url_https );
    Session.set("Tile2", array[2].user.profile_image_url_https );
    Session.set("Tile3", array[3].user.profile_image_url_https );
    sub.stop();
  } );

  Tracker.autorun( function() { document.title = i18n( "appName" ); } );

  configInternationalization();

  maxNumberOfContainers = 6;
  var backgroundPhotos = []
  var backgroundProfile = []

  function now() { return +(new Date()); }
  function rand() { return Math.round( Math.random() * 1000000 ); }

  Session.set( "Counter 0", 0 );
  Session.set( "Counter 1", 0 );
  Session.set( "Counter 2", 0 );
  Session.set( "Counter 3", 0 );
  Session.set( "Counter 4", 0 );
  Session.set( "Counter 5", 0 );
  Session.set( "Images", [] );
  Session.setDefault( "WordList", [] );
  Session.setDefault( "WordCounter", [] );

  function buildPlot() {

    d3.select("#demo").selectAll("#vs").remove();
    d3.select("#demo").append("div").attr("id", "vs");

    var modelArray = [];
    var strataArray = [];
    var list = [];

    for(var i = 0; i < maxNumberOfContainers; ++i) {
      list.push( { label : "" } );
    }

    _.each( list, function( word ) {
      strataArray.push( [ { initValue : 10 } ] );
    } );

    var divWidth = parseInt( d3.select("#plotDiv").style('width') ) - 30;
    var viewportWidth = divWidth;
    var chartX = 10;
    var chartY = 50;
    var chartWidth = viewportWidth - 2 * chartX;
    var settings = {
      width  : viewportWidth,
      height : 300,
      data:{
            model: list,
            strata: strataArray,
            stream:{
              provider:'none'
            },
          },
      sedimentation:{
        token:{
          size:{original:20,minimum:3}
        },
        aggregation:{height:180},
        suspension:{
          decay: { power : 1.005 }
        }
      },
      options:{
        layout:false
      },
      chart:{
        x: chartX,
        y: chartY,
        height : 280,
        width : chartWidth,
        type : "StackedAreaChart",
        wallColor : "rgba(230,230,230,0.5)",
        label : true,
        spacer : 1,
      }
    };

    scene = $("#vs").vs(settings).data('visualSedimentation');

  }

  Template.BodyT.rendered = function() {
    $LAB.script( "http://s7.addthis.com/js/250/addthis_widget.js" ).wait();
  }

  Template.VisualSedimentationT.rendered = function() {
    buildPlot();
    Tracker.autorun( updateLegend );
  };
  Tracker.autorun( observeData );

  var backgroundHandler;
  function restartBackgroundLoop() {

    if( _.isUndefined( backgroundHandler ) == false ) {
      clearInterval( backgroundHandler );
    }

    backgroundHandler = setInterval( function() {

      if( _.isEmpty( backgroundPhotos ) ) {
        if( _.isEmpty( backgroundProfile ) ) {
          return
        }
        backgroundProfile = _.shuffle( backgroundProfile );
        Session.set( "Image", backgroundProfile.pop() );
      } else {
        backgroundPhotos = _.shuffle( backgroundPhotos );
        Session.set( "Image", backgroundPhotos.pop() );
      }

    }, 20000 );
  }
  restartBackgroundLoop();

  setInterval( function() {

    if( _.isUndefined( scene ) ) {
      return;
    }

    var array = myPop();
    _.each(array, function( p ) {
      setTimeout( function() {
        var counterId = "Counter " + p.category;
        Session.set( counterId, Session.get( counterId ) + 1 );
        scene.addToken( p );
      }, rand() % 5000 );
    } );

  }, 5000 );

  function observeData() {
    var wordList = Session.get( "WordList" );

    Session.set( "DataIsReady", false );
    Meteor.subscribe( "feelings", wordList, function() {
      Session.set( "DataIsReady", true );
      feelings.find({}).observeChanges( {
        added : function( id, tweet ) {

          if( _.size( tweet ) == 1 ) {
            return;
          }

          //
          // Twitter API appends RT @screen_name to retweets.
          // We want to ignore those as they are repeated over
          // and over as background
          //
          if( _.isUndefined( tweet.retweeted_status ) == false ) {
            return;
          }

          obj = buildBackgroundObject( tweet );

          if( _.isEqual( obj.type, "photo" ) == false &&
            backgroundProfile.length < 1000 ) {
            backgroundProfile.push( obj );
          }

          if( _.isEqual( obj.type, "photo" ) == true &&
              backgroundPhotos.length < 1000 ) {
              backgroundPhotos.push( obj )  ;
          }

          var wordList = Session.get( "WordList" )
          var text = tweet.text.toLowerCase();
          _.each( wordList, function( word, idx ) {
            if( text.indexOf( word ) != -1 ) {
              myEnqueue( {
                tweet : tweet,
                size : 60 / maxNumberOfContainers,
                category : idx,
                callback : {
                  onclick : function( token ) {
                    var obj = buildBackgroundObject( token.myobj.m_userData.tweet );
                    Session.set( "Image", obj );
                    restartBackgroundLoop();
                  },
                  mouseover : function( token ) {
                  }
                }
              } );
            }
          } );
        }
      } ) ;
    } );
  }

  function updateLegend() {

    d3.select("svg").select("#legend").remove();

    var wordList = Session.get( "WordList" );
    var textNode = d3.select("svg").append("g").attr("id", "legend");
    var textXDelta = settings.chart.width / maxNumberOfContainers;
    var textX = settings.chart.x + textXDelta * 0.5;
    var textYA = settings.chart.y - 30;
    var textYB = settings.chart.y - 10;

    _.each( wordList, function( word, idx ) {
      textNode
        .append("g")
        .append("text")
        .attr( "font-size", 20)
        .attr( "font-family", "HelveticaNeue-Light")
        .attr( "font-weight", 300)
        .attr( "fill", "white")
        .attr( "text-anchor", "middle")
        .attr( "pointer-events", "all")
        .attr( "cursor", "pointer")
        .text( word )
        .on("click", function( d ) {
          var w = d3.select(this).text().toLowerCase();
          var wordList = Session.get( "WordList" );
          wordList = _.filter( wordList, function( word ) {
            return _.isEqual( word, w ) == false;
          } );
          Session.set( "WordList", wordList );
        } )
        .attr("transform", function() {
          if( idx % 2 == 0 ) {
            return "translate(" + textX + "," + textYA + ")"
          }
          return "translate(" + textX + "," + textYB + ")"
        });
      textX += textXDelta;
    } );
  }

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    var termsCollection = new Mongo.Collection( "commonTerms" );

    Meteor.publish( "feelingsSmallSet", function( ) {
      var options = {
        fields : { "user.profile_image_url_https" : 1 },
        limit : 4
      };
      return feelings.find( { }, options );
    } );

    Meteor.publish( "feelings", function( words, lang ) {

      var list = "";
      _.each( words, function( word ) {
        var query = {};
        var modfiers = {};
        var increment = {};
        query[ word ] = { $exists : true } ;

        var cursor = termsCollection.find( query );
        if( cursor.count() == 0 ) {
          var term = {};
          term[ word ] = 1;
          termsCollection.insert( term );
        } else {
          var array = cursor.fetch();
          increment[ word ] = +1;
          modfiers[ "$inc" ] = increment;
          termsCollection.update( { _id : array[ 0 ]._id }, modfiers );
        }

        list += word + " ";
      } );

      var query = {
        $text : {
          $search : list,
          $language : "en"
        }
      };
      var options = {
        fields : {
          id_str : 1,
          text : 1,
          created_at : 1,
          "entities.media" : 1,
          "user.id_str" : 1,
          "user.screen_name" : 1,
          "user.profile_image_url_https" : 1,
          "retweeted_status.id_str" : 1
        }
      };
      return feelings.find( query, options );
    } );
  });
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var util = require('util');
var Base = require('base');
var File = require('vinyl');
var utils = require('./lib/utils');
var cursor = utils.ansi(process.stdout);

/**
 * Create an instance of Benchmarked with the given `options`.
 *
 * ```js
 * var benchmarks = new Benchmarked();
 * ```
 * @param {Object} `options`
 * @api public
 */

function Benchmarked(options) {
  if (!(this instanceof Benchmarked)) {
    return new Benchmarked(options);
  }
  Base.call(this, null, options);
  this.use(utils.option());
  this.use(utils.cwd());
  this.defaults(this);
}

/**
 * Inherit `Base`
 */

Base.extend(Benchmarked);

/**
 * Default settings
 */

Benchmarked.prototype.defaults = function(benchmarked) {
  this.fixtures = {
    files: [],
    cache: {},
    toFile: function(file) {
      var str = fs.readFileSync(file.path, 'utf8');
      file.content = utils.reader.file(file);
      file.title = util.format('(%d bytes)', str.length);
    }
  };

  this.code = {
    files: [],
    cache: {},
    toFile: function(file) {
      file.run = require(file.path);
    }
  };

  if (typeof this.options.format === 'function') {
    this.format = this.options.format;
  }
  if (this.options.fixtures) {
    this.addFixtures(this.options.fixtures);
  }
  if (this.options.code) {
    this.addCode(this.options.code);
  }
};

/**
 * Default formatter for benchmark.
 *
 * @param  {Benchmark} `benchmark` The Benchmark to produce a string from.
 */

Benchmarked.prototype.format = function(benchmark) {
  return '  ' + benchmark;
};

/**
 * Create a vinyl file object.
 *
 * @param  {String} `type` The type of file to create (`code` or `fixture`)
 * @param  {String} `filepath`
 */

Benchmarked.prototype.toFile = function(type, filepath, options) {
  var opts = utils.merge({}, this.options, options);
  var file = new File({path: path.resolve(this.cwd, filepath)});

  file.key = utils.setKey(file, opts);
  file.inspect = function() {
    return '<' + utils.toTitle(type) + ' ' + this.key + '"' + this.relative + '">';
  };

  var fn = opts.toFile || this[type].toFile;
  var res = fn.call(this, file);
  if (utils.isFile(res)) {
    file = res;
  }
  return file;
};

/**
 * Add fixtures to run benchmarks against.
 *
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 */

Benchmarked.prototype.filter = function(type, patterns, options) {
  if (typeof patterns === 'undefined') {
    patterns = '*';
  }

  if (Array.isArray(patterns)) {
    patterns = '{' + patterns.join(',') + '}';
  }

  var isMatch = utils.mm.matcher(patterns, options);
  var results = [];
  var self = this;

  this.fixtures.files.forEach(function(file) {
    if (isMatch(file.basename)) {
      file.suite = self.addSuite(file);
      results.push(file);
    }
  });
  return results;
};

/**
 * Add fixtures to run benchmarks against.
 *
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 */

Benchmarked.prototype.match = function(type, patterns, options) {
  return utils.mm.matchKeys(this[type].files, patterns, options);
};

/**
 * Add fixtures to run benchmarks against.
 *
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 */

Benchmarked.prototype.addFile = function(type, file, options) {
  if (utils.isGlob(file) || Array.isArray(file)) {
    return this.addFiles.apply(this, arguments);
  }

  type = utils.type(type);
  if (typeof file === 'string') {
    file = this.toFile(type, file, options);
  }

  if (!utils.isFile(file)) {
    throw new Error('expected "file" to be a vinyl file object');
  }

  this[type].cache[file.path] = file;
  this[type].files.push(file);
  return this;
};

/**
 * Add fixtures to run benchmarks against.
 *
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 */

Benchmarked.prototype.addFiles = function(type, files, options) {
  var opts = utils.merge({cwd: this.cwd}, this.options, options);
  switch (utils.typeOf(files)) {
    case 'string':
      if (utils.isGlob(files)) {
        this.addFiles(type, utils.glob.sync(files, opts), options);
      } else {
        this.addFile(type, files, options);
      }
      break;
    case 'array':
      this.addFilesArray(type, files, options);
      break;
    case 'object':
      this.addFilesObject(type, files, options);
      break;
    default: {
      throw new TypeError('cannot load files: ', util.inspect(arguments));
    }
  }
  return this;
};

/**
 * Add an array of `files` to the files array and cache for the given `type`.
 *
 * @param  {String} `type` Either `code` or `fixtures`
 * @param  {Array} Files to add
 * @param  {Object}
 */

Benchmarked.prototype.addFilesArray = function(type, files, options) {
  for (var i = 0; i < files.length; i++) {
    this.addFile(type, files[i], options);
  }
  return this;
};

/**
 * Add a fixture to run benchmarks against.
 *
 * @param  {String|Function} `fixture` Filepath or function
 */

Benchmarked.prototype.addFilesObject = function(type, files, options) {
  for (var key in files) {
    if (files.hasOwnProperty(key)) {
      this.addFile(type, files[key], options);
    }
  }
  return this;
};

/**
 * Add a fixture to run benchmarks against.
 *
 * @param  {String|Function} `fixture` Filepath or function
 */

Benchmarked.prototype.addFixture = function(file, options) {
  this.addFile('fixtures', file, options);
  return this;
};

/**
 * Add fixtures to run benchmarks against.
 *
 * ```js
 * benchmarks.addFixtures('fixtures/*.txt');
 * ```
 * @param  {String|Array} `patterns` Filepaths or glob patterns.
 * @param  {Options} `options`
 * @api public
 */

Benchmarked.prototype.addFixtures = function(files, options) {
  this.addFiles('fixtures', files, options);
  return this;
};

/**
 * Specify the functions to be benchmarked.
 *
 * ```js
 * benchmarks.addCode('fixtures/*.txt');
 * ```
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 * @api public
 */

Benchmarked.prototype.addCode = function(file, options) {
  this.addFile('code', file, options);
  return this;
};

/**
 * Add benchmark suite to the given `fixture` file.
 *
 * @param {Object} `fixture` vinyl file object
 * @api public
 */

Benchmarked.prototype.addSuite = function(fixture) {
  var colors = utils.colors;
  var files = this.code.files;
  var opts = this.options;

  if (opts.dryRun === true) {
    files.forEach(function(file) {
      console.log(file.run(fixture.content));
    });
  }

  var suite = new utils.Benchmark.Suite(fixture.title, {
    name: fixture.key,
    onStart: function onStart() {
      console.log(colors.cyan('\n# %s %s'), fixture.relative, fixture.title);
    },
    onComplete: function() {
      cursor.write('\n');
    }
  });

  files.forEach(function(file) {
    suite.add(file.key, {
      onCycle: function onCycle(event) {
        cursor.horizontalAbsolute();
        cursor.eraseLine();
        cursor.write(this.format(event.target));
      },
      fn: function() {
        var args = fixture.content;
        if (Array.isArray(args[0])) {
          file.run.apply(null, args);
        } else {
          file.run(args);
        }
        return;
      },
      onComplete: function() {
        cursor.write('\n');
      }
    });
  });

  if (files.length <= 1) {
    return suite;
  }

  suite.on('complete', function() {
    console.log('  fastest is', colors.green(this.filter('fastest').map('name')));
  });

  return suite;
};

/**
 * Run the benchmarks.
 *
 * ```js
 * benchmarks.run();
 * ```
 * @param  {Object} `options`
 * @param  {Function} `cb`
 * @param  {Object} `thisArg`
 * @api public
 */

Benchmarked.prototype.run = function(patterns, options) {
  var fixtures = this.filter('fixtures', patterns, options);

  if (fixtures.length > 0) {
    console.log('Benchmarking: (%d of %d)', fixtures.length, this.fixtures.files.length);
    fixtures.forEach(function(file) {
      console.log(' · %s', file.key);
    });
  } else {
    console.log('No matches for patterns: %s', util.inspect(patterns));
  }

  fixtures.forEach(function(file) {
    file.suite.run();
  });
};

Benchmarked.prototype.dryRun = function(pattern, options, fn) {
  if (typeof options === 'function') {
    fn = options;
    options = {};
  }

  if (typeof pattern === 'function') {
    fn = pattern;
    options = {};
    pattern = '**/*';
  }

  if (typeof fn !== 'function') {
    throw new Error('Expected fn to be a function');
  }

  var fixtures = this.filter('fixtures', pattern, options);
  var code = this.code;

  if (fixtures.length > 0) {
    console.log('Dry run for (%d of %d) fixtures:', fixtures.length, this.fixtures.files.length);
    fixtures.forEach(function(file) {
      console.log(' · %s', file.key);
    });
  } else {
    console.log('No matches for pattern: %s', util.inspect(pattern));
  }

  console.log();
  code.files.forEach(function(file) {
    fixtures.forEach(function(fixture) {
      fn(file, fixture);
    });
  });
};

/**
 * Expose `Benchmarked`
 */

module.exports = Benchmarked;
<commit_msg>fix this.format inside inner function<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var util = require('util');
var Base = require('base');
var File = require('vinyl');
var utils = require('./lib/utils');
var cursor = utils.ansi(process.stdout);

/**
 * Create an instance of Benchmarked with the given `options`.
 *
 * ```js
 * var benchmarks = new Benchmarked();
 * ```
 * @param {Object} `options`
 * @api public
 */

function Benchmarked(options) {
  if (!(this instanceof Benchmarked)) {
    return new Benchmarked(options);
  }
  Base.call(this, null, options);
  this.use(utils.option());
  this.use(utils.cwd());
  this.defaults(this);
}

/**
 * Inherit `Base`
 */

Base.extend(Benchmarked);

/**
 * Default settings
 */

Benchmarked.prototype.defaults = function(benchmarked) {
  this.fixtures = {
    files: [],
    cache: {},
    toFile: function(file) {
      var str = fs.readFileSync(file.path, 'utf8');
      file.content = utils.reader.file(file);
      file.title = util.format('(%d bytes)', str.length);
    }
  };

  this.code = {
    files: [],
    cache: {},
    toFile: function(file) {
      file.run = require(file.path);
    }
  };

  if (typeof this.options.format === 'function') {
    this.format = this.options.format;
  }
  if (this.options.fixtures) {
    this.addFixtures(this.options.fixtures);
  }
  if (this.options.code) {
    this.addCode(this.options.code);
  }
};

/**
 * Default formatter for benchmark.
 *
 * @param  {Benchmark} `benchmark` The Benchmark to produce a string from.
 */

Benchmarked.prototype.format = function(benchmark) {
  return '  ' + benchmark;
};

/**
 * Create a vinyl file object.
 *
 * @param  {String} `type` The type of file to create (`code` or `fixture`)
 * @param  {String} `filepath`
 */

Benchmarked.prototype.toFile = function(type, filepath, options) {
  var opts = utils.merge({}, this.options, options);
  var file = new File({path: path.resolve(this.cwd, filepath)});

  file.key = utils.setKey(file, opts);
  file.inspect = function() {
    return '<' + utils.toTitle(type) + ' ' + this.key + '"' + this.relative + '">';
  };

  var fn = opts.toFile || this[type].toFile;
  var res = fn.call(this, file);
  if (utils.isFile(res)) {
    file = res;
  }
  return file;
};

/**
 * Add fixtures to run benchmarks against.
 *
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 */

Benchmarked.prototype.filter = function(type, patterns, options) {
  if (typeof patterns === 'undefined') {
    patterns = '*';
  }

  if (Array.isArray(patterns)) {
    patterns = '{' + patterns.join(',') + '}';
  }

  var isMatch = utils.mm.matcher(patterns, options);
  var results = [];
  var self = this;

  this.fixtures.files.forEach(function(file) {
    if (isMatch(file.basename)) {
      file.suite = self.addSuite(file);
      results.push(file);
    }
  });
  return results;
};

/**
 * Add fixtures to run benchmarks against.
 *
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 */

Benchmarked.prototype.match = function(type, patterns, options) {
  return utils.mm.matchKeys(this[type].files, patterns, options);
};

/**
 * Add fixtures to run benchmarks against.
 *
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 */

Benchmarked.prototype.addFile = function(type, file, options) {
  if (utils.isGlob(file) || Array.isArray(file)) {
    return this.addFiles.apply(this, arguments);
  }

  type = utils.type(type);
  if (typeof file === 'string') {
    file = this.toFile(type, file, options);
  }

  if (!utils.isFile(file)) {
    throw new Error('expected "file" to be a vinyl file object');
  }

  this[type].cache[file.path] = file;
  this[type].files.push(file);
  return this;
};

/**
 * Add fixtures to run benchmarks against.
 *
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 */

Benchmarked.prototype.addFiles = function(type, files, options) {
  var opts = utils.merge({cwd: this.cwd}, this.options, options);
  switch (utils.typeOf(files)) {
    case 'string':
      if (utils.isGlob(files)) {
        this.addFiles(type, utils.glob.sync(files, opts), options);
      } else {
        this.addFile(type, files, options);
      }
      break;
    case 'array':
      this.addFilesArray(type, files, options);
      break;
    case 'object':
      this.addFilesObject(type, files, options);
      break;
    default: {
      throw new TypeError('cannot load files: ', util.inspect(arguments));
    }
  }
  return this;
};

/**
 * Add an array of `files` to the files array and cache for the given `type`.
 *
 * @param  {String} `type` Either `code` or `fixtures`
 * @param  {Array} Files to add
 * @param  {Object}
 */

Benchmarked.prototype.addFilesArray = function(type, files, options) {
  for (var i = 0; i < files.length; i++) {
    this.addFile(type, files[i], options);
  }
  return this;
};

/**
 * Add a fixture to run benchmarks against.
 *
 * @param  {String|Function} `fixture` Filepath or function
 */

Benchmarked.prototype.addFilesObject = function(type, files, options) {
  for (var key in files) {
    if (files.hasOwnProperty(key)) {
      this.addFile(type, files[key], options);
    }
  }
  return this;
};

/**
 * Add a fixture to run benchmarks against.
 *
 * @param  {String|Function} `fixture` Filepath or function
 */

Benchmarked.prototype.addFixture = function(file, options) {
  this.addFile('fixtures', file, options);
  return this;
};

/**
 * Add fixtures to run benchmarks against.
 *
 * ```js
 * benchmarks.addFixtures('fixtures/*.txt');
 * ```
 * @param  {String|Array} `patterns` Filepaths or glob patterns.
 * @param  {Options} `options`
 * @api public
 */

Benchmarked.prototype.addFixtures = function(files, options) {
  this.addFiles('fixtures', files, options);
  return this;
};

/**
 * Specify the functions to be benchmarked.
 *
 * ```js
 * benchmarks.addCode('fixtures/*.txt');
 * ```
 * @param  {String|Array} `patterns` Filepath(s) or glob patterns.
 * @param  {Options} `options`
 * @api public
 */

Benchmarked.prototype.addCode = function(file, options) {
  this.addFile('code', file, options);
  return this;
};

/**
 * Add benchmark suite to the given `fixture` file.
 *
 * @param {Object} `fixture` vinyl file object
 * @api public
 */

Benchmarked.prototype.addSuite = function(fixture) {
  var colors = utils.colors;
  var files = this.code.files;
  var opts = this.options;
  var format = this.format;

  if (opts.dryRun === true) {
    files.forEach(function(file) {
      console.log(file.run(fixture.content));
    });
  }

  var suite = new utils.Benchmark.Suite(fixture.title, {
    name: fixture.key,
    onStart: function onStart() {
      console.log(colors.cyan('\n# %s %s'), fixture.relative, fixture.title);
    },
    onComplete: function() {
      cursor.write('\n');
    }
  });

  files.forEach(function(file) {
    suite.add(file.key, {
      onCycle: function onCycle(event) {
        cursor.horizontalAbsolute();
        cursor.eraseLine();
        cursor.write(format(event.target));
      },
      fn: function() {
        var args = fixture.content;
        if (Array.isArray(args[0])) {
          file.run.apply(null, args);
        } else {
          file.run(args);
        }
        return;
      },
      onComplete: function() {
        cursor.write('\n');
      }
    });
  });

  if (files.length <= 1) {
    return suite;
  }

  suite.on('complete', function() {
    console.log('  fastest is', colors.green(this.filter('fastest').map('name')));
  });

  return suite;
};

/**
 * Run the benchmarks.
 *
 * ```js
 * benchmarks.run();
 * ```
 * @param  {Object} `options`
 * @param  {Function} `cb`
 * @param  {Object} `thisArg`
 * @api public
 */

Benchmarked.prototype.run = function(patterns, options) {
  var fixtures = this.filter('fixtures', patterns, options);

  if (fixtures.length > 0) {
    console.log('Benchmarking: (%d of %d)', fixtures.length, this.fixtures.files.length);
    fixtures.forEach(function(file) {
      console.log(' · %s', file.key);
    });
  } else {
    console.log('No matches for patterns: %s', util.inspect(patterns));
  }

  fixtures.forEach(function(file) {
    file.suite.run();
  });
};

Benchmarked.prototype.dryRun = function(pattern, options, fn) {
  if (typeof options === 'function') {
    fn = options;
    options = {};
  }

  if (typeof pattern === 'function') {
    fn = pattern;
    options = {};
    pattern = '**/*';
  }

  if (typeof fn !== 'function') {
    throw new Error('Expected fn to be a function');
  }

  var fixtures = this.filter('fixtures', pattern, options);
  var code = this.code;

  if (fixtures.length > 0) {
    console.log('Dry run for (%d of %d) fixtures:', fixtures.length, this.fixtures.files.length);
    fixtures.forEach(function(file) {
      console.log(' · %s', file.key);
    });
  } else {
    console.log('No matches for pattern: %s', util.inspect(pattern));
  }

  console.log();
  code.files.forEach(function(file) {
    fixtures.forEach(function(fixture) {
      fn(file, fixture);
    });
  });
};

/**
 * Expose `Benchmarked`
 */

module.exports = Benchmarked;
<|endoftext|>


<commit_before>var request = require("request")
var twitterCreds = require("./twitterCreds.js")
var Twitter = require("twitter")
var CronJob = require('cron').CronJob;

new CronJob('0 * * * * ', function() {
    console.log("I'm fetching")
    fetchTopStories()
}, null, true, 'America/Chicago');

var client = new Twitter({
    consumer_key: twitterCreds.consumer_key,
    consumer_secret: twitterCreds.consumer_secret,
    access_token_key: twitterCreds.access_token_key,
    access_token_secret: twitterCreds.access_token_secret
});

function tweet(tweetActual) {
    console.log("here I am I am RIGHT here")
    client.post('statuses/update', {status: tweetActual},  function(error, tweet, response){
        console.log(error)
        console.log("I just Tweeted");
    });
}

function fetchTopStories() {
    request({
        url: "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty",
    json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            compileTop30Stories(body)
        } else {
            console.log(error)
        }
    })
}

function compileTop30Stories(groupOfStories) {
    for (i = 0; i < 30; i++) {
        fetchStory(groupOfStories[i])
    }
}

function fetchStory(storyID) {
    request({
        url: "https://hacker-news.firebaseio.com/v0/item/" + storyID + ".json?print=pretty",
    json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            vimChecker(body)
        } else {
            console.log(error)
        }

    })
}

function vimChecker(storyActual) {
    if (storyActual.title.match(/vim/gi)) {
    // if (storyActual.title.match(/Jerk/gi)) {
        var wholeTweet = storyActual.title + " " + storyActual.url
        tweet(wholeTweet)
    }
}

fetchTopStories()
// app.listen(3000);
<commit_msg>logs date and time<commit_after>var request = require("request")
var twitterCreds = require("./twitterCreds.js")
var Twitter = require("twitter")
var CronJob = require('cron').CronJob;

new CronJob('0 * * * * ', function() {
    var currentdate = new Date();
    var datetime = "HN_Vimmy_Bot running Scan: " + currentdate.getDate() + "/"
                    + (currentdate.getMonth()+1)  + "/"
                    + currentdate.getFullYear() + " @ "
                    + currentdate.getHours() + ":"
                    + currentdate.getMinutes() + ":"
                    + currentdate.getSeconds();

    consol.log(datetime)
    fetchTopStories()
}, null, true, 'America/Chicago');

var client = new Twitter({
    consumer_key: twitterCreds.consumer_key,
    consumer_secret: twitterCreds.consumer_secret,
    access_token_key: twitterCreds.access_token_key,
    access_token_secret: twitterCreds.access_token_secret
});

function tweet(tweetActual) {
    client.post('statuses/update', {status: tweetActual},  function(error, tweet, response){
        console.log(error)
        console.log("I just Tweeted");
    });
}

function fetchTopStories() {
    request({
        url: "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty",
    json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            compileTop30Stories(body)
        } else {
            console.log(error)
        }
    })
}

function compileTop30Stories(groupOfStories) {
    for (i = 0; i < 30; i++) {
        fetchStory(groupOfStories[i])
    }
}

function fetchStory(storyID) {
    request({
        url: "https://hacker-news.firebaseio.com/v0/item/" + storyID + ".json?print=pretty",
    json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            vimChecker(body)
        } else {
            console.log(error)
        }

    })
}

function vimChecker(storyActual) {
    if (storyActual.title.match(/vim/gi)) {
    // if (storyActual.title.match(/Jerk/gi)) {
        var wholeTweet = storyActual.title + " " + storyActual.url
        tweet(wholeTweet)
    }
}

fetchTopStories()
// app.listen(3000);
<|endoftext|>


<commit_before>var router = require('ramrod')(),
  form = require('formidable').IncomingForm(),
  http = require('http'),
  couchdb = require('felix-couchdb'),
  client = couchdb.createClient(),
  db = client.db('redwah'),
  web = require('./lib/web.js'),
  redwah = {
    version: "0.0.1",
    description: "dont trust your gut: make decisions with numbers!"
  },
  headers = {};

headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Headers"] = "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept"

// Route handler

router.on('putlist|put', function (req, res) {
  form.parse(req, function (err, params) {
    db.getDoc(params.id, function (err, previousDoc) {
      if (err) { return web.sendError(res, 404, headers); }
      db.saveDoc(params, function (err, doc) {
        if (err) { return web.sendError(res, 500, headers); }
        res.writeHead(200, headers);
        res.end(JSON.stringify(doc));
      });
    });
  });
});

router.on('dellist|del', function (req, res, params) {
  db.getDoc(params.id, function (err, doc) {
    if (err) { return web.sendError(res, 404, headers); }
    db.removeDoc(doc.id, doc.rev, function (err) {
      if (err) { return web.sendError(res, 404, headers); }
      res.writeHead(200, headers);
      res.end(JSON.stringify({ "ok": true }));
    });
  });
});

router.on('postlist|post', function (req, res) {
  form.parse(req, function (err, params) {
    if (err) { return web.sendError(res, 500, headers); }
    var listDocument = {
      "name": params.name,
      "items": [],
      "qualities": [],
      "createdAt": new Date().getTime(),
      "lastUpdated": new Date().getTime()
    };
    db.saveDoc(listDocument, function (err, doc) {
      res.writeHead(201, headers);
      res.end(JSON.stringify(doc));
    });
  });
});

router.on('getlist|get', function (req, res, params) {
  res.writeHead(200);
  db.getDoc(params.id, function (err, doc) {
    if (err) { return web.sendError(res, 404, headers); }
    res.writeHead(200, headers);
    res.end(JSON.stringify(doc));
  });
});

router.on('*', function (req, res) {
  res.writeHead(200, headers);
  res.end(JSON.stringify(redwah));
});

// Enumerate routes

['post', 'get', 'put', 'del'].forEach(function (method) {
  router[method]('list', method + 'list');
});

db.exists(function (err, dbExists) {
  if (!dbExists) {
    console.log('db does not exist');
    db.create(function (err) {
      if (err) { throw new Error (JSON.stringify(err)); }
      console.log('redwah db created');
    });
  }
});

http.createServer(function (req, res) {
  if (req.method === 'OPTIONS') {
    res.writeHead(204, headers);
    res.end();
  } else {
    router.dispatch(req, res);
  }
}).listen(3000);
<commit_msg>fix syntax<commit_after>var router = require('ramrod')(),
  form = require('formidable').IncomingForm(),
  http = require('http'),
  couchdb = require('felix-couchdb'),
  client = couchdb.createClient(),
  db = client.db('redwah'),
  web = require('./lib/web.js'),
  redwah = {
    version: "0.0.1",
    description: "dont trust your gut: make decisions with numbers!"
  },
  headers = {};

headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Headers"] = "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept"

// Route handler

router.on('putlist|put', function (req, res) {
  form.parse(req, function (err, params) {
    db.getDoc(params.id, function (err, previousDoc) {
      if (err) { return web.sendError(res, 404, headers); }
      db.saveDoc({
        "_id": params.id,
        "_rev": params.rev,
        "qualities": params.qualities,
        "items": params.items,
        "name": params.name,
        "lastModified": new Date().getTime()
      }, function (err, doc) {
        if (err) { return web.sendError(res, 500, headers); }
        res.writeHead(200, headers);
        res.end(JSON.stringify(doc));
      });
    });
  });
});

router.on('dellist|del', function (req, res, params) {
  db.getDoc(params.id, function (err, doc) {
    if (err) { return web.sendError(res, 404, headers); }
    db.removeDoc(doc.id, doc.rev, function (err) {
      if (err) { return web.sendError(res, 404, headers); }
      res.writeHead(200, headers);
      res.end(JSON.stringify({ "ok": true }));
    });
  });
});

router.on('postlist|post', function (req, res) {
  form.parse(req, function (err, params) {
    if (err) { return web.sendError(res, 500, headers); }
    var listDocument = {
      "name": params.name,
      "items": [],
      "qualities": [],
      "createdAt": new Date().getTime(),
      "lastUpdated": new Date().getTime()
    };
    db.saveDoc(listDocument, function (err, doc) {
      res.writeHead(201, headers);
      res.end(JSON.stringify(doc));
    });
  });
});

router.on('getlist|get', function (req, res, params) {
  res.writeHead(200);
  db.getDoc(params.id, function (err, doc) {
    if (err) { return web.sendError(res, 404, headers); }
    res.writeHead(200, headers);
    res.end(JSON.stringify(doc));
  });
});

router.on('*', function (req, res) {
  res.writeHead(200, headers);
  res.end(JSON.stringify(redwah));
});

// Enumerate routes

['post', 'get', 'put', 'del'].forEach(function (method) {
  router[method]('list', method + 'list');
});

db.exists(function (err, dbExists) {
  if (!dbExists) {
    console.log('db does not exist');
    db.create(function (err) {
      if (err) { throw new Error (JSON.stringify(err)); }
      console.log('redwah db created');
    });
  }
});

http.createServer(function (req, res) {
  if (req.method === 'OPTIONS') {
    res.writeHead(204, headers);
    res.end();
  } else {
    router.dispatch(req, res);
  }
}).listen(3000);
<|endoftext|>


<commit_before>'use strict';

var argv = require('minimist')(process.argv.slice(2));
var stdin = require('get-stdin');
var input = argv._[0];

var taketalk = {
  init: function () {},
  printHelp: function () { this._doWhatItIs('help'); },
  printVersion: function () { this._doWhatItIs('version'); },
  _doWhatItIs: function (key) {
    var thing = this[key];
    switch (typeof thing) {
      case 'string': console.log(thing); break;
      case 'function': thing(); break;
    }
  }
};

module.exports = function (obj) {
  if ({}.toString.call(obj).indexOf('Object') === -1) {
    throw new Error('Expected an object.');
  }

  for (var prop in obj) {
    taketalk[prop] = obj[prop];
  }

  if (argv.help || argv.h) return taketalk.printHelp();
  if (argv.version || argv.v) return taketalk.printVersion();

  if (process.stdin.isTTY) {
    if (!input) {
      taketalk.printHelp();
      return;
    }

    taketalk.init(input, argv);
  } else {
    stdin(function (data) {
      taketalk.init(data, argv);
    });
  }

  return taketalk;
};
<commit_msg>dont require options to be passed.<commit_after>'use strict';

var argv = require('minimist')(process.argv.slice(2));
var stdin = require('get-stdin');
var input = argv._[0];

var taketalk = {
  init: function () {},
  printHelp: function () { this._doWhatItIs('help'); },
  printVersion: function () { this._doWhatItIs('version'); },
  _doWhatItIs: function (key) {
    var thing = this[key];
    switch (typeof thing) {
      case 'string': console.log(thing); break;
      case 'function': thing(); break;
    }
  }
};

module.exports = function (obj) {
  if ({}.toString.call(obj).indexOf('Object') === -1) {
    throw new Error('Expected an object.');
  }

  for (var prop in obj) {
    taketalk[prop] = obj[prop];
  }

  if (argv.help || argv.h) return taketalk.printHelp();
  if (argv.version || argv.v) return taketalk.printVersion();

  if (process.stdin.isTTY) {
    taketalk.init.call(taketalk, input, argv);
  } else {
    stdin(function (data) {
      taketalk.init.call(taketalk, data, argv);
    });
  }

  return taketalk;
};
<|endoftext|>


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

'use strict';

var exec = require('child_process').exec,
    async = require('async'),
    concat = require('concat-stream');

var isOld = /^v/;

/**
 * Lists all git tags for the current repository
 */
function listTags(done) {
  exec('git tag', function (err, stdout) {
    if (err) { return done(err); }
    var tags = stdout.split('\n').filter(Boolean);
    var types = { past: {}, current: {} };

    tags.forEach(function (tag) {
      var type = isOld.test(tag) ? 'past' : 'current';
      types[type][tag] = true;
    });

    done(null, types);
  });
}

/**
 * Generates all git commands based on the tags
 */
function allCommands(tags, done) {
  var local = { create: [], remove: [] };
  var remote = { create: [], remove: [] };

  Object.keys(tags.past).forEach(function (tag) {
    var current = tag.replace(isOld, '');

    if (tags.current[current]) {
      console.log('%s already exists');
    } else {
      local.create.push(['git', 'tag', current, tag].join(' '));
    }

    local.remove.push(['git', 'tag', '-d', tag].join(' '));
    remote.remove.push(['git', 'push', 'origin', ':refs/tags/' + tag].join(' '));
  });

  done(null, {
    local: local,
    remote: remote
  });
}

/**
 * Confirms that the following commands need be run
 */
function confirmAndRun(commands, done) {
  console.log(commands.local.create);
  console.log(commands.local.remove);
  console.log(commands.remote.create);
  console.log(commands.remote.remove);
  done();
}

/**
 * Runs all the `series` of commands.
 */
function runCommands(series, done) {
  async.forEachSeries(series, function execOne(cmd, next) {
    console.log('Executing %s', cmd);
    if (!process.env.DRY) {

    }

    next();
  }, done);
}

async.waterfall([
  listTags,
  allCommands,
  confirmAndRun
], function () {
  console.log(arguments);
});
<commit_msg>[api] Finalize simple API.<commit_after>#!/usr/bin/env node

'use strict';

var exec = require('child_process').exec,
    async = require('async');

var isOld = /^v/;

/**
 * Lists all git tags for the current repository
 */
function listTags(done) {
  exec('git tag', function (err, stdout) {
    if (err) { return done(err); }
    var tags = stdout.split('\n').filter(Boolean);
    var types = { past: {}, current: {} };

    tags.forEach(function (tag) {
      var type = isOld.test(tag) ? 'past' : 'current';
      types[type][tag] = true;
    });

    done(null, types);
  });
}

/**
 * Generates all git commands based on the tags
 */
function allCommands(tags, done) {
  var local = { create: [], remove: [] };
  var remote = { create: [], remove: [] };

  Object.keys(tags.past).forEach(function (tag) {
    var current = tag.replace(isOld, '');

    if (tags.current[current]) {
      console.log('%s already exists for %s', current, tag);
    } else {
      local.create.push(['git', 'tag', current, tag].join(' '));
    }

    local.remove.push(['git', 'tag', '-d', tag].join(' '));
    remote.remove.push(['git', 'push', 'origin', ':refs/tags/' + tag].join(' '));
  });

  done(null, {
    local: local,
    remote: remote
  });
}

/**
 * Confirms that the following commands need be run
 */
function confirmAndRun(commands, done) {
  var hasCommands = !!(
    commands.local.create.length,
    commands.local.remove.length,
    commands.remote.remove.length
  );

  async.series([
    async.apply(runCommands, '## Renaming local tags', commands.local.create),
    async.apply(runCommands, '\n## Removing old tags', commands.local.remove),
    async.apply(runCommands, '\n## Removing remote tags', commands.remote.remove),
    function (next) {
      if (!hasCommands) {
        console.log('git tags are already semver@2.0.0 compliant');
        return done(null, true);
      }

      console.log('\n## Adding new remote tags');
      var cmd = 'git push --tags';
      console.log('Executing %s\n', cmd);
      if (!process.env.DRY) {
        return exec(cmd, next);
      }

      next();
    }
  ], done);
}

/**
 * Runs all the `series` of commands.
 */
function runCommands(msg, series, done) {
  console.log(msg);
  async.forEachSeries(series, function execOne(cmd, next) {
    console.log('%s', cmd);
    if (!process.env.DRY) {
      return exec(cmd, next);
    }

    next();
  }, done);
}

async.waterfall([
  listTags,
  allCommands,
  confirmAndRun
], function (err, noop) {
  if (err) {
    throw err;
  } else if (process.env.DRY) {
    console.log('DRY run completed. No git commands run.');
  } else if (!noop) {
    console.log('Local and origin git tags are now semver@2.0.0 compliant.');
  }
});
<|endoftext|>


<commit_before>module.exports = createLayout;
module.exports.simulator = require('ngraph.physics.simulator');

/**
 * Creates force based layout for a given graph.
 * @param {ngraph.graph} graph which needs to be laid out
 * @param {object} physicsSettings if you need custom settings
 * for physics simulator you can pass your own settings here. If it's not passed
 * a default one will be created.
 */
function createLayout(graph, physicsSettings) {
  if (!graph) {
    throw new Error('Graph structure cannot be undefined');
  }

  var createSimulator = require('ngraph.physics.simulator');
  var physicsSimulator = createSimulator(physicsSettings);

  var nodeBodies = typeof Object.create === 'function' ? Object.create(null) : {};
  var springs = {};

  var springTransform = physicsSimulator.settings.springTransform || noop;

  // Initialize physical objects according to what we have in the graph:
  initPhysics();
  listenToGraphEvents();

  var api = {
    /**
     * Performs one step of iterative layout algorithm
     */
    step: function() {
      return physicsSimulator.step();
    },

    /**
     * For a given `nodeId` returns position
     */
    getNodePosition: function (nodeId) {
      return getInitializedBody(nodeId).pos;
    },

    /**
     * Sets position of a node to a given coordinates
     * @param {string} nodeId node identifier
     * @param {number} x position of a node
     * @param {number} y position of a node
     * @param {number=} z position of node (only if applicable to body)
     */
    setNodePosition: function (nodeId) {
      var body = getInitializedBody(nodeId);
      body.setPosition.apply(body, Array.prototype.slice.call(arguments, 1));
    },

    /**
     * @returns {Object} Link position by link id
     * @returns {Object.from} {x, y} coordinates of link start
     * @returns {Object.to} {x, y} coordinates of link end
     */
    getLinkPosition: function (linkId) {
      var spring = springs[linkId];
      if (spring) {
        return {
          from: spring.from.pos,
          to: spring.to.pos
        };
      }
    },

    /**
     * @returns {Object} area required to fit in the graph. Object contains
     * `x1`, `y1` - top left coordinates
     * `x2`, `y2` - bottom right coordinates
     */
    getGraphRect: function () {
      return physicsSimulator.getBBox();
    },

    /*
     * Requests layout algorithm to pin/unpin node to its current position
     * Pinned nodes should not be affected by layout algorithm and always
     * remain at their position
     */
    pinNode: function (node, isPinned) {
      var body = getInitializedBody(node.id);
       body.isPinned = !!isPinned;
    },

    /**
     * Checks whether given graph's node is currently pinned
     */
    isNodePinned: function (node) {
      return getInitializedBody(node.id).isPinned;
    },

    /**
     * Request to release all resources
     */
    dispose: function() {
      graph.off('changed', onGraphChanged);
    },

    /**
     * Gets physical body for a given node id. If node is not found undefined
     * value is returned.
     */
    getBody: getBody,

    /**
     * Gets spring for a given edge.
     *
     * @param {string} linkId link identifer. If two arguments are passed then
     * this argument is treated as formNodeId
     * @param {string=} toId when defined this parameter denotes head of the link
     * and first argument is trated as tail of the link (fromId)
     */
    getSpring: getSpring,

    /**
     * [Read only] Gets current physics simulator
     */
    simulator: physicsSimulator
  };

  return api;

  function getSpring(fromId, toId) {
    var linkId;
    if (toId === undefined) {
      if (typeof fromId === 'string') {
        // assume fromId as a linkId:
        linkId = fromId;
      } else {
        // assume fromId to be a link object:
        linkId = fromId.id;
      }
    } else {
      // toId is defined, should grab link:
      var link = graph.hasLink(fromId, toId);
      if (!link) return;
      linkId = link.id;
    }

    return springs[linkId];
  }

  function getBody(nodeId) {
    return nodeBodies[nodeId];
  }

  function listenToGraphEvents() {
    graph.on('changed', onGraphChanged);
  }

  function onGraphChanged(changes) {
    for (var i = 0; i < changes.length; ++i) {
      var change = changes[i];
      if (change.changeType === 'add') {
        if (change.node) {
          initBody(change.node.id);
        }
        if (change.link) {
          initLink(change.link);
        }
      } else if (change.changeType === 'remove') {
        if (change.node) {
          releaseNode(change.node);
        }
        if (change.link) {
          releaseLink(change.link);
        }
      }
    }
  }

  function initPhysics() {
    graph.forEachNode(function (node) {
      initBody(node.id);
    });
    graph.forEachLink(initLink);
  }

  function initBody(nodeId) {
    var body = nodeBodies[nodeId];
    if (!body) {
      var node = graph.getNode(nodeId);
      if (!node) {
        throw new Error('initBody() was called with unknown node id');
      }

      var pos = node.position;
      if (!pos) {
        var neighbors = getNeighborBodies(node);
        pos = physicsSimulator.getBestNewBodyPosition(neighbors);
      }

      body = physicsSimulator.addBodyAt(pos);

      nodeBodies[nodeId] = body;
      updateBodyMass(nodeId);

      if (isNodeOriginallyPinned(node)) {
        body.isPinned = true;
      }
    }
  }

  function releaseNode(node) {
    var nodeId = node.id;
    var body = nodeBodies[nodeId];
    if (body) {
      nodeBodies[nodeId] = null;
      delete nodeBodies[nodeId];

      physicsSimulator.removeBody(body);
    }
  }

  function initLink(link) {
    updateBodyMass(link.fromId);
    updateBodyMass(link.toId);

    var fromBody = nodeBodies[link.fromId],
        toBody  = nodeBodies[link.toId],
        spring = physicsSimulator.addSpring(fromBody, toBody, link.length);

    springTransform(link, spring);

    springs[link.id] = spring;
  }

  function releaseLink(link) {
    var spring = springs[link.id];
    if (spring) {
      var from = graph.getNode(link.fromId),
          to = graph.getNode(link.toId);

      if (from) updateBodyMass(from.id);
      if (to) updateBodyMass(to.id);

      delete springs[link.id];

      physicsSimulator.removeSpring(spring);
    }
  }

  function getNeighborBodies(node) {
    // TODO: Could probably be done better on memory
    var neighbors = [];
    if (!node.links) {
      return neighbors;
    }
    var maxNeighbors = Math.min(node.links.length, 2);
    for (var i = 0; i < maxNeighbors; ++i) {
      var link = node.links[i];
      var otherBody = link.fromId !== node.id ? nodeBodies[link.fromId] : nodeBodies[link.toId];
      if (otherBody && otherBody.pos) {
        neighbors.push(otherBody);
      }
    }

    return neighbors;
  }

  function updateBodyMass(nodeId) {
    var body = nodeBodies[nodeId];
    body.mass = nodeMass(nodeId);
  }

  /**
   * Checks whether graph node has in its settings pinned attribute,
   * which means layout algorithm cannot move it. Node can be preconfigured
   * as pinned, if it has "isPinned" attribute, or when node.data has it.
   *
   * @param {Object} node a graph node to check
   * @return {Boolean} true if node should be treated as pinned; false otherwise.
   */
  function isNodeOriginallyPinned(node) {
    return (node && (node.isPinned || (node.data && node.data.isPinned)));
  }

  function getInitializedBody(nodeId) {
    var body = nodeBodies[nodeId];
    if (!body) {
      initBody(nodeId);
      body = nodeBodies[nodeId];
    }
    return body;
  }

  /**
   * Calculates mass of a body, which corresponds to node with given id.
   *
   * @param {String|Number} nodeId identifier of a node, for which body mass needs to be calculated
   * @returns {Number} recommended mass of the body;
   */
  function nodeMass(nodeId) {
    return 1 + graph.getLinks(nodeId).length / 3.0;
  }
}

function noop() { }
<commit_msg>Fix assumption about link existence.<commit_after>module.exports = createLayout;
module.exports.simulator = require('ngraph.physics.simulator');

/**
 * Creates force based layout for a given graph.
 * @param {ngraph.graph} graph which needs to be laid out
 * @param {object} physicsSettings if you need custom settings
 * for physics simulator you can pass your own settings here. If it's not passed
 * a default one will be created.
 */
function createLayout(graph, physicsSettings) {
  if (!graph) {
    throw new Error('Graph structure cannot be undefined');
  }

  var createSimulator = require('ngraph.physics.simulator');
  var physicsSimulator = createSimulator(physicsSettings);

  var nodeBodies = typeof Object.create === 'function' ? Object.create(null) : {};
  var springs = {};

  var springTransform = physicsSimulator.settings.springTransform || noop;

  // Initialize physical objects according to what we have in the graph:
  initPhysics();
  listenToGraphEvents();

  var api = {
    /**
     * Performs one step of iterative layout algorithm
     */
    step: function() {
      return physicsSimulator.step();
    },

    /**
     * For a given `nodeId` returns position
     */
    getNodePosition: function (nodeId) {
      return getInitializedBody(nodeId).pos;
    },

    /**
     * Sets position of a node to a given coordinates
     * @param {string} nodeId node identifier
     * @param {number} x position of a node
     * @param {number} y position of a node
     * @param {number=} z position of node (only if applicable to body)
     */
    setNodePosition: function (nodeId) {
      var body = getInitializedBody(nodeId);
      body.setPosition.apply(body, Array.prototype.slice.call(arguments, 1));
    },

    /**
     * @returns {Object} Link position by link id
     * @returns {Object.from} {x, y} coordinates of link start
     * @returns {Object.to} {x, y} coordinates of link end
     */
    getLinkPosition: function (linkId) {
      var spring = springs[linkId];
      if (spring) {
        return {
          from: spring.from.pos,
          to: spring.to.pos
        };
      }
    },

    /**
     * @returns {Object} area required to fit in the graph. Object contains
     * `x1`, `y1` - top left coordinates
     * `x2`, `y2` - bottom right coordinates
     */
    getGraphRect: function () {
      return physicsSimulator.getBBox();
    },

    /*
     * Requests layout algorithm to pin/unpin node to its current position
     * Pinned nodes should not be affected by layout algorithm and always
     * remain at their position
     */
    pinNode: function (node, isPinned) {
      var body = getInitializedBody(node.id);
       body.isPinned = !!isPinned;
    },

    /**
     * Checks whether given graph's node is currently pinned
     */
    isNodePinned: function (node) {
      return getInitializedBody(node.id).isPinned;
    },

    /**
     * Request to release all resources
     */
    dispose: function() {
      graph.off('changed', onGraphChanged);
    },

    /**
     * Gets physical body for a given node id. If node is not found undefined
     * value is returned.
     */
    getBody: getBody,

    /**
     * Gets spring for a given edge.
     *
     * @param {string} linkId link identifer. If two arguments are passed then
     * this argument is treated as formNodeId
     * @param {string=} toId when defined this parameter denotes head of the link
     * and first argument is trated as tail of the link (fromId)
     */
    getSpring: getSpring,

    /**
     * [Read only] Gets current physics simulator
     */
    simulator: physicsSimulator
  };

  return api;

  function getSpring(fromId, toId) {
    var linkId;
    if (toId === undefined) {
      if (typeof fromId === 'string') {
        // assume fromId as a linkId:
        linkId = fromId;
      } else {
        // assume fromId to be a link object:
        linkId = fromId.id;
      }
    } else {
      // toId is defined, should grab link:
      var link = graph.hasLink(fromId, toId);
      if (!link) return;
      linkId = link.id;
    }

    return springs[linkId];
  }

  function getBody(nodeId) {
    return nodeBodies[nodeId];
  }

  function listenToGraphEvents() {
    graph.on('changed', onGraphChanged);
  }

  function onGraphChanged(changes) {
    for (var i = 0; i < changes.length; ++i) {
      var change = changes[i];
      if (change.changeType === 'add') {
        if (change.node) {
          initBody(change.node.id);
        }
        if (change.link) {
          initLink(change.link);
        }
      } else if (change.changeType === 'remove') {
        if (change.node) {
          releaseNode(change.node);
        }
        if (change.link) {
          releaseLink(change.link);
        }
      }
    }
  }

  function initPhysics() {
    graph.forEachNode(function (node) {
      initBody(node.id);
    });
    graph.forEachLink(initLink);
  }

  function initBody(nodeId) {
    var body = nodeBodies[nodeId];
    if (!body) {
      var node = graph.getNode(nodeId);
      if (!node) {
        throw new Error('initBody() was called with unknown node id');
      }

      var pos = node.position;
      if (!pos) {
        var neighbors = getNeighborBodies(node);
        pos = physicsSimulator.getBestNewBodyPosition(neighbors);
      }

      body = physicsSimulator.addBodyAt(pos);

      nodeBodies[nodeId] = body;
      updateBodyMass(nodeId);

      if (isNodeOriginallyPinned(node)) {
        body.isPinned = true;
      }
    }
  }

  function releaseNode(node) {
    var nodeId = node.id;
    var body = nodeBodies[nodeId];
    if (body) {
      nodeBodies[nodeId] = null;
      delete nodeBodies[nodeId];

      physicsSimulator.removeBody(body);
    }
  }

  function initLink(link) {
    updateBodyMass(link.fromId);
    updateBodyMass(link.toId);

    var fromBody = nodeBodies[link.fromId],
        toBody  = nodeBodies[link.toId],
        spring = physicsSimulator.addSpring(fromBody, toBody, link.length);

    springTransform(link, spring);

    springs[link.id] = spring;
  }

  function releaseLink(link) {
    var spring = springs[link.id];
    if (spring) {
      var from = graph.getNode(link.fromId),
          to = graph.getNode(link.toId);

      if (from) updateBodyMass(from.id);
      if (to) updateBodyMass(to.id);

      delete springs[link.id];

      physicsSimulator.removeSpring(spring);
    }
  }

  function getNeighborBodies(node) {
    // TODO: Could probably be done better on memory
    var neighbors = [];
    if (!node.links) {
      return neighbors;
    }
    var maxNeighbors = Math.min(node.links.length, 2);
    for (var i = 0; i < maxNeighbors; ++i) {
      var link = node.links[i];
      var otherBody = link.fromId !== node.id ? nodeBodies[link.fromId] : nodeBodies[link.toId];
      if (otherBody && otherBody.pos) {
        neighbors.push(otherBody);
      }
    }

    return neighbors;
  }

  function updateBodyMass(nodeId) {
    var body = nodeBodies[nodeId];
    body.mass = nodeMass(nodeId);
  }

  /**
   * Checks whether graph node has in its settings pinned attribute,
   * which means layout algorithm cannot move it. Node can be preconfigured
   * as pinned, if it has "isPinned" attribute, or when node.data has it.
   *
   * @param {Object} node a graph node to check
   * @return {Boolean} true if node should be treated as pinned; false otherwise.
   */
  function isNodeOriginallyPinned(node) {
    return (node && (node.isPinned || (node.data && node.data.isPinned)));
  }

  function getInitializedBody(nodeId) {
    var body = nodeBodies[nodeId];
    if (!body) {
      initBody(nodeId);
      body = nodeBodies[nodeId];
    }
    return body;
  }

  /**
   * Calculates mass of a body, which corresponds to node with given id.
   *
   * @param {String|Number} nodeId identifier of a node, for which body mass needs to be calculated
   * @returns {Number} recommended mass of the body;
   */
  function nodeMass(nodeId) {
    var links = graph.getLinks(nodeId);
    if (links === null) {
      return 1;
    }
    return 1 + links.length / 3.0;
  }
}

function noop() { }
<|endoftext|>


<commit_before>/*jshint node: true */

var request = require('request'),
    json    = require('JSONStream'),
    es      = require('event-stream'),
    crypto  = require('crypto'),
    baseURI = 'https://api.checklist.ninja',
    merge   = require('lodash.merge'),
    url     = require('url'),
    config  = { host: baseURI };

// prepare payloads
function parsePayload(input) {
  if (typeof input === "object") { return input; }
  var obj = { title: input };
  return obj;
}

this.config = function (config) {
  if (config) { this.config = merge(this.config,config); }
  return this.config;
};

this.sign = function (method, resource, date) {
    var parsedUrl = url.parse(resource);
    var str     = this.config.secret + '\n' + date + '\n' + method + '\n' + parsedUrl.pathname + '\n',
        shasum  = crypto.createHash('sha1'); // this may be okay at higher scope

    shasum.update(str);
    return shasum.digest('hex');
  };

this.date = function () { return new Date().toUTCString(); };

this.raw = function (method, endpoint, payload, callback) {
    if (arguments.length === 3) {
        callback = payload;
    }

    var date    = this.date(),
        sig     = this.sign(method, endpoint, date),
        headers = {
          'authorization': 'ChecklistNinja ' + this.config.pubkey +  ':' + sig,
          'date'         : date
        },
        options = { url: this.config.host + endpoint, method: method, headers: headers };

        if (arguments.length === 4) {
            options.body = JSON.stringify(payload)
        }

    request(options, function (error, response, body) {
        if (!error) {
            if (response.statusCode == 204) {
                return callback(undefined, response.statusCode, null)
            }
            return callback(undefined, response.statusCode, JSON.parse(body))
        }
        return callback(error, null, null)
    });
  };

// Sugar

this.get = function (endpoint, callback) {
  this.raw('GET', endpoint, callback);
};

this.post = function (endpoint, payload, callback) {
  this.raw('POST', endpoint, payload, callback);
};

this.put = function (endpoint, payload, callback) {
  this.raw('PUT', endpoint, payload, callback);
};

this.patch = function (endpoint, payload, callback) {
  this.raw('PATCH', endpoint, payload, callback);
};

this.delete = function (endpoint, callback) {
  this.raw('DELETE', endpoint, callback);
};

this.getAccount = function(accountId, callback) {
  this.getOrFail('/accounts/' + accountId, 'Could not load account.', callback)
}

this.findAccount = function(email, callback) {
  var endpoint = '/accounts?email=' + encodeURIComponent(email)
  this.getOrFail(endpoint, 'Could not load account.', callback)
}

this.getChecklist = function(checklistId, callback) {
  this.getOrFail('/checklists/' + checklistId, 'Could not load checklist.', callback)
}

this.getChecklistEvents = function(checklistId, callback) {
  this.getOrFail('/checklists/' + checklistId + '/events', 'Could not load checklist events.', callback)
}

this.getChecklistWebhooks = function(checklistId, callback) {
  this.getOrFail('/checklists/' + checklistId + '/webhooks', 'Could not load checklist webhooks.', callback)
}

this.getOrFail = function(endpoint, message, callback) {
  this.get(endpoint, function(err, code, data) {
    if (!err && code == 200) {
      return callback(null, data)
    }
    callback(new Error(message))
  });
}
<commit_msg>Adding additional helper methods.<commit_after>/*jshint node: true */

var request = require('request'),
    json    = require('JSONStream'),
    es      = require('event-stream'),
    crypto  = require('crypto'),
    baseURI = 'https://api.checklist.ninja',
    merge   = require('lodash.merge'),
    url     = require('url'),
    config  = { host: baseURI };

// prepare payloads
function parsePayload(input) {
  if (typeof input === "object") { return input; }
  var obj = { title: input };
  return obj;
}

this.config = function (config) {
  if (config) { this.config = merge(this.config,config); }
  return this.config;
};

this.sign = function (method, resource, date) {
    var parsedUrl = url.parse(resource);
    var str     = this.config.secret + '\n' + date + '\n' + method + '\n' + parsedUrl.pathname + '\n',
        shasum  = crypto.createHash('sha1'); // this may be okay at higher scope

    shasum.update(str);
    return shasum.digest('hex');
  };

this.date = function () { return new Date().toUTCString(); };

this.raw = function (method, endpoint, payload, callback) {
    if (arguments.length === 3) {
        callback = payload;
    }

    var date    = this.date(),
        sig     = this.sign(method, endpoint, date),
        headers = {
          'authorization': 'ChecklistNinja ' + this.config.pubkey +  ':' + sig,
          'date'         : date
        },
        options = { url: this.config.host + endpoint, method: method, headers: headers };

        if (arguments.length === 4) {
            options.body = JSON.stringify(payload)
        }

    request(options, function (error, response, body) {
        if (!error) {
            if (response.statusCode == 204) {
                return callback(undefined, response.statusCode, null)
            }
            return callback(undefined, response.statusCode, JSON.parse(body))
        }
        return callback(error, null, null)
    });
  };

// Sugar

this.get = function (endpoint, callback) {
  this.raw('GET', endpoint, callback);
};

this.post = function (endpoint, payload, callback) {
  this.raw('POST', endpoint, payload, callback);
};

this.put = function (endpoint, payload, callback) {
  this.raw('PUT', endpoint, payload, callback);
};

this.patch = function (endpoint, payload, callback) {
  this.raw('PATCH', endpoint, payload, callback);
};

this.delete = function (endpoint, callback) {
  this.raw('DELETE', endpoint, callback);
};

this.getAccount = function(accountId, callback) {
  this.getOrFail('/accounts/' + accountId, 'Could not load account.', callback)
}

this.findAccount = function(email, callback) {
  var endpoint = '/accounts?email=' + encodeURIComponent(email)
  this.getOrFail(endpoint, 'Could not load account.', callback)
}

this.getChecklists = function(callback) {
  this.getOrFail('/checklists', 'Could not load checklists.', callback)
}

this.getChecklist = function(checklistId, callback) {
  this.getOrFail('/checklists/' + checklistId, 'Could not load checklist.', callback)
}

this.getChecklistEvents = function(checklistId, callback) {
  this.getOrFail('/checklists/' + checklistId + '/events', 'Could not load checklist events.', callback)
}

this.getChecklistWebhooks = function(checklistId, callback) {
  this.getOrFail('/checklists/' + checklistId + '/webhooks', 'Could not load checklist webhooks.', callback)
}

// TODO: Verify that the 2nd param is an array of strings.
this.createChecklist = function(title, tags, callback) {
  var payload = {
    'title': title
  }

  // If createChecklist('title', fn)
  if (arguments.length === 2) {
    callback = tags;
  } else {
    // if createChecklist('title', ['foo'], callback)
    payload.tags = tags
  }

  this.post('/checklists', payload, function(error, code, data) {
    if (!err && code == 201) {
      return callback(null, data)
    }
    callback(new Error('Could not create checklist.'))
  });
}

this.createItem = function(checklistId, displayText, parent, position, callback) {

  // TODO: Ensure position is serialized as a number.
  var payload = {
    'display_text': displayText,
    'parent': parent,
    'position': position
  }

  this.post('/checklists/' + checklistId + '/items', payload, function(error, code, data) {
    if (!err && code == 201) {
      return callback(null, data)
    }
    callback(new Error('Could not create checklist item.'))
  });
}

this.createGroup = function(checklistId, label, parent, position, callback) {

  // TODO: Ensure position is serialized as a number.
  var payload = {
    'label': label,
    'parent': parent,
    'position': position
  }

  this.post('/checklists/' + checklistId + '/groups', payload, function(error, code, data) {
    if (!err && code == 201) {
      return callback(null, data)
    }
    callback(new Error('Could not create checklist group.'))
  });
}

this.getOrFail = function(endpoint, message, callback) {
  this.get(endpoint, function(err, code, data) {
    if (!err && code == 200) {
      return callback(null, data)
    }
    callback(new Error(message))
  });
}
<|endoftext|>