<commit_before>var sqlite3 = require('sqlite3');
var fs = require('fs');
var file = 'sample_data/templog.db';
var exists = fs.existsSync(file);

if (!exists) {
	console.log('file does not exist.');
} else {
	console.log('file exists.');
}

var db = new sqlite3.Database(file);

module.exports.getAll = function (callback) {

	var sqlQuery = 'SELECT * FROM temps';

	db.all(sqlQuery, function (err, rows) {
		if (err !== null) {
			// TODO Error handling
			console.log('Error during sql query: ' + err);
		} else {
			var temperatureData = [];

			for(var i = 0; i < rows.length; i++) {
				temperatureData.push({
					degreeCelsius: rows[i].temp,
					sensorName: rows[i].ID,
					timestamp: rows[i].timestamp
				});
			}

			callback(temperatureData);
		}
	});
};
<commit_msg>added NODE_ENV switch for db location (dev/prod).<commit_after>var sqlite3 = require('sqlite3');
var fs = require('fs');

var dbLocation = process.env.NODE_ENV === 'production'
		? '/var/www/templog.db'
		: 'sample_data/templog.db';

var exists = fs.existsSync(dbLocation);

if (!exists) {
	console.log('db file does not exist.');
} else {
	console.log('db file exists.');
}

var db = new sqlite3.Database(dbLocation);

module.exports.getAll = function (callback) {

	var sqlQuery = 'SELECT * FROM temps';

	db.all(sqlQuery, function (err, rows) {
		if (err !== null) {
			// TODO Error handling
			console.log('Error during sql query: ' + err);
		} else {
			var temperatureData = [];

			for(var i = 0; i < rows.length; i++) {
				temperatureData.push({
					degreeCelsius: rows[i].temp,
					sensorName: rows[i].ID,
					timestamp: rows[i].timestamp
				});
			}

			callback(temperatureData);
		}
	});
};
<|endoftext|>


<commit_before>'use strict';

// Module dependencies
var express = require('express')
  , livereload = require('./livereload');

// var enableCORS = require('./enableCORS');

var middleware = function (server, config) {

  // log requests to the console
  server.use(express.logger('dev'));

  // setup encrypted session cookies
  if (config.server.secret) {
    server.use(express.cookieParser());
    server.use(express.session({secret: config.server.secret}));
  }

  // For security sake, it's better to disable file upload if your application doesn't need it.
  // To do this, don't use the bodyParser and multipart() middleware
  // @see http://expressjs.com/api.html#bodyParser
  server.use(express.json());
  server.use(express.urlencoded());

  server.use(express.methodOverride());

  // allow CORS
  // server.use(enableCORS);

  var viewEngine;

  // ## Views

  // views directory
  server.set('views', config.dirs.views);

  // view engine
  switch (config.viewEngine) {
    case 'jade':
      server.set('view engine', 'jade');
      break;
    case 'ect':
      viewEngine = require('ect')({watch: true, root: server.get('views')});
      server.engine('ect', viewEngine.render);
      server.set('view engine', 'ect');
      break;
    case 'html' :
      viewEngine = require('ect')({watch: true, root: server.get('views')});
      server.engine('html', viewEngine.render); // assign ect as the engine for html files
      server.set('view engine', 'html'); // set .html as the default extension
      break;
  }

  // ## Livereload
  if (config.livereload) {
    livereload(server, config);
  }

  // ## Static Files

  // return the correct mime type for woff filess
  express.static.mime.define({'application/font-woff': ['woff']});

  // Set the directory(s) to serve static files from
  if (config.dirs.static) {
    var staticDirs, maxAge;
    staticDirs = [].concat(config.dirs.static);
    maxAge = 30 * 24 * 60 * 60 * 1000; // 30 day cache control in milliseconds
    for (var i = staticDirs.length - 1; i >= 0; i--) {
      server.use(express.static(staticDirs[i], {maxAge: maxAge}));
    }
  }

  // ## Error Handler
  // Picks up any left over errors and returns a nicely formatted server 500 error
  server.use(express.errorHandler());
};

module.exports = middleware;<commit_msg>minor refactoring<commit_after>'use strict';

// Module dependencies
var express = require('express');

var livereload = require('./livereload');
// var enableCORS = require('./enableCORS');

var middleware = function (server, config) {

  // log requests to the console
  server.use(express.logger('dev'));

  // setup encrypted session cookies
  if (config.server.secret) {
    server.use(express.cookieParser());
    server.use(express.session({secret: config.server.secret}));
  }

  // For security sake, it's better to disable file upload if your application doesn't need it.
  // To do this, don't use the bodyParser and multipart() middleware
  // @see http://expressjs.com/api.html#bodyParser
  server.use(express.json());
  server.use(express.urlencoded());

  server.use(express.methodOverride());

  // allow CORS
  // server.use(enableCORS);

  var viewEngine;

  // ## Views

  // views directory
  server.set('views', config.dirs.views);

  // view engine
  switch (config.viewEngine) {
    case 'jade':
      server.set('view engine', 'jade');
      break;
    case 'ect':
      viewEngine = require('ect')({watch: true, root: server.get('views')});
      server.engine('ect', viewEngine.render);
      server.set('view engine', 'ect');
      break;
    case 'html' :
      viewEngine = require('ect')({watch: true, root: server.get('views')});
      server.engine('html', viewEngine.render); // assign ect as the engine for html files
      server.set('view engine', 'html'); // set .html as the default extension
      break;
  }

  // ## Livereload
  if (config.livereload) {
    livereload(server, config);
  }

  // ## Static Files

  // return the correct mime type for woff filess
  express.static.mime.define({'application/font-woff': ['woff']});

  // Set the directory(s) to serve static files from
  if (config.dirs.static) {
    var staticDirs, maxAge;
    staticDirs = [].concat(config.dirs.static);
    maxAge = 30 * 24 * 60 * 60 * 1000; // 30 day cache control in milliseconds
    for (var i = staticDirs.length - 1; i >= 0; i--) {
      server.use(express.static(staticDirs[i], {maxAge: maxAge}));
    }
  }

  // ## Error Handler
  // Picks up any left over errors and returns a nicely formatted server 500 error
  server.use(express.errorHandler());
};

module.exports = middleware;<|endoftext|>


<commit_before>/**
 * TAC Presets: TAC rankings, followed by wins and numgames
 *
 * @return Presets
 * @author Erik E. Lorenz <erik@tuvero.de>
 * @license MIT License
 * @see LICENSE
 */

define(function () {
  var Presets;

  Presets = {
    target: "tac",
    systems: {
      swiss: {
        ranking: ["tac", "numgames", "wins", "headtohead"],
        mode: "ranks"
      },
      ko: {
        mode: "matched"
      },
      round: {
        ranking: ["tac", "numgames", "wins", "headtohead"]
      },
      placement: {}
    },
    ranking: {
      components: ["tac", "numgames", "wins", "headtohead", "saldo"]
    },
    registration: {
      defaultteamsize: 1,
      minteamsize: 1,
      maxteamsize: 3,
      teamsizeicon: false
    },
    taboptions: {
      namemaxwidth: false,
      showmatchtables: true
    },
    names: {
      playernameurl: "",
      dbplayername: "tacplayers",
      apitoken: "apitoken",
      teamsfile: "tuvero-anmeldungen.txt"
    },
    ui: {
      rankingpoints: false,
      hiderankingorder: true
    }
  };

  return Presets;
});<commit_msg>Enable buchholz, feinbuchholz and sonneborn for TAC<commit_after>/**
 * TAC Presets: TAC rankings, followed by wins and numgames
 *
 * @return Presets
 * @author Erik E. Lorenz <erik@tuvero.de>
 * @license MIT License
 * @see LICENSE
 */

define(function () {
  var Presets;

  Presets = {
    target: "tac",
    systems: {
      swiss: {
        ranking: ["tac", "numgames", "wins", "headtohead"],
        mode: "ranks"
      },
      ko: {
        mode: "matched"
      },
      round: {
        ranking: ["tac", "numgames", "wins", "headtohead"]
      },
      placement: {}
    },
    ranking: {
      components: ["tac", "numgames", "wins", "saldo", "headtohead", "buchholz", "finebuchholz", "sonneborn"]
    },
    registration: {
      defaultteamsize: 1,
      minteamsize: 1,
      maxteamsize: 3,
      teamsizeicon: false
    },
    taboptions: {
      namemaxwidth: false,
      showmatchtables: true
    },
    names: {
      playernameurl: "",
      dbplayername: "tacplayers",
      apitoken: "apitoken",
      teamsfile: "tuvero-anmeldungen.txt"
    },
    ui: {
      rankingpoints: false,
      hiderankingorder: true
    }
  };

  return Presets;
});<|endoftext|>


<commit_before>/*
Copyright 2006-2007, Open Source Applications Foundation

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

//Wait a specified number of milliseconds
windmill.controller.waits.sleep = function (paramObj, obj) {
  windmill.waiting = true;
  //if a number of milliseconds werent provided in a int format
  if ((paramObj.milliseconds == "") || (parseInt(paramObj.milliseconds, 10) == NaN)){
    paramObj.milliseconds = 5000;
  }

  done = function(){
    windmill.waiting = false;
    windmill.controller.continueLoop();
    //we passed the id in the parms object of the action in the ide
    var aid = paramObj.aid;
    delete paramObj.aid;
    //set the result in the ide
    windmill.xhr.setWaitBgAndReport(aid,true,obj);
  }
  setTimeout('done()', paramObj.milliseconds);
  return true;
};

windmill.controller.waits.forJSTrue = function (paramObj, obj, pageLoad) {
  _this = this;

  //we passed the id in the parms object of the action in the ide
  var aid = paramObj.aid;
  delete paramObj.aid;
  var count = 0;
  var p = paramObj || {};
  var timeout = 8000;
  var isJsTest = (p.orig == 'js');
  var testCondition = p.test;

  // If we get the weird string "NaN" (yes, the actual
  // string, "NaN" :)) value from the IDE, or some other
  // unusable string , just use the default value of 20 seconds
  if (p.timeout) {
    if (parseInt(p.timeout, 10) != NaN){
      timeout = p.timeout;
    }
  }

  //implement windmill safe waits
  //most browser javascript interpreters time out when the wait is greater than 60 seconds
  if ((windmill.safeWaits) && (timeout > 600000)){
    timeout = 60000;
  }

  //lookup method
  var lookup = function () {
    if (count >= timeout) {
      if (isJsTest) {
        windmill.jsTest.runTestItemArray();
        windmill.jsTest.waiting = false;
        windmill.jsTest.handleErr('waits.forElement timed out after ' + timeout + ' seconds.');
      }
      else {
        if (pageLoad){
          windmill.loaded();
          windmill.controller.continueLoop();
        }
        else{ windmill.controller.continueLoop(); }
      }
      windmill.xhr.setWaitBgAndReport(aid,false,obj);
      return false;
    }
    count += 100;

    // Get a result
    var result;
    if (typeof testCondition == 'string') {
      result = eval(testCondition);
    }
    else if (typeof testCondition == 'function') {
      result = testCondition();
    }
    else {
      throw new Error('waits.forTrue test condition must be a string or function.');
    }
    result = !!result; // Make sure we've got a Boolean

    if (!result){ var x = setTimeout(lookup, 100); }
    else {
        c = function () {
          //If this method is being called by the js test framework
          if (isJsTest) {
            windmill.jsTest.waiting = false;
            windmill.jsTest.runTestItemArray();
          }
          else{
             if (pageLoad){ windmill.loaded(); }
             else{ windmill.controller.continueLoop(); }
          }

           //set the result in the ide
            windmill.xhr.setWaitBgAndReport(aid,true,obj);
        }
      setTimeout(c, 500);
    }
  }

  lookup();

  //waits are going to wait, so I return true
  //Optimally it would return false if it times out, so when it does return false
  //the calling code will jump back up and process the ui accordingly
  return true;

};

//wait for an element to show up on the page
//if it doesn't after a provided timeout, defaults to 20 seconds
windmill.controller.waits.forElement = function (paramObj,obj) {
    var p = paramObj || {};
    var f = function () {
      try { return windmill.controller._lookupDispatch(p); }
      catch(err){}
    };
    p.test = f;
    return windmill.controller.waits.forJSTrue(p, obj);
};

//wait for an element to show up on the page
//if it doesn't after a provided timeout, defaults to 20 seconds
windmill.controller.waits.forNotElement = function (paramObj,obj) {
    var p = paramObj || {};
    var f = function () {
      try{
        var node = windmill.controller._lookupDispatch(p);
        return !node;
      }
      catch(err){}
    };
    p.test = f;
    return windmill.controller.waits.forJSTrue(p, obj);
};

//This is more of an internal function used by wait and click events
//To know when to try and reattach the listeners
//But if users wanted this manually they could use it
windmill.controller.waits.forPageLoad = function (paramObj,obj) {

  var p = paramObj || {};
  var sl = function(){
    var f = function () {
      try {
        var v = opener.document.domain;
      }catch(err){
        document.domain = windmill.docDomain;
      }
      try {
        var d = opener.document.body.style;
      }catch(err){ d = null;}

      if (d != null){
        return true;
      }

      return false;
    };
    p.test = f;

    return windmill.controller.waits.forJSTrue(p, obj, true);
  }
  setTimeout(sl, 500);
  //we can't access the body, so now wait for the loading
  //setTimeout(sl, 0);
}

//wait for an element to show up on the page
//if it doesn't after a provided timeout, defaults to 20 seconds
windmill.controller.waits._forNotTitleAttach = function (paramObj,obj) {
    var p = paramObj || {};
    var f = function () {
      try {
        if (opener.document.title != param_object.title){
          var d = opener.document.body;
          return true;
        }
        return false;
      } catch(err){ return false; }
    };
    p.test = f;
    p.timeout = 60000;
    return windmill.controller.waits.forJSTrue(p, obj, true);
};<commit_msg>Fixing a waits bug for IE<commit_after>/*
Copyright 2006-2007, Open Source Applications Foundation

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

//Wait a specified number of milliseconds
windmill.controller.waits.sleep = function (paramObj, obj) {
  windmill.waiting = true;
  //if a number of milliseconds werent provided in a int format
  if ((paramObj.milliseconds == "") || (parseInt(paramObj.milliseconds, 10) == NaN)){
    paramObj.milliseconds = 5000;
  }

  done = function(){
    windmill.waiting = false;
    windmill.controller.continueLoop();
    //we passed the id in the parms object of the action in the ide
    var aid = paramObj.aid;
    delete paramObj.aid;
    //set the result in the ide
    windmill.xhr.setWaitBgAndReport(aid,true,obj);
  }
  setTimeout('done()', paramObj.milliseconds);
  return true;
};

windmill.controller.waits.forJSTrue = function (paramObj, obj, pageLoad) {
  _this = this;

  //we passed the id in the parms object of the action in the ide
  var aid = paramObj.aid;
  delete paramObj.aid;
  var count = 0;
  var p = paramObj || {};
  var timeout = 8000;
  var isJsTest = (p.orig == 'js');
  var testCondition = p.test;

  // If we get the weird string "NaN" (yes, the actual
  // string, "NaN" :)) value from the IDE, or some other
  // unusable string , just use the default value of 20 seconds
  if (p.timeout) {
    if (parseInt(p.timeout, 10) != NaN){
      timeout = p.timeout;
    }
  }

  //implement windmill safe waits
  //most browser javascript interpreters time out when the wait is greater than 60 seconds
  if ((windmill.safeWaits) && (timeout > 60000)){
    timeout = 60000;
  }

  //lookup method
  var lookup = function () {
    if (count >= timeout) {
      if (isJsTest) {
        windmill.jsTest.runTestItemArray();
        windmill.jsTest.waiting = false;
        windmill.jsTest.handleErr('waits.forElement timed out after ' + timeout + ' seconds.');
      }
      else {
        if (pageLoad){
          windmill.loaded();
          windmill.controller.continueLoop();
        }
        else{ windmill.controller.continueLoop(); }
      }
      windmill.xhr.setWaitBgAndReport(aid,false,obj);
      return false;
    }
    count += 100;

    // Get a result
    var result;
    if (typeof testCondition == 'string') {
      result = eval(testCondition);
    }
    else if (typeof testCondition == 'function') {
      result = testCondition();
    }
    else {
      throw new Error('waits.forTrue test condition must be a string or function.');
    }
    result = !!result; // Make sure we've got a Boolean

    if (!result){ var x = setTimeout(lookup, 100); }
    else {
        c = function () {
          //If this method is being called by the js test framework
          if (isJsTest) {
            windmill.jsTest.waiting = false;
            windmill.jsTest.runTestItemArray();
          }
          else{
             if (pageLoad){ windmill.loaded(); }
             else{ windmill.controller.continueLoop(); }
          }

           //set the result in the ide
            windmill.xhr.setWaitBgAndReport(aid,true,obj);
        }
      setTimeout(c, 500);
    }
  }

  lookup();

  //waits are going to wait, so I return true
  //Optimally it would return false if it times out, so when it does return false
  //the calling code will jump back up and process the ui accordingly
  return true;

};

//wait for an element to show up on the page
//if it doesn't after a provided timeout, defaults to 20 seconds
windmill.controller.waits.forElement = function (paramObj,obj) {
    var p = paramObj || {};
    var f = function () {
      try { return windmill.controller._lookupDispatch(p); }
      catch(err){}
    };
    p.test = f;
    return windmill.controller.waits.forJSTrue(p, obj);
};

//wait for an element to show up on the page
//if it doesn't after a provided timeout, defaults to 20 seconds
windmill.controller.waits.forNotElement = function (paramObj,obj) {
    var p = paramObj || {};
    var f = function () {
      try{
        var node = windmill.controller._lookupDispatch(p);
        return !node;
      }
      catch(err){}
    };
    p.test = f;
    return windmill.controller.waits.forJSTrue(p, obj);
};

//This is more of an internal function used by wait and click events
//To know when to try and reattach the listeners
//But if users wanted this manually they could use it
windmill.controller.waits.forPageLoad = function (paramObj,obj) {

  var p = paramObj || {};
  var sl = function(){
    var f = function () {
      try {
        var v = opener.document.domain;
      }catch(err){
        document.domain = windmill.docDomain;
      }
      try {
        var d = opener.document.body.style;
      }catch(err){ d = null;}

      if (d != null){
        return true;
      }

      return false;
    };
    p.test = f;

    return windmill.controller.waits.forJSTrue(p, obj, true);
  }
  setTimeout(sl, 500);
  //we can't access the body, so now wait for the loading
  //setTimeout(sl, 0);
}

//wait for an element to show up on the page
//if it doesn't after a provided timeout, defaults to 20 seconds
windmill.controller.waits._forNotTitleAttach = function (paramObj,obj) {
    var p = paramObj || {};
    var f = function () {
      try {
        if (opener.document.title != param_object.title){
          var d = opener.document.body;
          return true;
        }
        return false;
      } catch(err){ return false; }
    };
    p.test = f;
    p.timeout = 60000;
    return windmill.controller.waits.forJSTrue(p, obj, true);
};<|endoftext|>


<commit_before>'use strict'

const $ = require('gulp-load-plugins')()
const webpack = require('webpack')
const path = require('path')

const config = require('../../config/webpack')

const webpackDone = (done) => (err, stats) => {
  if (err) {
    throw new $.util.PluginError('webpack', err)
  }

  $.util.log('[webpack]', stats.toString({
    modules: false,
    colors: true,
    chunks: false
  }))

  done()
}

module.exports = {
  dep: ['clean:browser'],
  fn (gulp, done) {
    const c = config
    c.output.filename = 'index.js'
    c.output.path = path.resolve('dist')
    c.devtool = 'source-map'
    c.debug = false
    c.plugins.push(
      new webpack.optimize.DedupePlugin()
    )

    webpack(c, webpackDone(() => {
      gulp.src('dist/index.js')
        .pipe($.uglify({
          mangle: false
        }))
        .pipe($.rename({
          suffix: '.min'
        }))
        .pipe($.size())
        .pipe(gulp.dest('dist'))
        .once('end', done)
    }))
  }
}
<commit_msg>feat(build): add stats flag<commit_after>'use strict'

const $ = require('gulp-load-plugins')()
const webpack = require('webpack')
const path = require('path')
const fs = require('fs')

const config = require('../../config/webpack')

const webpackDone = (done) => (err, stats) => {
  if (err) {
    throw new $.util.PluginError('webpack', err)
  }

  if ($.util.env.stats) {
    fs.writeFileSync('stats.json', JSON.stringify(stats.toJson(), null, 2))
  }

  $.util.log('[webpack]', stats.toString({
    modules: false,
    colors: true,
    chunks: false
  }))

  done()
}

module.exports = {
  dep: ['clean:browser'],
  fn (gulp, done) {
    const c = config
    c.output.filename = 'index.js'
    c.output.path = path.resolve('dist')
    c.devtool = 'source-map'
    c.debug = false
    c.plugins.push(
      new webpack.optimize.DedupePlugin()
    )

    webpack(c, webpackDone(() => {
      gulp.src('dist/index.js')
        .pipe($.uglify({
          mangle: false
        }))
        .pipe($.rename({
          suffix: '.min'
        }))
        .pipe($.size())
        .pipe(gulp.dest('dist'))
        .once('end', done)
    }))
  }
}
<|endoftext|>


<commit_before>/*
 * grunt-spider-script
 * https://github.com/mariusc23/grunt-spider-script
 *
 * Copyright (c) 2014 Marius Craciunoiu
 * Licensed under the MIT license.
 */

'use strict';
var spider = require('spider-script');
var path = require('path');
var dargs = require('dargs');
var numCPUs = require('os').cpus().length || 1;
var async = require('async');
var chalk = require('chalk');

module.exports = function (grunt) {
  grunt.registerMultiTask('spider_script', 'Compile spider script into javascript.', function () {
    var cb = this.async();
    var options = this.options();
    var banner;
    var passedArgs;

    // Unset banner option if set
    if (options.banner) {
      banner = options.banner;
      delete options.banner;
    }

    passedArgs = dargs(options, ['bundleExec']);

    async.eachLimit(this.files, numCPUs, function (file, next) {
      // Default options
      var options = this.options({
        sourcemap: true,
        strict: true,
        separator: grunt.util.linefeed
      });

      options.separator = grunt.util.normalizelf(options.separator);
      options.sourcemap = file.src.length > 1 ? false : options.sourcemap; // disable sourcemaps if concatenating files

      var src = file.src[0];

      if (typeof src !== 'string') {
        src = file.orig.src[0];
      };

      // Concat files if necessary
      var contents = file.src.filter(function(filepath) {
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        return grunt.file.read(filepath);
      }).join(options.separator);

      // Make sure grunt creates the destination folders if they don't exist
      if (!grunt.file.exists(file.dest)) {
        grunt.file.write(file.dest, '');
      }

      var errors = [];
      var sourceMapDest = file.dest.replace(file.orig && file.orig.ext ? file.orig.ext : '.js', '.map');

      if (options.sourcemap) {
        var result = spider.compile(contents, false, errors, src, sourceMapDest, true, options.strict);
      } else {
        var result = {
          code: spider.compile(contents, false, errors, false, sourceMapDest, true, options.strict)
        };
      };

      if (errors.length) {
        for (var i = 0; i < errors.length; i++) {
          var startLoc = (errors[i].loc && errors[i].loc.start) ? ('Line: ' + errors[i].loc.start.line + ', Column: ' + errors[i].loc.start.column) : '';
          var endLoc = (errors[i].loc && errors[i].loc.end) ? ('Line: ' + errors[i].loc.end.line + ', Column: ' + errors[i].loc.end.column) : '';
          grunt.warn([errors[i].type + ':' , errors[i].message, 'at', src, 'on', startLoc, endLoc].join(' ')); // FIXME: this will be wrong if concatenating
        };
      };

      grunt.file.write(file.dest, result.code);
      grunt.verbose.writeln('Compiled file ' + chalk.cyan(file.dest) + ' created.');

      if (options.sourcemap !== false) {
        grunt.file.write(sourceMapDest, result.map);
        grunt.verbose.writeln('Source map ' + chalk.cyan(sourceMapDest) + ' created.');
      };

      if (banner) {
        grunt.verbose.writeln('Writing banner for ' + chalk.cyan(file.dest));
        grunt.file.write(file.dest, banner + grunt.util.linefeed + grunt.file.read(file.dest));
      };

      next();
    }.bind(this), cb);

  });
};
<commit_msg>Clean up useless code<commit_after>/*
 * grunt-spider-script
 * https://github.com/mariusc23/grunt-spider-script
 *
 * Copyright (c) 2014 Marius Craciunoiu
 * Licensed under the MIT license.
 */

'use strict';
var spider = require('spider-script');
var path = require('path');
var numCPUs = require('os').cpus().length || 1;
var async = require('async');
var chalk = require('chalk');

module.exports = function (grunt) {
  grunt.registerMultiTask('spider_script', 'Compile spider script into javascript.', function () {
    var cb = this.async();
    var options = this.options();
    var banner;

    // Unset banner option if set
    if (options.banner) {
      banner = options.banner;
      delete options.banner;
    }

    async.eachLimit(this.files, numCPUs, function (file, next) {
      // Default options
      var options = this.options({
        sourcemap: true,
        strict: true,
        separator: grunt.util.linefeed
      });

      options.separator = grunt.util.normalizelf(options.separator);
      options.sourcemap = file.src.length > 1 ? false : options.sourcemap; // disable sourcemaps if concatenating files

      var src = file.src[0];

      if (typeof src !== 'string') {
        src = file.orig.src[0];
      };

      // Concat files if necessary
      var contents = file.src.filter(function(filepath) {
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        return grunt.file.read(filepath);
      }).join(options.separator);

      // Make sure grunt creates the destination folders if they don't exist
      if (!grunt.file.exists(file.dest)) {
        grunt.file.write(file.dest, '');
      }

      var errors = [];
      var sourceMapDest = file.dest.replace(file.orig && file.orig.ext ? file.orig.ext : '.js', '.map');

      if (options.sourcemap) {
        var result = spider.compile(contents, false, errors, src, sourceMapDest, true, options.strict);
      } else {
        var result = {
          code: spider.compile(contents, false, errors, false, sourceMapDest, true, options.strict)
        };
      };

      if (errors.length) {
        for (var i = 0; i < errors.length; i++) {
          var startLoc = (errors[i].loc && errors[i].loc.start) ? ('Line: ' + errors[i].loc.start.line + ', Column: ' + errors[i].loc.start.column) : '';
          var endLoc = (errors[i].loc && errors[i].loc.end) ? ('Line: ' + errors[i].loc.end.line + ', Column: ' + errors[i].loc.end.column) : '';
          grunt.warn([errors[i].type + ':' , errors[i].message, 'at', src, 'on', startLoc, endLoc].join(' ')); // FIXME: this will be wrong if concatenating
        };
      };

      grunt.file.write(file.dest, result.code);
      grunt.verbose.writeln('Compiled file ' + chalk.cyan(file.dest) + ' created.');

      if (options.sourcemap !== false) {
        grunt.file.write(sourceMapDest, result.map);
        grunt.verbose.writeln('Source map ' + chalk.cyan(sourceMapDest) + ' created.');
      };

      if (banner) {
        grunt.verbose.writeln('Writing banner for ' + chalk.cyan(file.dest));
        grunt.file.write(file.dest, banner + grunt.util.linefeed + grunt.file.read(file.dest));
      };

      next();
    }.bind(this), cb);

  });
};
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var path = require('path');
var fs = require('fs');

var tcollectorSpec = fs.readFileSync(
    path.join(__dirname, 'tcollector.thrift'), 'utf8'
);

module.exports = TCollectorTraceReporter;

function TCollectorTraceReporter(options) {
    if (!(this instanceof TCollectorTraceReporter)) {
        return new TCollectorTraceReporter(options);
    }
    var self = this;

    self.logger = options.logger;
    self.channel = options.channel;

    if (!self.channel) {
        // TODO: typederror or vld
        throw new Error('TCollectorTraceReporter must be passed a tchannel');
    }

    self.tchannelThrift = self.channel.TChannelAsThrift({
        source: tcollectorSpec
    });
}

function ipToInt(ip) {
    var ipl = 0;
    var parts = ip.split('.');
    for (var i = 0; i < parts; i++) {
        ipl <<= 8;
        ipl += parseInt(parts[i], 10);
    }
    return (ipl >>> 0);
}

function convertHost(endpoint) {
    return {
        ipv4: ipToInt(endpoint.ipv4),
        port: endpoint.port,
        serviceName: endpoint.serviceName
    };
}

function jsonSpanToThriftSpan(span) {
    var annotations = span.annotations.map(function fixAnnotation(item) {
        return {
            timestamp: item.timestamp,
            value: item.value
        };
    });

    var binaryAnnotations =
        span.binaryAnnotations.map(function fixBinAnnotation(item) {
            var ret = {
                key: item.key
            };

            if (item.type === 'boolean') {
                ret.annotationType = 'BOOL';
                ret.boolValue = item.value;
            } else if (item.type === 'number') {
                ret.annotationType = 'DOUBLE';
                ret.doubleValue = item.value;
            } else {
                ret.annotationType = 'STRING';
                ret.stringValue = String(item.value);
            }

            return ret;
        });

    if (!span.host) {
        // Workaround to support older tchannels
        span.host = convertHost(span.annotations[0].host);
    }

    var mapped = {
        name: span.name,
        traceId: span.traceid,
        parentId: span.parentid,
        id: span.id,
        annotations: annotations,
        binaryAnnotations: binaryAnnotations,
        host: span.host
    };

    return mapped;
}

TCollectorTraceReporter.prototype.report = function report(span, callback) {
    var self = this;

    var req = self.channel.request({
        timeout: 100,
        trace: false,
        hasNoParent: true,
        headers:{
            cn: "tcollector-reporter",
            shardKey: span.traceid.toString('base64')
        },
        serviceName: 'tcollector',
        retryLimit: 1,
        retryFlags: {never: true}
    });

    self.tchannelThrift.send(
        req,
        'TCollector::submit',
        null,
        {span: jsonSpanToThriftSpan(span)},
        function (err, response) {
            if (err) {
                self.logger.warn("Zipkin span submit failed", {
                    err: err
                });
                if (callback) {
                    callback(err);
                }
                return;
            }

            if (!response.ok) {
                self.logger.warn("Zipkin span submit failed: not ok", {
                    response: response
                });
            }

            if (callback) {
                callback();
            }
        }
    );
};

<commit_msg>tcollector: style fixes<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var path = require('path');
var fs = require('fs');

var tcollectorSpec = fs.readFileSync(
    path.join(__dirname, 'tcollector.thrift'), 'utf8'
);

module.exports = TCollectorTraceReporter;

function TCollectorTraceReporter(options) {
    if (!(this instanceof TCollectorTraceReporter)) {
        return new TCollectorTraceReporter(options);
    }
    var self = this;

    self.logger = options.logger;
    self.channel = options.channel;

    if (!self.channel) {
        // TODO: typederror or vld
        throw new Error('TCollectorTraceReporter must be passed a tchannel');
    }

    self.tchannelThrift = self.channel.TChannelAsThrift({
        source: tcollectorSpec
    });
}

function ipToInt(ip) {
    var ipl = 0;
    var parts = ip.split('.');
    for (var i = 0; i < parts; i++) {
        ipl <<= 8;
        ipl += parseInt(parts[i], 10);
    }
    return (ipl >>> 0);
}

function convertHost(endpoint) {
    return {
        ipv4: ipToInt(endpoint.ipv4),
        port: endpoint.port,
        serviceName: endpoint.serviceName
    };
}

function jsonSpanToThriftSpan(span) {
    var annotations = span.annotations.map(function fixAnnotation(item) {
        return {
            timestamp: item.timestamp,
            value: item.value
        };
    });

    var binaryAnnotations =
        span.binaryAnnotations.map(function fixBinAnnotation(item) {
            var ret = {
                key: item.key
            };

            if (item.type === 'boolean') {
                ret.annotationType = 'BOOL';
                ret.boolValue = item.value;
            } else if (item.type === 'number') {
                ret.annotationType = 'DOUBLE';
                ret.doubleValue = item.value;
            } else {
                ret.annotationType = 'STRING';
                ret.stringValue = String(item.value);
            }

            return ret;
        });

    if (!span.host) {
        // Workaround to support older tchannels
        span.host = convertHost(span.annotations[0].host);
    }

    var mapped = {
        name: span.name,
        traceId: span.traceid,
        parentId: span.parentid,
        id: span.id,
        annotations: annotations,
        binaryAnnotations: binaryAnnotations,
        host: span.host
    };

    return mapped;
}

TCollectorTraceReporter.prototype.report = function report(span, callback) {
    var self = this;

    var req = self.channel.request({
        timeout: 100,
        trace: false,
        hasNoParent: true,
        headers: {
            cn: 'tcollector-reporter',
            shardKey: span.traceid.toString('base64')
        },
        serviceName: 'tcollector',
        retryLimit: 1,
        retryFlags: {
            never: true
        }
    });

    self.tchannelThrift.send(req, 'TCollector::submit', null, {
        span: jsonSpanToThriftSpan(span)
    }, onResponse);

    function onResponse(err, response) {
        if (err) {
            self.logger.warn('Zipkin span submit failed', {
                err: err
            });
            if (callback) {
                callback(err);
            }
            return;
        }

        if (!response.ok) {
            self.logger.warn('Zipkin span submit failed: not ok', {
                response: response
            });
        }

        if (callback) {
            callback();
        }
    }
};

<|endoftext|>


<commit_before>const t = require("babel-types");

const { htmlStringEscape } = require("../render/util");
const { REACT_ID } = require("../symbols");

const _isVanillaDomTag = /^[a-z][a-z0-9\-]*$/;
const isVanillaDomTag = tag => _isVanillaDomTag.test(tag);

module.exports = () => ({
  manipulateOptions: (opts, parserOpts) => parserOpts.plugins.push("jsx"),
  visitor: {
    JSXElement: path => {
      const { node } = path;
      path.replaceWith(
        isVanillaDomTag(node.openingElement.name.name) ?
          prerenderDom(node) :
          prerenderComponent(node)
      );
    }
  }
});

// <Component />
const prerenderComponent = node => {
  const children = node.children
    .map(child => {
      if (t.isJSXText(child)) {
        const trimmed = child.value.trim();
        return trimmed && t.stringLiteral(trimmed);
      } else if (t.isJSXExpressionContainer(child)) {
        return child.expression;
      }
      return child;
    })
    .filter(x => x);

  return buildObjectExpression({
    __prerendered__: t.stringLiteral("component"),
    type: t.identifier(node.openingElement.name.name),
    props: t.objectExpression(getComponentProps(node.openingElement.attributes)),
    children: t.arrayExpression(children)
  });
};

//

const prerenderDom = node => {
  let segments = [];
  pushVanillaVdom(segments, node);

  segments = compress(segments);
  segments = expressionifyStringSegments(segments);

  return buildObjectExpression({
    __prerendered__: t.stringLiteral("dom"),
    segments: t.arrayExpression(segments)
  });
};

const getComponentProps = attributes =>
  attributes.map(attr => {
    if (t.isJSXSpreadAttribute(attr)) {
      return t.spreadProperty(attr.argument);
    }

    const { name, value } = attr;
    return t.objectProperty(
      t.identifier(name.name),
      t.isJSXExpressionContainer(value) ?
        value.expression :
        value
    );
  });

const pushVanillaVdom = (segments, node) => {
  const { openingElement, children, closingElement } = node;

  segments.push(`<${openingElement.name.name}`);
  pushAttributes(segments, openingElement.attributes);
  if (openingElement.selfClosing) {
    segments.push(`></${openingElement.name.name}>`);
    return;
  }

  segments.push(">");

  children.forEach(child => {
    if (t.isJSXText(child)) {
      const trimmed = child.value.trim();
      if (trimmed) { segments.push(htmlStringEscape(trimmed)); }
    } else if (t.isJSXExpressionContainer(child)) {
      segments.push(
        buildObjectExpression({
          __prerendered__: t.stringLiteral("expression"),
          expression: child.expression
        })
      );
    } else {
      segments.push(child);
    }
  });

  segments.push(`</${closingElement.name.name}>`);
};

const pushAttributes = (segments, attrs) => {
  attrs.forEach(attr => {
    const { name: { name }, value } = attr;

    if (!value) {
      // If no value is specified, this is a boolean HTML attribute that is set.
      segments.push(` ${name}`);
    } else if (t.isStringLiteral(value)) {
      // If the value is a string literal, it is pre-renderable.
      segments.push(` ${name}="${value.value}"`);
    } else {
      segments.push(
        buildObjectExpression({
          __prerendered__: t.stringLiteral("attr"),
          attrObj: buildObjectExpression({
            [name]: value.expression
          })
        })
      );
    }
  });
  segments.push(
    // This is used by the renderer to insert `data-react-id`s.
    t.numericLiteral(REACT_ID)
  );
};

const compress = segments => {
  return segments.reduce((memo, segment) => {
    const prevIdx = memo.length - 1;
    const prev = memo[prevIdx];

    if (typeof segment === "string" && typeof prev === "string") {
      memo[prevIdx] += segment;
    } else {
      memo.push(segment);
    }

    return memo;
  }, []);
};

const expressionifyStringSegments = segments => {
  return segments.map(segment =>
    typeof segment === "string" ?
      t.stringLiteral(segment) :
      segment
  );
};

const buildObjectExpression = obj => {
  return t.objectExpression(Object.keys(obj).map(key => {
    return t.objectProperty(
      t.identifier(key),
      obj[key]
    );
  }));
};
<commit_msg>Update `compress` helper to operate on StringLiterals instead of strings.<commit_after>const t = require("babel-types");

const { htmlStringEscape } = require("../render/util");
const { REACT_ID } = require("../symbols");

const _isVanillaDomTag = /^[a-z][a-z0-9\-]*$/;
const isVanillaDomTag = tag => _isVanillaDomTag.test(tag);

module.exports = () => ({
  manipulateOptions: (opts, parserOpts) => parserOpts.plugins.push("jsx"),
  visitor: {
    JSXElement: path => {
      const { node } = path;
      path.replaceWith(
        isVanillaDomTag(node.openingElement.name.name) ?
          prerenderDom(node) :
          prerenderComponent(node)
      );
    }
  }
});

// <Component />
const prerenderComponent = node => {
  const children = node.children
    .map(child => {
      if (t.isJSXText(child)) {
        const trimmed = child.value.trim();
        return trimmed && t.stringLiteral(trimmed);
      } else if (t.isJSXExpressionContainer(child)) {
        return child.expression;
      }
      return child;
    })
    .filter(x => x);

  return buildObjectExpression({
    __prerendered__: t.stringLiteral("component"),
    type: t.identifier(node.openingElement.name.name),
    props: t.objectExpression(getComponentProps(node.openingElement.attributes)),
    children: t.arrayExpression(children)
  });
};

//

const prerenderDom = node => {
  let segments = [];
  pushVanillaVdom(segments, node);

  segments = expressionifyStringSegments(segments);
  segments = compress(segments);

  return buildObjectExpression({
    __prerendered__: t.stringLiteral("dom"),
    segments: t.arrayExpression(segments)
  });
};

const getComponentProps = attributes =>
  attributes.map(attr => {
    if (t.isJSXSpreadAttribute(attr)) {
      return t.spreadProperty(attr.argument);
    }

    const { name, value } = attr;
    return t.objectProperty(
      t.identifier(name.name),
      t.isJSXExpressionContainer(value) ?
        value.expression :
        value
    );
  });

const pushVanillaVdom = (segments, node) => {
  const { openingElement, children, closingElement } = node;

  segments.push(`<${openingElement.name.name}`);
  pushAttributes(segments, openingElement.attributes);
  if (openingElement.selfClosing) {
    segments.push(`></${openingElement.name.name}>`);
    return;
  }

  segments.push(">");

  children.forEach(child => {
    if (t.isJSXText(child)) {
      const trimmed = child.value.trim();
      if (trimmed) { segments.push(htmlStringEscape(trimmed)); }
    } else if (t.isJSXExpressionContainer(child)) {
      segments.push(
        buildObjectExpression({
          __prerendered__: t.stringLiteral("expression"),
          expression: child.expression
        })
      );
    } else {
      segments.push(child);
    }
  });

  segments.push(`</${closingElement.name.name}>`);
};

const pushAttributes = (segments, attrs) => {
  attrs.forEach(attr => {
    const { name: { name }, value } = attr;

    if (!value) {
      // If no value is specified, this is a boolean HTML attribute that is set.
      segments.push(` ${name}`);
    } else if (t.isStringLiteral(value)) {
      // If the value is a string literal, it is pre-renderable.
      segments.push(` ${name}="${value.value}"`);
    } else {
      segments.push(
        buildObjectExpression({
          __prerendered__: t.stringLiteral("attr"),
          attrObj: buildObjectExpression({
            [name]: value.expression
          })
        })
      );
    }
  });
  segments.push(
    // This is used by the renderer to insert `data-react-id`s.
    t.numericLiteral(REACT_ID)
  );
};

const compress = elements => {
  return elements.reduce((memo, element) => {
    const prevIdx = memo.length - 1;
    const prev = memo[prevIdx];

    if (t.isStringLiteral(prev) && t.isStringLiteral(element)) {
      prev.value += element.value;
    } else {
      memo.push(element);
    }

    return memo;
  }, []);
};

const expressionifyStringSegments = segments => {
  return segments.map(segment =>
    typeof segment === "string" ?
      t.stringLiteral(segment) :
      segment
  );
};

const buildObjectExpression = obj => {
  return t.objectExpression(Object.keys(obj).map(key => {
    return t.objectProperty(
      t.identifier(key),
      obj[key]
    );
  }));
};
<|endoftext|>


<commit_before>var d3 = require('d3'),
    Tuple = require('vega-dataflow').Tuple,
    ChangeSet = require('vega-dataflow/src/ChangeSet'),
    Tuple = require('vega-dataflow/src/Tuple'),
    log = require('vega-logging'),
    Transform = require('./Transform');

function Force(graph) {
  Transform.prototype.init.call(this, graph);

  this._prev = null;
  this._setup = true;
  this._nodes  = [];
  this._links = [];
  this._layout = d3.layout.force();

  Transform.addParameters(this, {
    size: {type: 'array<value>', default: [500, 500]},
    bound: {type: 'value', default: true},

    links: {type: 'data'},
    linkStrength: {type: 'field|value', default: 1},
    linkDistance: {type: 'field|value', default: 20},
    charge: {type: 'field|value', default: -30},
    chargeDistance: {type: 'field|value', default: Infinity},
    friction: {type: 'value', default: 0.9},
    theta: {type: 'value', default: 0.8},
    gravity: {type: 'value', default: 0.1},
    alpha: {type: 'value', default: 0.1},
    iterations: {type: 'value', default: 500},

    interactive: {type: 'value', default: false},
    active: {type: 'value', default: this._prev},
    fixed: {type: 'data'}
  });

  this._output = {
    'x': 'layout_x',
    'y': 'layout_y',
    'px': 'layout_px',
    'py': 'layout_py',
    'fixed': 'layout_fixed',
    'weight': 'layout_weight',
    'source': '_source',
    'target': '_target'
  };

  return this.mutates(true);
}

var prototype = (Force.prototype = Object.create(Transform.prototype));
prototype.constructor = Force;

prototype.transform = function(nodeInput) {
  log.debug(nodeInput, ['force']);

  // get variables
  var interactive = this.param('interactive'),
      linkInput = this.param('links').source.last(),
      active = this.param('active'),
      output = this._output,
      layout = this._layout,
      nodes = this._nodes,
      links = this._links;

  // configure nodes, links and layout
  // TODO what if interactive or charge/linkDistance/linkStrength has changed?
  if (this._setup || nodeInput.add.length || linkInput.add.length) {
    this.configure(nodeInput, linkInput, interactive);
    this._setup = false;
  }

  // run batch layout
  if (!interactive) {
    var iterations = this.param('iterations');
    for (var i=0; i<iterations; ++i) layout.tick();
    layout.stop();
  }

  // update node positions
  this.update(active);

  // update active node status
  if (active !== this._prev) {
    if (active && active.update) {
      layout.alpha(this.param('alpha')); // re-start layout
    }
    this._prev = active;
  }

  // process removed nodes or edges
  if (nodeInput.rem.length) {
    layout.nodes(this._nodes = Tuple.idFilter(nodes, nodeInput.rem));
  }
  if (linkInput.rem.length) {
    layout.links(this._links = Tuple.idFilter(links, linkInput.rem));
  }

  // return changeset
  nodeInput.fields[output.x] = 1;
  nodeInput.fields[output.y] = 1;
  return nodeInput;
};

prototype.configure = function(nodeInput, linkInput, interactive) {
  var force = this,
      graph = this._graph,
      output = this._output,
      layout = this._layout,
      nodes = this._nodes,
      links = this._links,
      a, i, x, link;

  // process added nodes
  for (a=nodeInput.add, i=0; i<a.length; ++i) {
    nodes.push({tuple: a[i]});
  }

  // process added edges
  for (a=linkInput.add, i=0; i<a.length; ++i) {
    x = a[i];
    link = {
      tuple:  x,
      source: nodes[x.source],
      target: nodes[x.target]
    };
    Tuple.set(x, output.source, link.source.tuple);
    Tuple.set(x, output.target, link.target.tuple);
    links.push(link);
  }

  // TODO process 'mod' of edge source or target?

  // setup handler for force layout tick events
  var tickHandler = !interactive ? null : function() {
    // re-schedule the transform, force reflow
    graph.propagate(ChangeSet.create(null, true), force);

    // hard-code propagation to links
    // TODO: dataflow graph should propagate automatically
    var lnode = force.param('links').source._pipeline[0];
    graph.propagate(ChangeSet.create(null, true), lnode);
  };

  // configure layout
  layout
    .size(this.param('size'))
    .linkStrength(this.param('linkStrength'))
    .linkDistance(this.param('linkDistance'))
    .chargeDistance(this.param('chargeDistance'))
    .charge(this.param('charge'))
    .theta(this.param('theta'))
    .gravity(this.param('gravity'))
    .friction(this.param('friction'))
    .nodes(nodes)
    .links(links)
    .on('tick', tickHandler)
    .start().alpha(this.param('alpha'));
};

prototype.update = function(active) {
  var output = this._output,
      bound = this.param('bound'),
      fixed = this.param('fixed'),
      size = this.param('size'),
      nodes = this._nodes,
      lut = {}, id, i, n, t, x, y;

  if (fixed) {
    fixed = fixed.source.values();
    for (i=0, n=fixed.length; i<n; ++i) {
      lut[fixed[i].id] = 1;
    }
  }

  for (i=0; i<nodes.length; ++i) {
    n = nodes[i];
    t = n.tuple;
    id = t._id;

    if (active && active.id === id) {
      n.fixed = 1;
      if (active.update) {
        n.x = n.px = active.x;
        n.y = n.py = active.y;
      }
    } else {
      n.fixed = lut[id] || 0;
    }

    x = bound ? Math.max(0, Math.min(n.x, size[0])) : n.x;
    y = bound ? Math.max(0, Math.min(n.y, size[1])) : n.y;
    Tuple.set(t, output.x, x);
    Tuple.set(t, output.y, y);
  }
};

module.exports = Force;

Force.schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Force transform",
  "description": "Performs force-directed layout for network data.",
  "type": "object",
  "properties": {
    "type": {"enum": ["force"]},
    "size": {
      "description": "The dimensions [width, height] of this force layout.",
      "oneOf": [
        {
          "type": "array",
          "minItems": 2,
          "maxItems": 2,
          "items": {"oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}]}
        },
        {"$ref": "#/refs/signal"}
      ],

      "default": [500, 500]
    },
    "links": {
      "type": "string",
      "description": "The name of the link (edge) data set."
    },
    "linkDistance": {
      "description": "Determines the length of edges, in pixels.",
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "default": 20
    },
    "linkStrength": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "Determines the tension of edges (the spring constant).",
      "default": 1
    },
    "charge": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "The strength of the charge each node exerts.",
      "default": -30
    },
    "chargeDistance": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "The maximum distance over which charge forces are applied.",
      "default": Infinity
    },
    "iterations": {
      "description": "The number of iterations to run the force directed layout.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 500
    },
    "friction": {
      "description": "The strength of the friction force used to stabilize the layout.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.9
    },
    "theta": {
      "description": "The theta parameter for the Barnes-Hut algorithm, which is used to compute charge forces between nodes.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.8
    },
    "gravity": {
      "description": "The strength of the pseudo-gravity force that pulls nodes towards the center of the layout area.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.1
    },
    "alpha": {
      "description": "A \"temperature\" parameter that determines how much node positions are adjusted at each step.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.1
    },
    "output": {
      "type": "object",
      "description": "Rename the output data fields",
      "properties": {
        "x": {"type": "string", "default": "layout_x"},
        "y": {"type": "string", "default": "layout_y"},
        "source": {"type": "string", "default": "_source"},
        "target": {"type": "string", "default": "_target"}
      },
      "additionalProperties": false
    }
  },
  "additionalProperties": false,
  "required": ["type", "links"]
};<commit_msg>Add missing ChangeSet require.<commit_after>var d3 = require('d3'),
    df = require('vega-dataflow'),
    Tuple = df.Tuple,
    ChangeSet = df.ChangeSet,
    log = require('vega-logging'),
    Transform = require('./Transform');

function Force(graph) {
  Transform.prototype.init.call(this, graph);

  this._prev = null;
  this._setup = true;
  this._nodes  = [];
  this._links = [];
  this._layout = d3.layout.force();

  Transform.addParameters(this, {
    size: {type: 'array<value>', default: [500, 500]},
    bound: {type: 'value', default: true},

    links: {type: 'data'},
    linkStrength: {type: 'field|value', default: 1},
    linkDistance: {type: 'field|value', default: 20},
    charge: {type: 'field|value', default: -30},
    chargeDistance: {type: 'field|value', default: Infinity},
    friction: {type: 'value', default: 0.9},
    theta: {type: 'value', default: 0.8},
    gravity: {type: 'value', default: 0.1},
    alpha: {type: 'value', default: 0.1},
    iterations: {type: 'value', default: 500},

    interactive: {type: 'value', default: false},
    active: {type: 'value', default: this._prev},
    fixed: {type: 'data'}
  });

  this._output = {
    'x': 'layout_x',
    'y': 'layout_y',
    'px': 'layout_px',
    'py': 'layout_py',
    'fixed': 'layout_fixed',
    'weight': 'layout_weight',
    'source': '_source',
    'target': '_target'
  };

  return this.mutates(true);
}

var prototype = (Force.prototype = Object.create(Transform.prototype));
prototype.constructor = Force;

prototype.transform = function(nodeInput) {
  log.debug(nodeInput, ['force']);

  // get variables
  var interactive = this.param('interactive'),
      linkInput = this.param('links').source.last(),
      active = this.param('active'),
      output = this._output,
      layout = this._layout,
      nodes = this._nodes,
      links = this._links;

  // configure nodes, links and layout
  // TODO what if interactive or charge/linkDistance/linkStrength has changed?
  if (this._setup || nodeInput.add.length || linkInput.add.length) {
    this.configure(nodeInput, linkInput, interactive);
    this._setup = false;
  }

  // run batch layout
  if (!interactive) {
    var iterations = this.param('iterations');
    for (var i=0; i<iterations; ++i) layout.tick();
    layout.stop();
  }

  // update node positions
  this.update(active);

  // update active node status
  if (active !== this._prev) {
    if (active && active.update) {
      layout.alpha(this.param('alpha')); // re-start layout
    }
    this._prev = active;
  }

  // process removed nodes or edges
  if (nodeInput.rem.length) {
    layout.nodes(this._nodes = Tuple.idFilter(nodes, nodeInput.rem));
  }
  if (linkInput.rem.length) {
    layout.links(this._links = Tuple.idFilter(links, linkInput.rem));
  }

  // return changeset
  nodeInput.fields[output.x] = 1;
  nodeInput.fields[output.y] = 1;
  return nodeInput;
};

prototype.configure = function(nodeInput, linkInput, interactive) {
  var force = this,
      graph = this._graph,
      output = this._output,
      layout = this._layout,
      nodes = this._nodes,
      links = this._links,
      a, i, x, link;

  // process added nodes
  for (a=nodeInput.add, i=0; i<a.length; ++i) {
    nodes.push({tuple: a[i]});
  }

  // process added edges
  for (a=linkInput.add, i=0; i<a.length; ++i) {
    x = a[i];
    link = {
      tuple:  x,
      source: nodes[x.source],
      target: nodes[x.target]
    };
    Tuple.set(x, output.source, link.source.tuple);
    Tuple.set(x, output.target, link.target.tuple);
    links.push(link);
  }

  // TODO process 'mod' of edge source or target?

  // setup handler for force layout tick events
  var tickHandler = !interactive ? null : function() {
    // re-schedule the transform, force reflow
    graph.propagate(ChangeSet.create(null, true), force);

    // hard-code propagation to links
    // TODO: dataflow graph should propagate automatically
    var lnode = force.param('links').source._pipeline[0];
    graph.propagate(ChangeSet.create(null, true), lnode);
  };

  // configure layout
  layout
    .size(this.param('size'))
    .linkStrength(this.param('linkStrength'))
    .linkDistance(this.param('linkDistance'))
    .chargeDistance(this.param('chargeDistance'))
    .charge(this.param('charge'))
    .theta(this.param('theta'))
    .gravity(this.param('gravity'))
    .friction(this.param('friction'))
    .nodes(nodes)
    .links(links)
    .on('tick', tickHandler)
    .start().alpha(this.param('alpha'));
};

prototype.update = function(active) {
  var output = this._output,
      bound = this.param('bound'),
      fixed = this.param('fixed'),
      size = this.param('size'),
      nodes = this._nodes,
      lut = {}, id, i, n, t, x, y;

  if (fixed) {
    fixed = fixed.source.values();
    for (i=0, n=fixed.length; i<n; ++i) {
      lut[fixed[i].id] = 1;
    }
  }

  for (i=0; i<nodes.length; ++i) {
    n = nodes[i];
    t = n.tuple;
    id = t._id;

    if (active && active.id === id) {
      n.fixed = 1;
      if (active.update) {
        n.x = n.px = active.x;
        n.y = n.py = active.y;
      }
    } else {
      n.fixed = lut[id] || 0;
    }

    x = bound ? Math.max(0, Math.min(n.x, size[0])) : n.x;
    y = bound ? Math.max(0, Math.min(n.y, size[1])) : n.y;
    Tuple.set(t, output.x, x);
    Tuple.set(t, output.y, y);
  }
};

module.exports = Force;

Force.schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Force transform",
  "description": "Performs force-directed layout for network data.",
  "type": "object",
  "properties": {
    "type": {"enum": ["force"]},
    "size": {
      "description": "The dimensions [width, height] of this force layout.",
      "oneOf": [
        {
          "type": "array",
          "minItems": 2,
          "maxItems": 2,
          "items": {"oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}]}
        },
        {"$ref": "#/refs/signal"}
      ],

      "default": [500, 500]
    },
    "links": {
      "type": "string",
      "description": "The name of the link (edge) data set."
    },
    "linkDistance": {
      "description": "Determines the length of edges, in pixels.",
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "default": 20
    },
    "linkStrength": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "Determines the tension of edges (the spring constant).",
      "default": 1
    },
    "charge": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "The strength of the charge each node exerts.",
      "default": -30
    },
    "chargeDistance": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "The maximum distance over which charge forces are applied.",
      "default": Infinity
    },
    "iterations": {
      "description": "The number of iterations to run the force directed layout.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 500
    },
    "friction": {
      "description": "The strength of the friction force used to stabilize the layout.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.9
    },
    "theta": {
      "description": "The theta parameter for the Barnes-Hut algorithm, which is used to compute charge forces between nodes.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.8
    },
    "gravity": {
      "description": "The strength of the pseudo-gravity force that pulls nodes towards the center of the layout area.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.1
    },
    "alpha": {
      "description": "A \"temperature\" parameter that determines how much node positions are adjusted at each step.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.1
    },
    "output": {
      "type": "object",
      "description": "Rename the output data fields",
      "properties": {
        "x": {"type": "string", "default": "layout_x"},
        "y": {"type": "string", "default": "layout_y"},
        "source": {"type": "string", "default": "_source"},
        "target": {"type": "string", "default": "_target"}
      },
      "additionalProperties": false
    }
  },
  "additionalProperties": false,
  "required": ["type", "links"]
};<|endoftext|>


<commit_before>'use strict';

angular.module('angWeatherAppApp')
  .controller('LoginCtrl', function ($scope, $http, setting) {
  	var url = setting.apiurl + '/verify_credentials';
  	$scope.submit = function(){
  		var sendData = {
  			"usernamename": $scope.username,
  			"password": $scope.password
  		};
  		$http.post(url, sendData)
  		.success(function(data){
  			console.log(data);
  		})
  		.error(function(data) {
        	console.log('Error: ' + data);
      });
  	}
  });
<commit_msg>fixed name for json object on login<commit_after>'use strict';

angular.module('angWeatherAppApp')
  .controller('LoginCtrl', function ($scope, $http, setting) {
  	var url = setting.apiurl + "/verify_credentials";
  	$scope.submit = function(){
  		var sendData = {
  			"username": $scope.username,
  			"password": $scope.password
  		};

  		$http.post(url, sendData)
  		.success(function(data){
  			console.log(data);
  		})
  		.error(function(data) {
        	console.log('Error: ' + data);
      });
  	}
  });
<|endoftext|>


<commit_before>
NGApp.controller('DefaultCtrl', function ($rootScope, $scope, $http, $location, $routeParams, MainNavigationService, AccountService) {

	var redirect = function() {
		// redirect to login if there is no user
		if (!AccountService.user || !AccountService.user.id_admin) {
			MainNavigationService.link('/login');
			return;
		}

		var id_order = $location.path().replace( '/', '' );
		if( !isNaN( parseInt( id_order ) ) ){
			MainNavigationService.link('/drivers/order/' + id_order);
		} else {
			if (App.isPhoneGap && !$.totalStorage('isDriverWelcomeSetup')) {
				setTimeout(function(){
					MainNavigationService.link('/drivers/welcome');
					$rootScope.$apply();
				},100);
				return;
			}

			if (AccountService.user.permissions.GLOBAL) {
				MainNavigationService.link('/home');
			} else if (AccountService.isRestaurant) {
				MainNavigationService.link('/restaurant/order/placement/dashboard');
			} else if (AccountService.isDriver) {
				MainNavigationService.link('/drivers/orders');
			} else {
				MainNavigationService.link('/login');
			}
		}
	};

	// wait for login to complete
	if (!AccountService.init) {
		$scope.$on('userAuth', redirect);
	} else {
		redirect()
	}
});

NGApp.controller('HomeCtrl', function ( $scope) {} );

NGApp.controller('MainHeaderCtrl', function ( $scope) {} );

NGApp.controller('SideMenuCtrl', function ($scope, $rootScope, AccountService) {
	$scope.setupPermissions = function() {}
	$scope.menu = {};

	//$scope.menu.toggle = $.totalStorage('menu.toggle');

	var fixToggle = function() {
		if (!AccountService.user || !AccountService.user.permissions) {
			$scope.menu.toggle = '';
		} else if (AccountService.user.permissions.GLOBAL) {
			$scope.menu.toggle = 'admin';
		} else if (AccountService.isDriver) {
			$scope.menu.toggle = 'driver';
		} else if(AccountService.isMarketingRep) {
			$scope.menu.toggle = 'marketing-rep';
		}
	};

	$rootScope.$on('userAuth', function(e, data) {
		fixToggle();
	});

	//$.totalStorage('menu.toggle', $scope.menu.toggle);

	/*
	$scope.$watch('menu.toggle', function() {
		$.totalStorage('menu.toggle', $scope.menu.toggle);
	});
	*/

	fixToggle();
});

NGApp.controller('InfoCtrl', function ($scope) {

});

NGApp.controller('LegalCtrl', function ($scope) {
	var join = 'moc.nottubhcnurc@nioj'.split('').reverse().join('');
	var goodbye = 'moc.nottubhcnurc@eybdoog'.split('').reverse().join('');
	$scope.join = join;
	$scope.goodbye = goodbye;
});

NGApp.controller('LoginCtrl', function($rootScope, $scope, AccountService, MainNavigationService) {

	$scope.loggingIn = false;
	var l;
	setTimeout(function(){
		l = Ladda.create($('.button-login .ladda-button').get(0));
	},700);
	$scope.newuser = !$.totalStorage('hasLoggedIn');
	$scope.login = function() {
		if( !$scope.username ){
			App.alert('Please enter your username', '', false, function() {
				if (!App.isPhoneGap) {
					$rootScope.focus('[name="username"]');
				}
			});
			return;
		}
		if( !$scope.password ){
			App.alert('Please enter your password', '', false, function() {
				if (!App.isPhoneGap) {
					$rootScope.focus('[name="password"]');
				}
			});
			return;
		}
		$scope.loggingIn = true;
		l.start();
		AccountService.login( $scope.username, $scope.password, function( status ) {
			if( status ){
				MainNavigationService.link( '/' );
			} else {
				$scope.error = true;
				if (!App.isPhoneGap) {
					$rootScope.focus('[name="username"]');
				}
			}
			$scope.loggingIn = false;
			l.stop();
		} );
	}

	// needs to be updated when the html is
	$scope.welcome = Math.floor((Math.random() * 8) + 1);
	console.debug('welcome message', $scope.welcome);

});

NGApp.controller( 'ProfileCtrl', function ($scope) {});

NGApp.controller( 'ProfilePasswordCtrl', function ($scope, ProfileService) {

	$scope.password = {};

	$scope.isSaving = false;

	$scope.save = function(){
		if( $scope.form.$invalid ){
			$scope.submitted = true;
			$scope.isSaving = false;
			return;
		}

		ProfileService.change_password( $scope.password, function( json ){
			if( json.error ){
				App.alert( 'Error saving: ' + json.error , 'error' );
			} else {
				App.alert( 'Your password was changed!' );
				$scope.submitted = false;
				$scope.isSaving = false;
				$scope.password = {};
			}
		} );
	}
});

NGApp.controller( 'NotificationAlertCtrl', function ($scope, $rootScope ) {
	$rootScope.$on('notificationAlert', function(e, title, message, fn) {

		if (!App.isPhoneGap) {
			$(':focus').blur();
		}

		var complete = function() {
			$rootScope.closePopup();
			if (typeof fn === 'function') {
				fn();
			}
		};

		if ($scope.$$phase) {
			$scope.alertTitle = title;
			$scope.message = message;
			$scope.complete = complete;
			App.dialog.show('.notification-alert-container');

		} else {
			$rootScope.$apply(function(scope) {
				scope.alertTitle = title;
				scope.message = message;
				$scope.complete = complete;
				App.dialog.show('.notification-alert-container');
			});
		}
	});
});

NGApp.controller( 'NotificationConfirmCtrl', function ($scope, $rootScope ) {
	$rootScope.$on('notificationConfirm', function(e, title, message, success, fail, buttons) {

		$(':focus').blur();

		var complete = function() {
			$rootScope.closePopup();
			if (typeof success === 'function') {
				success();
			}
		};

		var cancel = function() {
			$rootScope.closePopup();
			if (typeof fail === 'function') {
				fail();
			}
		};

		if ($scope.$$phase) {
			$scope.alertTitle = title;
			$scope.message = message;
			$scope.complete = complete;
			$scope.cancel = cancel;
			$scope.buttonOk = 'Ok';
			$scope.buttonCancel = 'Cancel';
			if( buttons ){
				buttons = buttons.split(',');
				if( buttons.length == 2 ){
					$scope.buttonOk = buttons[0];
					$scope.buttonCancel = buttons[1];
				}
			}
			App.dialog.show('.notification-confirm-container');

		} else {
			$rootScope.$apply(function(scope) {
				scope.alertTitle = title;
				scope.message = message;
				scope.complete = complete;
				scope.cancel = cancel;
				scope.buttonOk = 'Ok';
				scope.buttonCancel = 'Cancel';
				if( buttons ){
					buttons = buttons.split(',');
					if( buttons.length == 2 ){
						scope.buttonOk = buttons[0];
						scope.buttonCancel = buttons[1];
					}
				}
				App.dialog.show('.notification-confirm-container');
			});
		}
	});
});

NGApp.controller( 'CallText', function ($scope, $rootScope) {

	$rootScope.$on('callText', function(e, num) {
		openModal( num );
	});

	$rootScope.$on('textNumer', function(e, num) {
		openModal( num );
		$scope.hideSMSBox = false;
		$scope.complete = function( json ){
			if( json.success ){
				setTimeout(function() { App.alert( 'Text messages sent!' ); }, 10 );
			} else {
				if( json.error ){
					setTimeout(function() { App.alert( json.error ); }, 10 );
				}
			}
		};
	});

	var openModal = function( num ){

		$(':focus').blur();

		if( angular.isArray( num ) ){
			$scope.listOfNumbers = true;
		} else {
			$scope.listOfNumbers = false;
		}

		$scope.number = num;
		$scope.complete = $rootScope.closePopup;
		App.dialog.show('.notification-call-text-container');

		$scope.hideCallBox = true;
		$scope.hideSMSBox = true;
	}

	// variables to controll the template 'assets/view/support-phone.html'
	// when it is called by a modal
	$scope.isModal = true;
	$scope.hideCallBox = true;
	$scope.hideSMSBox = true;

});

NGApp.filter('capitalize', function() {
	return function(input, scope) {
		if (input == null) {
			return null;
		}
		if (input!=null) {
			input = input.toLowerCase();
		}
		return input.substring(0,1).toUpperCase()+input.substring(1);
	}
});
<commit_msg>new cockpit app: fix buttons on login screen #6394<commit_after>
NGApp.controller('DefaultCtrl', function ($rootScope, $scope, $http, $location, $routeParams, MainNavigationService, AccountService) {

	var redirect = function() {
		// redirect to login if there is no user
		if (!AccountService.user || !AccountService.user.id_admin) {
			MainNavigationService.link('/login');
			return;
		}

		var id_order = $location.path().replace( '/', '' );
		if( !isNaN( parseInt( id_order ) ) ){
			MainNavigationService.link('/drivers/order/' + id_order);
		} else {
			if (App.isPhoneGap && !$.totalStorage('isDriverWelcomeSetup')) {
				setTimeout(function(){
					MainNavigationService.link('/drivers/welcome');
					$rootScope.$apply();
				},100);
				return;
			}

			if (AccountService.user.permissions.GLOBAL) {
				MainNavigationService.link('/home');
			} else if (AccountService.isRestaurant) {
				MainNavigationService.link('/restaurant/order/placement/dashboard');
			} else if (AccountService.isDriver) {
				MainNavigationService.link('/drivers/orders');
			} else {
				MainNavigationService.link('/login');
			}
		}
	};

	// wait for login to complete
	if (!AccountService.init) {
		$scope.$on('userAuth', redirect);
	} else {
		redirect()
	}
});

NGApp.controller('HomeCtrl', function ( $scope) {} );

NGApp.controller('MainHeaderCtrl', function ( $scope) {} );

NGApp.controller('SideMenuCtrl', function ($scope, $rootScope, AccountService) {
	$scope.setupPermissions = function() {}
	$scope.menu = {};

	//$scope.menu.toggle = $.totalStorage('menu.toggle');

	var fixToggle = function() {
		if (!AccountService.user || !AccountService.user.permissions) {
			$scope.menu.toggle = '';
		} else if (AccountService.user.permissions.GLOBAL) {
			$scope.menu.toggle = 'admin';
		} else if (AccountService.isDriver) {
			$scope.menu.toggle = 'driver';
		} else if(AccountService.isMarketingRep) {
			$scope.menu.toggle = 'marketing-rep';
		}
	};

	$rootScope.$on('userAuth', function(e, data) {
		fixToggle();
	});

	//$.totalStorage('menu.toggle', $scope.menu.toggle);

	/*
	$scope.$watch('menu.toggle', function() {
		$.totalStorage('menu.toggle', $scope.menu.toggle);
	});
	*/

	fixToggle();
});

NGApp.controller('InfoCtrl', function ($scope) {

});

NGApp.controller('LegalCtrl', function ($scope) {
	var join = 'moc.nottubhcnurc@nioj'.split('').reverse().join('');
	var goodbye = 'moc.nottubhcnurc@eybdoog'.split('').reverse().join('');
	$scope.join = join;
	$scope.goodbye = goodbye;
});

NGApp.controller('LoginCtrl', function($rootScope, $scope, AccountService, MainNavigationService) {

	$rootScope.hasBack = false;

	$scope.loggingIn = false;

	var l;
	setTimeout(function(){
		l = Ladda.create($('.button-login .ladda-button').get(0));
	},700);
	$scope.newuser = !$.totalStorage('hasLoggedIn');

	$scope.login = function() {
		if( !$scope.username ){
			App.alert('Please enter your username', '', false, function() {
				if (!App.isPhoneGap) {
					$rootScope.focus('[name="username"]');
				}
			});
			return;
		}
		if( !$scope.password ){
			App.alert('Please enter your password', '', false, function() {
				if (!App.isPhoneGap) {
					$rootScope.focus('[name="password"]');
				}
			});
			return;
		}
		$scope.loggingIn = true;
		l.start();
		AccountService.login( $scope.username, $scope.password, function( status ) {
			if( status ){
				MainNavigationService.link( '/' );
			} else {
				$scope.error = true;
				if (!App.isPhoneGap) {
					$rootScope.focus('[name="username"]');
				}
			}
			$scope.loggingIn = false;
			l.stop();
		} );
	}

	// needs to be updated when the html is
	$scope.welcome = Math.floor((Math.random() * 8) + 1);
	console.debug('welcome message', $scope.welcome);

});

NGApp.controller( 'ProfileCtrl', function ($scope) {});

NGApp.controller( 'ProfilePasswordCtrl', function ($scope, ProfileService) {

	$scope.password = {};

	$scope.isSaving = false;

	$scope.save = function(){
		if( $scope.form.$invalid ){
			$scope.submitted = true;
			$scope.isSaving = false;
			return;
		}

		ProfileService.change_password( $scope.password, function( json ){
			if( json.error ){
				App.alert( 'Error saving: ' + json.error , 'error' );
			} else {
				App.alert( 'Your password was changed!' );
				$scope.submitted = false;
				$scope.isSaving = false;
				$scope.password = {};
			}
		} );
	}
});

NGApp.controller( 'NotificationAlertCtrl', function ($scope, $rootScope ) {
	$rootScope.$on('notificationAlert', function(e, title, message, fn) {

		if (!App.isPhoneGap) {
			$(':focus').blur();
		}

		var complete = function() {
			$rootScope.closePopup();
			if (typeof fn === 'function') {
				fn();
			}
		};

		if ($scope.$$phase) {
			$scope.alertTitle = title;
			$scope.message = message;
			$scope.complete = complete;
			App.dialog.show('.notification-alert-container');

		} else {
			$rootScope.$apply(function(scope) {
				scope.alertTitle = title;
				scope.message = message;
				$scope.complete = complete;
				App.dialog.show('.notification-alert-container');
			});
		}
	});
});

NGApp.controller( 'NotificationConfirmCtrl', function ($scope, $rootScope ) {
	$rootScope.$on('notificationConfirm', function(e, title, message, success, fail, buttons) {

		$(':focus').blur();

		var complete = function() {
			$rootScope.closePopup();
			if (typeof success === 'function') {
				success();
			}
		};

		var cancel = function() {
			$rootScope.closePopup();
			if (typeof fail === 'function') {
				fail();
			}
		};

		if ($scope.$$phase) {
			$scope.alertTitle = title;
			$scope.message = message;
			$scope.complete = complete;
			$scope.cancel = cancel;
			$scope.buttonOk = 'Ok';
			$scope.buttonCancel = 'Cancel';
			if( buttons ){
				buttons = buttons.split(',');
				if( buttons.length == 2 ){
					$scope.buttonOk = buttons[0];
					$scope.buttonCancel = buttons[1];
				}
			}
			App.dialog.show('.notification-confirm-container');

		} else {
			$rootScope.$apply(function(scope) {
				scope.alertTitle = title;
				scope.message = message;
				scope.complete = complete;
				scope.cancel = cancel;
				scope.buttonOk = 'Ok';
				scope.buttonCancel = 'Cancel';
				if( buttons ){
					buttons = buttons.split(',');
					if( buttons.length == 2 ){
						scope.buttonOk = buttons[0];
						scope.buttonCancel = buttons[1];
					}
				}
				App.dialog.show('.notification-confirm-container');
			});
		}
	});
});

NGApp.controller( 'CallText', function ($scope, $rootScope) {

	$rootScope.$on('callText', function(e, num) {
		openModal( num );
	});

	$rootScope.$on('textNumer', function(e, num) {
		openModal( num );
		$scope.hideSMSBox = false;
		$scope.complete = function( json ){
			if( json.success ){
				setTimeout(function() { App.alert( 'Text messages sent!' ); }, 10 );
			} else {
				if( json.error ){
					setTimeout(function() { App.alert( json.error ); }, 10 );
				}
			}
		};
	});

	var openModal = function( num ){

		$(':focus').blur();

		if( angular.isArray( num ) ){
			$scope.listOfNumbers = true;
		} else {
			$scope.listOfNumbers = false;
		}

		$scope.number = num;
		$scope.complete = $rootScope.closePopup;
		App.dialog.show('.notification-call-text-container');

		$scope.hideCallBox = true;
		$scope.hideSMSBox = true;
	}

	// variables to controll the template 'assets/view/support-phone.html'
	// when it is called by a modal
	$scope.isModal = true;
	$scope.hideCallBox = true;
	$scope.hideSMSBox = true;

});

NGApp.filter('capitalize', function() {
	return function(input, scope) {
		if (input == null) {
			return null;
		}
		if (input!=null) {
			input = input.toLowerCase();
		}
		return input.substring(0,1).toUpperCase()+input.substring(1);
	}
});
<|endoftext|>


<commit_before>var total_tils = 0;

document.querySelectorAll('h3').forEach(element => {
    count_tils(element);
});

function count_tils(element) {
    var sibling;

    if (sibling = element.nextElementSibling) {
        var list = sibling.querySelectorAll('li');
        if (list.length > 0) {
            var text_content = element.textContent + ' (' + list.length + ' tils)';
            element.textContent = text_content;

            total_tils += list.length;
        }
    }
}

var total = document.getElementById('header-1');
text_content = total.textContent + ' (' + total_tils + ' tils)';
total.textContent = text_content;
<commit_msg>Added total to sidebar<commit_after>var total_tils = 0;

document.querySelectorAll('h3').forEach(element => {
    count_tils(element);
});

function count_tils(element) {
    var sibling;

    if (sibling = element.nextElementSibling) {
        var list = sibling.querySelectorAll('li');
        if (list.length > 0) {
            var text_content = element.textContent + ' (' + list.length + ' tils)';
            element.textContent = text_content;

            total_tils += list.length;
        }
    }
}

const count = document.createElement('p');
count.textContent = 'A collection of ' + total_tils + ' in total.';

var sidebar = document.getElementById('sidebar');
sidebar.appendChild(count);
<|endoftext|>


<commit_before>
define (['jquery', 'facebook', 'LastFMProxy'], function ($, facebook, LastFMProxy) {

    // User likes
    var artists = [];

    // Stats object for every artist (associative array)
    var artistStats = [];

    function getArtists(callback) {
        FB.init({
            appId      : '1468034890110746',
            xfbml      : true,
            status     : true,
            cookie     : true,
            version    : 'v2.1'
        });

        FB.login(function () {
            FB.api(
                "/me/music",
                function (response) {
                  if (!response.data) {
                      console.log('Error getting user music');
                  } else {
                      callback(response.data)
                  }
            });
        }, {scope: 'user_likes'});
    }

    // Get stats for every artists;
    getArtists(function (artists) {

        a
        // If no artist likes
        if (artists.length === 0) {
            // TO DO: show message
            alert('No artists');
            return;
        }

        // Get stats one by one
        artists.forEach(function (artist) {
            artistStats[artist] = LastFMProxy.getStats(artist.name);
        });
    });

    // DOM callbacks
    $(document).ready(function () {

        // Animate progress bar
        $('#appProgress').css('width', '33%');

        // Animate dots
        setInterval(function () {
            switch ($('#loading').text()) {
                case '':
                    $('#loading').text('.');
                    break;
                case '.':
                    $('#loading').text('..');
                    break;
                case '..':
                    $('#loading').text('...');
                    break;
                case '...':
                    $('#loading').text('');
                    break;
            }
        }, 500);

    });
});<commit_msg>JS rest ajax<commit_after>
define (['jquery', 'facebook', 'LastFMProxy'], function ($, facebook, LastFMProxy) {

    // User likes
    var artists = [];

    // Stats object for every artist (associative array)
    var artistStats = [];

    function getArtists(callback) {
        FB.init({
            appId      : '1468034890110746',
            xfbml      : true,
            status     : true,
            cookie     : true,
            version    : 'v2.1'
        });

        FB.login(function () {
            FB.api(
                "/me/music",
                function (response) {
                  if (!response.data) {
                      console.log('Error getting user music');
                  } else {
                      callback(response.data)
                  }
            });
        }, {scope: 'user_likes'});
    }

    // Get stats for every artists;
    getArtists(function (artists) {

        // If no artist likes
        if (artists.length === 0) {
            // TO DO: show message
            alert('No artists');
            return;
        }

        // Get stats one by one
        artists.forEach(function (artist) {
            artistStats[artist] = LastFMProxy.getStats(artist.name);
        });
    });

    // DOM callbacks
    $(document).ready(function () {

        // Animate progress bar
        $('#appProgress').css('width', '33%');

        // Animate dots
        setInterval(function () {
            switch ($('#loading').text()) {
                case '':
                    $('#loading').text('.');
                    break;
                case '.':
                    $('#loading').text('..');
                    break;
                case '..':
                    $('#loading').text('...');
                    break;
                case '...':
                    $('#loading').text('');
                    break;
            }
        }, 500);

    });
});<|endoftext|>


<commit_before><commit_msg>deleteing old samples.js<commit_after><|endoftext|>