<commit_before>// sudo udevadm control --reload-rules
// to refresh the port allocation

var events = require('events');
var eventEmitter = new events.EventEmitter();
var TLFolder="/home/pi/Documents/TL/"

var serPort = "/dev/ttyACM0";
var serBaud = 38400;
var serverPort = 999;

var LogR = 0;
var TelemetryFN = "";
var prevTel="";
var prevPitch="";

var SEPARATOR = ","
var version = "0.2";

var ArduHeader;
var ArduRead = {};

//--------------------------------------

var express = require('/usr/local/lib/node_modules/express');
var app = express();
var http = require('http').Server(app);
var io = require('/usr/local/lib/node_modules/socket.io')(http);
var fs = require('/usr/local/lib/node_modules/safefs');
var piblaster = require('/usr/local/lib/node_modules/pi-blaster.js');

var sys = require('sys');
var exec = require('child_process').exec;

var imgWidth = 2592; // Max = 2592
var imgHeight = 1944; //# Max = 1944
var TLInterval = 10000;

app.use(express.static(__dirname + '/public'));
// Routers
{
app.get('/', function(req, res){
  res.sendFile(__dirname + '/public/index.html');
  res.end;
});

app.get('/vj', function(req, res) {
  res.sendFile(__dirname + '/public/robotj.html');
  res.end;
});

app.get('/REBOOT', function(req, res) {
  var postData = req.url;
  function puts(error, stdout, stderr) { sys.puts(stdout) }
  exec('sudo reboot now');
  sockets.emit('Info', "Rebooting")
  //console.log(postData);
  res.end;
});

}

// Logging middleware

var mkdirSync = function (path) {
  try {
    fs.mkdirSync(path);
  } catch(e) {
    if ( e.code != 'EEXIST' ) throw e;
  }
}

io.on('connection', function(socket){
  var myDate = new Date();
  socket.emit('Info', 'Connected ' + myDate.getHours() + ':' +   myDate.getMinutes() + ':' +   myDate.getSeconds());
  console.log('New socket.io connection - id: %s', socket.id);
  function puts(error, stdout, stderr) { sys.puts(stdout) }
  exec('sudo /home/pi/pi-blaster/pi-blaster 4 17');

  socket.on('Video', function(Video){
   socket.emit('CMD', Video);
    console.log(Video);
    function puts(error, stdout, stderr) { sys.puts(stdout) }
    exec('sudo bash /home/pi/TLServer/scripts/' + Video, puts);
      });

  socket.on('REBOOT', function(){
    function puts(error, stdout, stderr) { sys.puts(stdout) }
    exec('sudo reboot now');
    sockets.emit('Info', "Rebooting")
  });

  socket.on('move', function(dX, dY){
    //console.log('event: ', dX, dY);
  piblaster.setPwm(17, (rescale(parseFloat(dX),-100,100,0.07,0.20)));
  piblaster.setPwm(4, (rescale(parseFloat(dY),-100,100,0.06,0.19)));
  //console.log(rescale(parseFloat(dY),-50,50,0.06,0.15));
  //console.log(rescale(parseFloat(dX),-100,100,0.07,0.20));
  });

  socket.on('TLInterval', function(T){
    TLInterval = T;
    socket.emit('Info', 'timelapse set to ' + T/1000 + 's')
  });

  function TLF() {
     var MyDate = new Date();
     var MyTimeStamp;
    MyTimeStamp = ('0' + MyDate.getHours()).slice(-2) + '-' + ('0' + (MyDate.getMinutes())).slice(-2) + '-' + ('0' + (MyDate.getSeconds())).slice(-2) ;

	 function puts(error, stdout, stderr) { sys.puts(stdout) }
	  exec('sudo raspistill -w ' + imgWidth + ' -h ' + imgHeight + ' -o ' + TLfolderName + '/' + TLfileName + '_' + MyTimeStamp +  '.jpg  -sh 40 -awb auto -mm average -v');
        //console.log('sudo raspistill -w ' + imgWidth + ' -h ' + imgHeight + ' -o ' + TLfolderName + '/' + TLfileName + '_' + MyTimeStamp +  '.jpg  -sh 40 -awb auto -mm average -v');
	socket.emit('Info', TLfileName + '_' + MyTimeStamp +  '.jpg');

    }

  function rescale(x, in_min, in_max, out_min, out_max){
    var output;
    output = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    //console.log(output);
    if (output < out_min) {
      output = out_min;
    } else if (output > out_max) {
      output = out_max;
    } else {
      //Nothing
    }

    return output

  }

  var myVar = "";
  socket.on('TLStart', function(){
   // function puts(error, stdout, stderr) { sys.puts(stdout) }
    var MyDate = new Date();
    var MyDateString;
    var MyTimeStamp;
    MyDateString = ('0' + MyDate.getFullYear()).slice(-2) + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2) + '-' + ('0' + (MyDate.getUTCDate())).slice(-2) ;
    MyTimeStamp = ('0' + MyDate.getHours()).slice(-2) + '-' + ('0' + (MyDate.getMinutes())).slice(-2) + '-' + ('0' + (MyDate.getSeconds())).slice(-2) ;

    TLfolderName = TLFolder + 'TL_' + MyDateString + '_' + MyTimeStamp;
    TLfileName = 'TL_' + MyDateString;
    fs.mkdir(TLfolderName);
    socket.emit('Folder', TLfolderName);
    //console.log(TLfolderName);
    myVar = setInterval(function(){TLF()}, TLInterval);
  });

   socket.on('TLStop', function(){
    clearInterval(myVar);
      socket.emit('Info', 'TL stopped');

  });

});

http.listen(serverPort, function(){
console.log('listening on *: ', serverPort);//

});
<commit_msg>Servos now works!!!<commit_after>// sudo udevadm control --reload-rules
// to refresh the port allocation

var events = require('events');
var eventEmitter = new events.EventEmitter();
var TLFolder="/home/pi/Documents/TL/"

var serPort = "/dev/ttyACM0";
var serBaud = 38400;
var serverPort = 999;

var LogR = 0;
var TelemetryFN = "";
var prevTel="";
var prevPitch="";

var SEPARATOR = ","
var version = "0.2";

var ArduHeader;
var ArduRead = {};

//--------------------------------------

var express = require('/usr/local/lib/node_modules/express');
var app = express();
var http = require('http').Server(app);
var io = require('/usr/local/lib/node_modules/socket.io')(http);
var fs = require('/usr/local/lib/node_modules/safefs');
var piblaster = require('/usr/local/lib/node_modules/pi-blaster.js');

var sys = require('sys');
var exec = require('child_process').exec;

var imgWidth = 2592; // Max = 2592
var imgHeight = 1944; //# Max = 1944
var TLInterval = 10000;

app.use(express.static(__dirname + '/public'));
// Routers
{
app.get('/', function(req, res){
  res.sendFile(__dirname + '/public/index.html');
  res.end;
});

app.get('/vj', function(req, res) {
  res.sendFile(__dirname + '/public/robotj.html');
  res.end;
});

app.get('/REBOOT', function(req, res) {
  var postData = req.url;
  function puts(error, stdout, stderr) { sys.puts(stdout) }
  exec('sudo reboot now');
  sockets.emit('Info', "Rebooting")
  //console.log(postData);
  res.end;
});

}

// Logging middleware

var mkdirSync = function (path) {
  try {
    fs.mkdirSync(path);
  } catch(e) {
    if ( e.code != 'EEXIST' ) throw e;
  }
}

io.on('connection', function(socket){
  var myDate = new Date();
  socket.emit('Info', 'Connected ' + myDate.getHours() + ':' +   myDate.getMinutes() + ':' +   myDate.getSeconds());
  console.log('New socket.io connection - id: %s', socket.id);
  function puts(error, stdout, stderr) { sys.puts(stdout) }
  exec('sudo /home/pi/pi-blaster/pi-blaster 4 17');

  socket.on('Video', function(Video){
   socket.emit('CMD', Video);
    console.log(Video);
    function puts(error, stdout, stderr) { sys.puts(stdout) }
    exec('sudo bash /home/pi/TLServer/scripts/' + Video, puts);
      });

  socket.on('REBOOT', function(){
    function puts(error, stdout, stderr) { sys.puts(stdout) }
    exec('sudo reboot now');
    sockets.emit('Info', "Rebooting")
  });

  socket.on('move', function(dX, dY){
    //console.log('event: ', dX, dY);
  //Need a value -100, 100
  piblaster.setPwm(17, (rescale(parseFloat(dX),-100,100,0.07,0.20)));
  piblaster.setPwm(4, (rescale(parseFloat(dY),-100,100,0.06,0.19)));

  //console.log(parseFloat(dX));
  //console.log(parseFloat(dY));

  //console.log(rescale(parseFloat(dY),-50,50,0.06,0.15));
  //console.log(rescale(parseFloat(dX),-100,100,0.07,0.20));
  });

  socket.on('TLInterval', function(T){
    TLInterval = T;
    socket.emit('Info', 'timelapse set to ' + T/1000 + 's')
  });

  function TLF() {
     var MyDate = new Date();
     var MyTimeStamp;
    MyTimeStamp = ('0' + MyDate.getHours()).slice(-2) + '-' + ('0' + (MyDate.getMinutes())).slice(-2) + '-' + ('0' + (MyDate.getSeconds())).slice(-2) ;

	 function puts(error, stdout, stderr) { sys.puts(stdout) }
	  exec('sudo raspistill -w ' + imgWidth + ' -h ' + imgHeight + ' -o ' + TLfolderName + '/' + TLfileName + '_' + MyTimeStamp +  '.jpg  -sh 40 -awb auto -mm average -v');
        //console.log('sudo raspistill -w ' + imgWidth + ' -h ' + imgHeight + ' -o ' + TLfolderName + '/' + TLfileName + '_' + MyTimeStamp +  '.jpg  -sh 40 -awb auto -mm average -v');
	socket.emit('Info', TLfileName + '_' + MyTimeStamp +  '.jpg');

    }

  function rescale(x, in_min, in_max, out_min, out_max){
    var output;
    output = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    //console.log(output);
    if (output < out_min) {
      output = out_min;
    } else if (output > out_max) {
      output = out_max;
    } else {
      //Nothing
    }

    return output

  }

  var myVar = "";
  socket.on('TLStart', function(){
   // function puts(error, stdout, stderr) { sys.puts(stdout) }
    var MyDate = new Date();
    var MyDateString;
    var MyTimeStamp;
    MyDateString = ('0' + MyDate.getFullYear()).slice(-2) + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2) + '-' + ('0' + (MyDate.getUTCDate())).slice(-2) ;
    MyTimeStamp = ('0' + MyDate.getHours()).slice(-2) + '-' + ('0' + (MyDate.getMinutes())).slice(-2) + '-' + ('0' + (MyDate.getSeconds())).slice(-2) ;

    TLfolderName = TLFolder + 'TL_' + MyDateString + '_' + MyTimeStamp;
    TLfileName = 'TL_' + MyDateString;
    fs.mkdir(TLfolderName);
    socket.emit('Folder', TLfolderName);
    //console.log(TLfolderName);
    myVar = setInterval(function(){TLF()}, TLInterval);
  });

   socket.on('TLStop', function(){
    clearInterval(myVar);
      socket.emit('Info', 'TL stopped');

  });

});

http.listen(serverPort, function(){
console.log('listening on *: ', serverPort);//

});
<|endoftext|>


<commit_before>angular.module('exceptionless', [])
    .constant('$ExceptionlessClient', exceptionless.ExceptionlessClient.default)
    .factory('exceptionlessHttpInterceptor', ['$q', '$ExceptionlessClient', function ($q, $ExceptionlessClient) {
        return {
            responseError: function responseError(rejection) {
                if (rejection.status === 404) {
                    $ExceptionlessClient.submitNotFound(rejection.config.url);
                }
                else if (rejection.status !== 401) {
                    $ExceptionlessClient.createUnhandledException(new Error("[" + rejection.status + "] " + rejection.config.url), 'errorHttpInterceptor')
                        .setSource(rejection.config.url)
                        .setProperty('request', rejection.config)
                        .submit();
                }
                return $q.reject(rejection);
            }
        };
    }])
    .config(['$httpProvider', '$provide', '$ExceptionlessClient', function ($httpProvider, $provide, $ExceptionlessClient) {
        $httpProvider.interceptors.push('exceptionlessHttpInterceptor');
        $provide.decorator('$exceptionHandler', ['$delegate', function ($delegate) {
                return function (exception, cause) {
                    $delegate(exception, cause);
                    $ExceptionlessClient.createUnhandledException(exception, '$exceptionHandler').setMessage(cause).submit();
                };
            }]);
        $provide.decorator('$log', ['$delegate', function ($delegate) {
                function decorateRegularCall(property, logLevel) {
                    var previousFn = $delegate[property];
                    return $delegate[property] = function () {
                        previousFn.apply(null, arguments);
                        if (arguments[0] && arguments[0].length > 0) {
                            $ExceptionlessClient.submitLog(null, arguments[0], logLevel);
                        }
                    };
                }
                $delegate.log = decorateRegularCall('log', 'Trace');
                $delegate.info = decorateRegularCall('info', 'Info');
                $delegate.warn = decorateRegularCall('warn', 'Warn');
                $delegate.debug = decorateRegularCall('debug', 'Debug');
                $delegate.error = decorateRegularCall('error', 'Error');
                return $delegate;
            }]);
    }])
    .run(['$rootScope', '$ExceptionlessClient', function ($rootScope, $ExceptionlessClient) {
        $rootScope.$on('$routeChangeSuccess', function (event, next, current) {
            if (!current) {
                return;
            }
            $ExceptionlessClient.createFeatureUsage(current.name)
                .setProperty('next', next)
                .setProperty('current', current)
                .submit();
        });
        $rootScope.$on('$routeChangeError', function (event, current, previous, rejection) {
            $ExceptionlessClient.createUnhandledException(new Error(rejection), '$routeChangeError')
                .setProperty('current', current)
                .setProperty('previous', previous)
                .submit();
        });
        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            if (!toState || toState.name === 'otherwise') {
                return;
            }
            $ExceptionlessClient.createFeatureUsage(toState.controller || toState.name)
                .setProperty('toState', toState)
                .setProperty('toParams', toParams)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$stateNotFound', function (event, unfoundState, fromState, fromParams) {
            if (!unfoundState) {
                return;
            }
            $ExceptionlessClient.createNotFound(unfoundState.to)
                .setProperty('unfoundState', unfoundState)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        var stateChangeError = '$stateChangeError';
        $rootScope.$on(stateChangeError, function (event, toState, toParams, fromState, fromParams, error) {
            if (!error) {
                return;
            }
            var builder = error && error.status === 404 ? $ExceptionlessClient.createNotFound(error.config.url) : $ExceptionlessClient.createUnhandledException(error, stateChangeError);
            builder.setSource(stateChangeError)
                .setMessage(error && error.statusText)
                .setProperty('toState', toState)
                .setProperty('toParams', toParams)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$destroy', function () {
            $ExceptionlessClient.config.queue.process();
        });
    }]);
<commit_msg>Updated dist folder<commit_after>angular.module('exceptionless', [])
    .constant('$ExceptionlessClient', exceptionless.ExceptionlessClient.default)
    .factory('exceptionlessHttpInterceptor', ['$q', '$ExceptionlessClient', function ($q, $ExceptionlessClient) {
        return {
            responseError: function responseError(rejection) {
                if (rejection.status === 404) {
                    $ExceptionlessClient.submitNotFound(rejection.config.url);
                }
                else if (rejection.status !== 401) {
                    var message = "[" + rejection.status + "] " + (rejection.data && rejection.data.Message ? rejection.data.Message : rejection.config.url);
                    $ExceptionlessClient.createUnhandledException(new Error(message), 'errorHttpInterceptor')
                        .setManualStackingInfo({ Status: rejection.status, ExceptionType: 'Error', Path: rejection.config.method + ' ' + rejection.config.url })
                        .setSource(rejection.config.url)
                        .setProperty('request', rejection.config)
                        .submit();
                }
                return $q.reject(rejection);
            }
        };
    }])
    .config(['$httpProvider', '$provide', '$ExceptionlessClient', function ($httpProvider, $provide, $ExceptionlessClient) {
        $httpProvider.interceptors.push('exceptionlessHttpInterceptor');
        $provide.decorator('$exceptionHandler', ['$delegate', function ($delegate) {
                return function (exception, cause) {
                    $delegate(exception, cause);
                    $ExceptionlessClient.createUnhandledException(exception, '$exceptionHandler').setMessage(cause).submit();
                };
            }]);
        $provide.decorator('$log', ['$delegate', function ($delegate) {
                function decorateRegularCall(property, logLevel) {
                    var previousFn = $delegate[property];
                    return $delegate[property] = function () {
                        previousFn.apply(null, arguments);
                        if (arguments[0] && arguments[0].length > 0) {
                            $ExceptionlessClient.submitLog(null, arguments[0], logLevel);
                        }
                    };
                }
                $delegate.log = decorateRegularCall('log', 'Trace');
                $delegate.info = decorateRegularCall('info', 'Info');
                $delegate.warn = decorateRegularCall('warn', 'Warn');
                $delegate.debug = decorateRegularCall('debug', 'Debug');
                $delegate.error = decorateRegularCall('error', 'Error');
                return $delegate;
            }]);
    }])
    .run(['$rootScope', '$ExceptionlessClient', function ($rootScope, $ExceptionlessClient) {
        $rootScope.$on('$routeChangeSuccess', function (event, next, current) {
            if (!current) {
                return;
            }
            $ExceptionlessClient.createFeatureUsage(current.name)
                .setProperty('next', next)
                .setProperty('current', current)
                .submit();
        });
        $rootScope.$on('$routeChangeError', function (event, current, previous, rejection) {
            $ExceptionlessClient.createUnhandledException(new Error(rejection), '$routeChangeError')
                .setProperty('current', current)
                .setProperty('previous', previous)
                .submit();
        });
        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            if (!toState || toState.name === 'otherwise') {
                return;
            }
            $ExceptionlessClient.createFeatureUsage(toState.controller || toState.name)
                .setProperty('toState', toState)
                .setProperty('toParams', toParams)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$stateNotFound', function (event, unfoundState, fromState, fromParams) {
            if (!unfoundState) {
                return;
            }
            $ExceptionlessClient.createNotFound(unfoundState.to)
                .setProperty('unfoundState', unfoundState)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        var stateChangeError = '$stateChangeError';
        $rootScope.$on(stateChangeError, function (event, toState, toParams, fromState, fromParams, error) {
            if (!error) {
                return;
            }
            var builder = error && error.status === 404 ? $ExceptionlessClient.createNotFound(error.config.url) : $ExceptionlessClient.createUnhandledException(error, stateChangeError);
            builder.setSource(stateChangeError)
                .setMessage(error && error.statusText)
                .setProperty('toState', toState)
                .setProperty('toParams', toParams)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$destroy', function () {
            $ExceptionlessClient.config.queue.process();
        });
    }]);
<|endoftext|>


<commit_before>function candidateLineGraph(nationalData) {
  var parseDate = d3.time.format("%Y-%m-%d");
  nationalData.forEach(function(candidate) {
    candidate.minDate = d3.min(candidate.attributes.responses.map(function(d) { return parseDate.parse(d.date); }));
    candidate.maxDate = d3.max(candidate.attributes.responses.map(function(d) { return parseDate.parse(d.date); }));
    candidate.maxPercentage = d3.max(candidate.attributes.responses.map(function(d) { return d.percentage; }));
  });
  var graph = d3.select("#line-graph");
  var WIDTH = 1000;
  var HEIGHT = 500;
  var MARGINS = {
      top: 20,
      right: 20,
      bottom: 26,
      left: 50
    };
  var Xscale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]);
  Xscale.domain([
      d3.min(nationalData.map(function(candidate) { return candidate.minDate; })),
      d3.max(nationalData.map(function(candidate) { return candidate.maxDate; }))
    ]);
  var Yscale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0,30]);

  var colorScale = d3.scale.category20();

  var Xaxis = d3.svg.axis()
      .scale(Xscale)
      .orient("bottom");

  var Yaxis = d3.svg.axis()
      .scale(Yscale)
      .orient("left");

  graph.append("svg:g")
    .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
    .call(Xaxis);

  graph.append("svg:g")
    .attr("transform", "translate(" + (MARGINS.left) + ",0)")
    .call(Yaxis)

  var lineGen = d3.svg.line()
    .x(function(d) {
      return Xscale(parseDate.parse(d.date));
    })
    .y(function(d) {
      return Yscale(parseFloat(d.percentage));
    })
    .interpolate('basis');

  nationalData.forEach(function(candidate, index) {
    graph.append("svg:path")
      .attr('d', lineGen(candidate.attributes.responses))
      .attr("stroke", colorScale(index))
      .attr("stroke-width", 3)
      .attr("fill", "none");
  });

  var yaxiscords = d3.range(26, HEIGHT, 45.4);
  var xaxiscords = d3.range(50, WIDTH, 25);

  graph.selectAll("line.vertical")
    .data(xaxiscords)
    .enter().append("svg:line")
    .attr("x1", function(d) {return d;})
    .attr("y1", 26)
    .attr("x2", function(d) {return d;})
    .attr("y2", HEIGHT - 25)
    .style("stroke", "rgb(192,192,192)")
    .style("opacity", 0.3)
    .style("stroke-width", 2);

  graph.selectAll("line.horizontal")
    .data(yaxiscords)
    .enter().append("svg:line")
    .attr("x1", 50)
    .attr("y1", function(d) {return d;})
    .attr("x2", WIDTH - 25)
    .attr("y2", function(d) {return d;})
    .style("stroke", "rgb(192,192,192)")
    .style("opacity", 0.3)
    .style("stroke-width", 2)
}

<commit_msg>change y domain to vary based on max percentage<commit_after>function candidateLineGraph(nationalData) {
  var parseDate = d3.time.format("%Y-%m-%d");
  nationalData.forEach(function(choice) {
    choice.minDate = d3.min(choice.attributes.responses.map(function(d) { return parseDate.parse(d.date); }));
    choice.maxDate = d3.max(choice.attributes.responses.map(function(d) { return parseDate.parse(d.date); }));
    choice.maxPercentage = d3.max(choice.attributes.responses.map(function(d) { return d.percentage; }));
  });
  var graph = d3.select("#line-graph");
  var WIDTH = 1000;
  var HEIGHT = 500;
  var MARGINS = {
      top: 20,
      right: 20,
      bottom: 26,
      left: 50
    };
  var Xscale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]);
  Xscale.domain([
      d3.min(nationalData.map(function(choice) { return choice.minDate; })),
      d3.max(nationalData.map(function(choice) { return choice.maxDate; }))
    ]);
  var Yscale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]);
  Yscale.domain([
      0,
      d3.max(nationalData.map(function(choice) { return parseFloat(choice.maxPercentage) })) + 5
    ]);

  var colorScale = d3.scale.category20();

  var Xaxis = d3.svg.axis()
      .scale(Xscale)
      .orient("bottom");

  var Yaxis = d3.svg.axis()
      .scale(Yscale)
      .orient("left");

  graph.append("svg:g")
    .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
    .call(Xaxis);

  graph.append("svg:g")
    .attr("transform", "translate(" + (MARGINS.left) + ",0)")
    .call(Yaxis)

  var lineGen = d3.svg.line()
    .x(function(d) {
      return Xscale(parseDate.parse(d.date));
    })
    .y(function(d) {
      return Yscale(parseFloat(d.percentage));
    })
    .interpolate('basis');

  nationalData.forEach(function(choice, index) {
    graph.append("svg:path")
      .attr('d', lineGen(choice.attributes.responses))
      .attr("stroke", colorScale(index))
      .attr("stroke-width", 3)
      .attr("fill", "none");
  });

  var yaxiscords = d3.range(26, HEIGHT, 45.4);
  var xaxiscords = d3.range(50, WIDTH, 25);

  graph.selectAll("line.vertical")
    .data(xaxiscords)
    .enter().append("svg:line")
    .attr("x1", function(d) {return d;})
    .attr("y1", 26)
    .attr("x2", function(d) {return d;})
    .attr("y2", HEIGHT - 25)
    .style("stroke", "rgb(192,192,192)")
    .style("opacity", 0.3)
    .style("stroke-width", 2);

  graph.selectAll("line.horizontal")
    .data(yaxiscords)
    .enter().append("svg:line")
    .attr("x1", 50)
    .attr("y1", function(d) {return d;})
    .attr("x2", WIDTH - 25)
    .attr("y2", function(d) {return d;})
    .style("stroke", "rgb(192,192,192)")
    .style("opacity", 0.3)
    .style("stroke-width", 2)
}

<|endoftext|>


<commit_before>import '/imports/Api.js';

let NoActionError = function(message) {
	this.message = message;
}

let jSendResponder = function(res, process) {
	try {
		let body =
			{ status: "success"
			, data: process()
			};
		res.statusCode = 200;
		res.setHeader('Content-Type', 'application/json; charset=utf-8');
		res.end(JSON.stringify(body, null, "\t"));
	} catch(e) {
		let body = {};
		if (e instanceof FilteringReadError
		 || e instanceof NoActionError
		) {
			res.statusCode = 400;
			body.status = "fail";
			body.data = {};
			if (e.name) {
				body.data[e.name] = e.message;
			} else {
				body.data.error = e.message;
			}
		} else {
			console.log(e)
			res.statusCode = 500;
			body.status = "error";
			body.message = "Server error";
		}
		res.end(JSON.stringify(body, null, "\t"));
	}
}

Router.route('api.0.json', {
	path: '/api/0/json/:handler',
	where: 'server',
	action: function() {
		jSendResponder(this.response, () => {
			let handler = this.params.handler;
			if (!Api.hasOwnProperty(handler)) {
				throw new NoActionError("Invalid action")
			}
			let query = this.params.query;
			return Api[handler](query);
		});
	}
});
<commit_msg>allow cross origin requests on /api<commit_after>import '/imports/Api.js';

WebApp.rawConnectHandlers.use("/api", function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  return next();
});

let NoActionError = function(message) {
	this.message = message;
}

let jSendResponder = function(res, process) {
	try {
		let body =
			{ status: "success"
			, data: process()
			};
		res.statusCode = 200;
		res.setHeader('Content-Type', 'application/json; charset=utf-8');
		res.end(JSON.stringify(body, null, "\t"));
	} catch(e) {
		let body = {};
		if (e instanceof FilteringReadError
		 || e instanceof NoActionError
		) {
			res.statusCode = 400;
			body.status = "fail";
			body.data = {};
			if (e.name) {
				body.data[e.name] = e.message;
			} else {
				body.data.error = e.message;
			}
		} else {
			console.log(e)
			res.statusCode = 500;
			body.status = "error";
			body.message = "Server error";
		}
		res.end(JSON.stringify(body, null, "\t"));
	}
}

Router.route('api.0.json', {
	path: '/api/0/json/:handler',
	where: 'server',
	action: function() {
		jSendResponder(this.response, () => {
			let handler = this.params.handler;
			if (!Api.hasOwnProperty(handler)) {
				throw new NoActionError("Invalid action")
			}
			let query = this.params.query;
			return Api[handler](query);
		});
	}
});
<|endoftext|>


<commit_before>/**
 * This file helps to run tests on Windows, as well as chooses to test ES5 for
 * Node < 8.6.0. Normal ES7 code is tested with Node 8.6+. The default binary
 * is actual source code, i.e. no transpilation, and es5 binary can be run with
 * zoroaster-es5
 */

const { fork } = require('child_process')
const { resolve } = require('path')
const { nodeLt } = require('noddy')
const { bin } = require('./package.json')

const { zoroaster, zoroasterEs5 } = bin

const force = process.argv.some(a => a === '--force')
if (force) {
  console.log(`Using the force to summon the dead with ${zoroasterEs5}...`) // eslint-disable-line no-console
} else {
  console.log(`Thus spoke Zarathustra ${zoroaster}`)
}
const useEs5 = nodeLt('v8.6.0') || force

const ZOROASTER = resolve(__dirname, zoroaster)
const ZOROASTER_ES5 = resolve(__dirname, zoroasterEs5)

const SPEC = resolve(__dirname, 'test/spec')
const SPEC_ES5 = resolve(__dirname, 'es5/test/spec')

const spec = useEs5 ? SPEC_ES5 : SPEC
const node = useEs5 ? ZOROASTER_ES5 : ZOROASTER

const args = [spec]

if (process.argv.find(argv => argv === '--watch')) {
  args.push('--watch')
}

fork(node, args)
<commit_msg>return fork exit<commit_after>/**
 * This file helps to run tests on Windows, as well as chooses to test ES5 for
 * Node < 8.6.0. Normal ES7 code is tested with Node 8.6+. The default binary
 * is actual source code, i.e. no transpilation, and es5 binary can be run with
 * zoroaster-es5
 */

const { fork } = require('child_process')
const { resolve } = require('path')
const { nodeLt } = require('noddy')
const { bin } = require('./package.json')

const { zoroaster, zoroasterEs5 } = bin

const force = process.argv.some(a => a === '--force')
if (force) {
  console.log(`Using the force to summon the dead with ${zoroasterEs5}...`) // eslint-disable-line no-console
} else {
  console.log(`Thus spoke Zarathustra ${zoroaster}`)
}
const useEs5 = nodeLt('v8.6.0') || force

const ZOROASTER = resolve(__dirname, zoroaster)
const ZOROASTER_ES5 = resolve(__dirname, zoroasterEs5)

const SPEC = resolve(__dirname, 'test/spec')
const SPEC_ES5 = resolve(__dirname, 'es5/test/spec')

const spec = useEs5 ? SPEC_ES5 : SPEC
const node = useEs5 ? ZOROASTER_ES5 : ZOROASTER

const args = [spec]

if (process.argv.find(argv => argv === '--watch')) {
  args.push('--watch')
}

fork(node, args)
  .on('exit', process.exit)
<|endoftext|>


<commit_before>import fs from 'fs';
import parseSyndicationFeed from '../src/feed-parser';

const expect = global.expect;
const TEST_FEEDS_DIRECTORY = './tests/syndication-feeds/';

function loadTestSyndicationFeed(type, name) {
  return fs.readFileSync(`${TEST_FEEDS_DIRECTORY}${type}/${name}.${type}`, { encoding: 'utf8' });
}

describe('feed-parser', () => {
  describe('parseSyndicationFeed(feedString)', () => {
    it('should throw if feedString is null, empty or not a string', () =>
      Promise.all([
        expect(parseSyndicationFeed(null)).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed('')).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed(1)).to.be.rejectedWith('Valid RSS/ATOM Required')
      ])
    );

    it('should throw if feedString is not a valid XML document', () =>
      Promise.all([
        expect(parseSyndicationFeed('{data: \'This is JSON not XML\'}')).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed('<?xml version = "1.0"?><data><<</data>')).to.be.rejectedWith('Valid RSS/ATOM Required')
      ])
    );

    it('should correctly parse minimum.rss', () => {
      const minimumRSS = loadTestSyndicationFeed('rss', 'minimum');
      const expectedItems = [
        {
          title: 'You won\'t believe what happened next!',
          link: 'http://example.com/what-happened-next',
          description: 'Something uninteresting, you got click baited!'
        },
        {
          title: 'Blog Authors hate him!',
          link: 'http://example.com/blog-authors-hate-him'
        }
      ];
      return expect(parseSyndicationFeed(minimumRSS)).to.eventually.deep.equal(expectedItems);
    });
  });
});
<commit_msg>Added wordpress.com parsing test<commit_after>import fs from 'fs';
import moment from 'moment';
import parseSyndicationFeed from '../src/feed-parser';

const expect = global.expect;
const TEST_FEEDS_DIRECTORY = './tests/syndication-feeds/';

function loadTestSyndicationFeed(type, name) {
  return fs.readFileSync(`${TEST_FEEDS_DIRECTORY}${type}/${name}.${type}`, { encoding: 'utf8' });
}

describe('feed-parser', () => {
  describe('parseSyndicationFeed(feedString)', () => {
    it('should throw if feedString is null, empty or not a string', () =>
      Promise.all([
        expect(parseSyndicationFeed(null)).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed('')).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed(1)).to.be.rejectedWith('Valid RSS/ATOM Required')
      ])
    );

    it('should throw if feedString is not a valid XML document', () =>
      Promise.all([
        expect(parseSyndicationFeed('{data: \'This is JSON not XML\'}')).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed('<?xml version = "1.0"?><data><<</data>')).to.be.rejectedWith('Valid RSS/ATOM Required')
      ])
    );

    it('should correctly parse minimum.rss', () => {
      const minimumRSS = loadTestSyndicationFeed('rss', 'minimum');
      const expectedItems = [
        {
          title: 'You won\'t believe what happened next!',
          link: 'http://example.com/what-happened-next',
          description: 'Something uninteresting, you got click baited!'
        },
        {
          title: 'Blog Authors hate him!',
          link: 'http://example.com/blog-authors-hate-him'
        }
      ];
      return expect(parseSyndicationFeed(minimumRSS)).to.eventually.deep.equal(expectedItems);
    });

    it('should correctly parse wordpress.com.rss', () => {
      const wordpressOrgRSS = loadTestSyndicationFeed('rss', 'wordpress.com');
      const expectedItems = [
        {
          title: 'Graduating from York',
          link: 'https://dannycomputerscientist.wordpress.com/2016/02/05/graduating-from-york/',
          description: 'On January 23rd I graduated with an MSc in Advanced Computer Science from The University of York. It was a nice occasion to get together and be merry with the family, and of course for some photos in my cap and gown — this time they were grey and blue. My parents took my degree',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2016/02/img_0091.jpg',
          datePublished: moment('Fri, 05 Feb 2016 18:05:12 +0000')
        },
        {
          title: 'HackTrain 2.0',
          link: 'https://dannycomputerscientist.wordpress.com/2016/01/10/hacktrain-2-0/',
          description: 'It seems like a lifetime ago, but the first HackTrain event was actually only 9 months ago — It probably feels so long ago to me as so much has change in the interim, including me getting a job as a result of the first event. When an opportunity came up to represent Trainline at',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/12304083_786742814805282_703787864428458423_o.jpg',
          datePublished: moment('Sun, 10 Jan 2016 22:01:22 +0000')
        },
        {
          title: 'Centre for Computing History',
          link: 'https://dannycomputerscientist.wordpress.com/2016/01/10/centre-for-computing-history/',
          description: 'Since September, Charlotte and I have lived about a minutes walk from the UK Computer Museum (which also seems to go by the name Centre for Computing History), but we\'d never actually gone inside. Today after my flying lesson we went to have a quick look. Whilst it made me feel old to see things I',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2016/01/bbc-micro.jpg',
          datePublished: moment('Sun, 10 Jan 2016 17:39:38 +0000')
        },
        {
          title: 'Tracking Moving Trains (with the minimum possible effort)',
          link: 'https://dannycomputerscientist.wordpress.com/2015/12/22/tracking-moving-trains-with-minimum-possible-effort/',
          description: 'Trains are, in many respects, wonderful machines. They\'re simultaneously both the most romantic form of travel and the most grueling way to get to work every morning. One thing trains are not however, is up-to-date with modern technology. Whilst you can follow the course, in real time, of a plane soaring at 36,000 feet above',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/12106848_1494412047526257_4658382875925199724_n.jpg',
          datePublished: moment('Tue, 22 Dec 2015 01:52:55 +0000')
        },
        {
          title: 'Captain Danny',
          link: 'https://dannycomputerscientist.wordpress.com/2015/12/09/captain-danny/',
          description: 'One of the nice things about working, opposed to studying, is that I now don\'t feel guilty about not spending all my time working on coursework. Time for a hobby! Living 15 minutes walk from Cambridge Airport I quite often see people learning to fly, and thought it looked like fun — so decided to start',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/img_05611.jpg',
          datePublished: moment('Wed, 09 Dec 2015 21:12:16 +0000')
        },
        {
          title: 'Trainline at Silicon Milkroundabout',
          link: 'https://dannycomputerscientist.wordpress.com/2015/12/04/trainline-at-silicon-milkroundabout/',
          description: 'A few weeks ago I was lucky enought to be part of the team that tried, and hopefully succeeded, to entice more developers to come and work with us at Trainline at the Silicon Milkroundabout tech recruitment event. I really enjoy talking to people about technology and it was especially nice to talk to people who',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/img_0521.jpg',
          datePublished: moment('Fri, 04 Dec 2015 23:12:03 +0000')
        },
        {
          title: 'On-boarding at Trainline',
          link: 'https://dannycomputerscientist.wordpress.com/2015/10/29/on-boarding-at-trainline/',
          description: 'I\'m now entering the sixth week of my time at Trainline. It\'s been quite the experience, due to it being my first full-time job and it being a time of significant changes at Trainline in terms of technology, branding and even an expansion into the European rail market. It\'s been great to be in a',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/10/trainline-homepage.png',
          datePublished: moment('Thu, 29 Oct 2015 17:57:27 +0000')
        },
        {
          title: 'MSc Finished',
          link: 'https://dannycomputerscientist.wordpress.com/2015/09/13/msc-finished/',
          description: 'Last week I submitted my thesis, workshop report and conference presentation for my MSc in Advanced Computer Science. Two days after my submission I was also required to present my research and answer a few questions fielded from a lecturer in Yorks Department of Computer Science who had not previously seen my work. The',
          datePublished: moment('Sun, 13 Sep 2015 01:13:58 +0000')
        },
        {
          title: 'Expect the unexpected',
          link: 'https://dannycomputerscientist.wordpress.com/2015/08/02/expect-the-unexpected/',
          description: 'When you design software you usually have a few use cases in mind, in the case of EpsilonGit the use case I keep coming back to is a project lead who wants an overview of how his team is working and how they are using their version control software. Back in second year when I',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/08/screen-shot-2015-08-02-at-21-16-29.png',
          datePublished: moment('Sun, 02 Aug 2015 20:19:55 +0000')
        },
        {
          title: 'Thesis writing begins',
          link: 'https://dannycomputerscientist.wordpress.com/2015/07/27/thesis-writing-begins/',
          description: 'Today I started work on my masters thesis covering my research for and development of EpsilonGit. There\'s no template provided for the layout of such reports, so today I\'ve been sketching out a rough outline of what I hope to include in the report. e.g. Chapter names, section headings and comments for things to talk',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/07/screen-shot-2015-07-27-at-22-02-20.png',
          datePublished: moment('Mon, 27 Jul 2015 21:13:14 +0000')
        }
      ];
      return expect(parseSyndicationFeed(wordpressOrgRSS)).to.eventually.deep.equal(expectedItems);
    });
  });
});
<|endoftext|>


<commit_before>(function (global, factory) {
    if (typeof define === "function" && define.amd) {
        define(["exports", "jQuery", "esprima"], factory);
    } else if (typeof exports !== "undefined") {
        factory(exports, require("jQuery"), require("esprima"));
    } else {
        var mod = {
            exports: {}
        };
        factory(mod.exports, global.jQuery, global.esprima);
        global.jqueryPlugincreator = mod.exports;
    }
})(this, function (exports, _jQuery, _esprima) {
    "use strict";

    Object.defineProperty(exports, "__esModule", {
        value: true
    });

    var _jQuery2 = _interopRequireDefault(_jQuery);

    var _esprima2 = _interopRequireDefault(_esprima);

    function _interopRequireDefault(obj) {
        return obj && obj.__esModule ? obj : {
            default: obj
        };
    }

    /*!
     * jQuery Plugin Creator 0.3.0
     * https://github.com/OOPMan/jquery-plugin-creator
     *
     * Copyright 2014 Adam Jorgensen
     * Released under the MIT license.
     * http://github.com/OOPMan/jquery-plugin-creator/LICENSE
     *
     */
    /**
     * TODO: Add checks to prevent over-writing plugins
     * TODO: Add ability to not specify plugin name and have a randomly generated name assigned
     */

    var $ = _jQuery2.default,
        noOp = _jQuery2.default.noop,
        scopeName = "jquery-plugincreator-",

    /**
     * Given a function parameter name and a function, determines whether the function in question accepts the
     * named parameter.
     *
     * As this function is used internally to detect whether a function defines the _super parameter and given
     * that the _super parameter will always be the last parameter IF it is defined, the search is restricted
     * to the very last parameter defined for a given function.
     *
     * @param {function} inputFunction
     * @returns {boolean}
     */
    isSuperParameterDefinedForFunction = function isSuperParameterDefinedForFunction(inputFunction) {
        var inputFunctionAST = _esprima2.default.parse("f = " + inputFunction.toString()),
            inputFunctionParams = inputFunctionAST.body[0].expression.right.params,
            firstInputFunctionParam = inputFunctionParams.shift();
        if (typeof firstInputFunctionParam == "undefined") return false;
        return firstInputFunctionParam.name == "_super";
    },

    /**
     *
     * @param {function} childMember
     * @param {function} parentMember
     * @returns {function}
     */
    parentWrapper = function parentWrapper(childMember, parentMember) {
        var parentMember = parentMember == childMember ? noOp : parentMember,
            childMemberExpectsSuper = isSuperParameterDefinedForFunction(childMember);

        function parentGenerator(self) {
            var _super = parentMember;
            if (_super._isParentGenerator) _super = _super(self);else _super = function _super() {
                return parentMember.apply(self, arguments);
            };
            return function () {
                var args = $.makeArray(arguments);
                if (childMemberExpectsSuper) args.unshift(_super);
                return childMember.apply(self, args);
            };
        }

        parentGenerator._isParentGenerator = true;
        return parentGenerator;
    },

    /**
     *
     * @param {Object} childMembers
     * @param {Object} parentMembers
     * @param {Object} [self]
     * @returns {Object}
     */
    wrapParents = function wrapParents(childMembers, parentMembers, self) {
        var childMembers = $.extend(true, {}, childMembers),
            parentMembers = $.extend(true, {}, parentMembers);
        for (var memberName in parentMembers) {
            if (childMembers[memberName]) {
                if (typeof childMembers[memberName] == "function" && !childMembers[memberName]._isParentGenerator) {
                    childMembers[memberName] = parentWrapper(childMembers[memberName], parentMembers[memberName]);
                    if (self) childMembers[memberName] = childMembers[memberName](self);
                }
            } else {
                childMembers[memberName] = parentMembers[memberName];
            }
        }
        return childMembers;
    },

    /**
     *
     * @type {{addPlugin: pluginCreator.addPlugin}}
     */
    pluginCreator = {
        /**
         * Adds a new stateful plugin to jQuery.
         *
         * A stateful plugin consists of the following optional components:
         * - An object defining default properties to be associated with a plugin instance via its options member
         * - An object defining member functions and values to be associated with a plugin instances prototype.
         *
         * @param {string} name
         * @param {Object} [defaults]
         * @param {Object} [members]
         * @return {string}
         */
        addPlugin: function addPlugin(name, defaults, members) {
            var defaults = $.extend(true, {}, defaults || {}),
                baseMembers = {
                /**
                 * Default init function. Does nothing.
                 */
                init: noOp,
                /**
                 *
                 * @returns {Object}
                 */
                getInstance: function getInstance() {
                    return this;
                },
                /**
                 *
                 * @param {Object} [options]
                 * @returns {Object}
                 */
                update: function update(options) {
                    $.extend(true, this.options, options || {});
                },
                /**
                 *
                 * @param {Object} members
                 * @returns {boolean}
                 */
                extend: function extend(members) {
                    $.extend(true, this, wrapParents(members, this, this));
                },
                /**
                 * Destructor function, performs the following:
                 *
                 * 1: Triggers a scopeName + name + ".destroy" (E.g. "jquery-plugincreator-myPlugin.destroy") event on the jQuery context (I.e. $(this) ) for the plugin instance.
                 * 2: Removes the scopeName + name (E.g. "jquery-plugincreator-myPlugin") class from the element linked to the plugin instance.
                 * 3: Removes the scopeName + name (E.g. "jquery-plugincreator-myPlugin") data value from the element linked to the plugin instance.
                 * 4: Removes the "data-" + scopeName + name (E.g. "data-jquery-plugincreator-myPlugin") attribute from the element linked to the plugin instance.
                 */
                destroy: function destroy() {
                    this.context.trigger(scopeName + name + ".destroy").removeClass(scopeName + name).removeData(scopeName + name).removeAttr("data-" + scopeName + name);
                }
            },
                members = $.isArray(members) ? members : [wrapParents(members, wrapParents(baseMembers, baseMembers))];

            /**
             * This function is used to instantiate an instance of the plugin on a given element.
             *
             * @param {Object} element
             * @param {Object} [options]
             * @param {Array} [initArguments]
             */
            function instantiatePlugin(element, options, initArguments) {
                var options = options || {},
                    prototype = $.extend(true, {}, members[0]),
                    instance = null;

                function pluginConstructor() {
                    this.instanceOf = name;
                    this.element = element;
                    this.context = $(element).addClass(scopeName + name);
                    this.options = $.extend(true, {}, defaults, options);
                    for (var memberName in prototype) {
                        if (typeof prototype[memberName] == "function" && prototype[memberName]._isParentGenerator) {
                            prototype[memberName] = prototype[memberName](this);
                        }
                    }
                    $.extend(true, this, prototype);
                    this.init.apply(this, initArguments);
                }

                instance = new pluginConstructor();
                $.data(element, scopeName + name, instance);
                return instance;
            }

            /**
             * A function to handle the actual process of instantiating a plugin instance or calling a method on
             * a given plugin instance.
             *
             * @param {Object} self
             * @param {Object|String} options
             * @param {Array} args
             * @returns {*}
             */
            function processPluginCall(self, options, args) {
                var instance = $.data(self, scopeName + name);
                if (instance) {
                    if (typeof options == "string" && typeof instance[options] == "function") {
                        // call a method on the instance
                        return instance[options].apply(instance, args.slice(1));
                    } else if (typeof instance.update == "function" && $.isPlainObject(options)) {
                        // call update on the instance
                        return instance.update.apply(instance, args);
                    } else {
                        throw options + " is not a member of " + self;
                    }
                } else {
                    return instantiatePlugin(self, options, args.slice(1));
                }
            }

            /**
             *
             * @param {Object|string} options
             * @returns {jQuery}
             */
            $.fn[name] = function (options) {
                var args = $.makeArray(arguments),
                    result = this;
                if (this.length === 1) {
                    result = processPluginCall(this[0], options, args);
                } else {
                    if (options === "map") {
                        result = this.map(function () {
                            return processPluginCall(this, args[1], args.slice(2));
                        });
                    } else {
                        result = this.each(function () {
                            processPluginCall(this, options, args);
                        });
                    }
                }
                if (typeof result == "undefined") result = this;
                return result;
            };

            /**
             *
             * @type {Object}
             */
            $.fn[name].defaults = defaults;

            /**
             *
             * @param {Object} options
             * @returns {Object}
             */
            $.fn[name].updateDefaultsWith = function (options) {
                $.extend(true, defaults, options);
                return defaults;
            };

            /**
             *
             * @param {Object} childMembers
             * @returns {function}
             */
            $.fn[name].extendMembersWith = function (childMembers) {
                members.unshift(wrapParents(childMembers, members[0]));
            };

            /**
             * Clones a plugin added using jQuery PluginCreator.
             *
             * While the defaults and members are cloned completely and are independent, the constructor is shared.
             *
             * @param {string} name
             * @param {string} newName
             * @returns {string}
             */
            $.fn[name].cloneTo = function (newName) {
                return pluginCreator.addPlugin(newName, defaults, $.extend(true, [], members));
            };

            /**
             * Extends a plugin added using jQuery PluginCreator.
             *
             * Defaults and members are cloned and extended from the original plugin while the extended constructor
             * functions such that the constructor for the original plugin is called first, then new new
             * constructor, if present.
             *
             * @param {string} name
             * @param {string} newName
             * @param {Object} [childMembers]
             * @return {string}
             */
            $.fn[name].extendTo = function (newName, childMembers) {
                $.fn[name].cloneTo(newName);
                $.fn[newName].extendMembersWith(childMembers);
            };

            return name;
        }
    };

    _jQuery2.default.extend(_jQuery2.default, pluginCreator);

    exports.default = pluginCreator.addPlugin;
});<commit_msg>#4: Updated distribution version of jquery.plugincreator.js<commit_after>(function (global, factory) {
    if (typeof define === "function" && define.amd) {
        define(["exports", "jQuery", "esprima"], factory);
    } else if (typeof exports !== "undefined") {
        factory(exports, require("jQuery"), require("esprima"));
    } else {
        var mod = {
            exports: {}
        };
        factory(mod.exports, global.jQuery, global.esprima);
        global.jqueryPlugincreator = mod.exports;
    }
})(this, function (exports, _jQuery, _esprima) {
    "use strict";

    Object.defineProperty(exports, "__esModule", {
        value: true
    });

    var _jQuery2 = _interopRequireDefault(_jQuery);

    var _esprima2 = _interopRequireDefault(_esprima);

    function _interopRequireDefault(obj) {
        return obj && obj.__esModule ? obj : {
            default: obj
        };
    }

    /*!
     * jQuery Plugin Creator 0.3.0
     * https://github.com/OOPMan/jquery-plugin-creator
     *
     * Copyright 2014 Adam Jorgensen
     * Released under the MIT license.
     * http://github.com/OOPMan/jquery-plugin-creator/LICENSE
     *
     */
    /**
     * TODO: Add checks to prevent over-writing plugins
     * TODO: Add ability to not specify plugin name and have a randomly generated name assigned
     */

    var $ = _jQuery2.default,
        noOp = _jQuery2.default.noop,
        scopeName = "jquery-plugincreator-",

    /**
     * Given a function parameter name and a function, determines whether the function in question accepts the
     * named parameter.
     *
     * As this function is used internally to detect whether a function defines the _super parameter and given
     * that the _super parameter will always be the last parameter IF it is defined, the search is restricted
     * to the very last parameter defined for a given function.
     *
     * @param {function} inputFunction
     * @returns {boolean}
     */
    isSuperParameterDefinedForFunction = function isSuperParameterDefinedForFunction(inputFunction) {
        var inputFunctionAST = _esprima2.default.parse("f = " + inputFunction.toString()),
            inputFunctionParams = inputFunctionAST.body[0].expression.right.params,
            firstInputFunctionParam = inputFunctionParams.shift();
        if (typeof firstInputFunctionParam == "undefined") return false;
        return firstInputFunctionParam.name == "_super";
    },

    /**
     *
     * @param {function} childMember
     * @param {function} parentMember
     * @param {boolean} [alwaysInjectSuper=false]
     * @returns {function}
     */
    parentWrapper = function parentWrapper(childMember, parentMember) {
        var alwaysInjectSuper = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];

        var parentMember = parentMember == childMember ? noOp : parentMember,
            childMemberExpectsSuper = alwaysInjectSuper ? true : isSuperParameterDefinedForFunction(childMember);

        function parentGenerator(self) {
            var _super = parentMember;
            if (_super._isParentGenerator) _super = _super(self);else _super = function _super() {
                return parentMember.apply(self, arguments);
            };
            return function () {
                var args = $.makeArray(arguments);
                if (childMemberExpectsSuper) args.unshift(_super);
                return childMember.apply(self, args);
            };
        }

        parentGenerator._isParentGenerator = true;
        return parentGenerator;
    },

    /**
     *
     * @param {Object} childMembers
     * @param {Object} parentMembers
     * @param {Object} [self=null]
     * @param {boolean} [alwaysInjectSuper=false]
     * @returns {Object}
     */
    wrapParents = function wrapParents(childMembers, parentMembers) {
        var self = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
        var alwaysInjectSuper = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];

        var childMembers = $.extend(true, {}, childMembers),
            parentMembers = $.extend(true, {}, parentMembers);
        for (var memberName in parentMembers) {
            if (childMembers[memberName]) {
                if (typeof childMembers[memberName] == "function" && !childMembers[memberName]._isParentGenerator) {
                    childMembers[memberName] = parentWrapper(childMembers[memberName], parentMembers[memberName], alwaysInjectSuper);
                    if (self) childMembers[memberName] = childMembers[memberName](self);
                }
            } else {
                childMembers[memberName] = parentMembers[memberName];
            }
        }
        return childMembers;
    },

    /**
     *
     * @type {{addPlugin: pluginCreator.addPlugin}}
     */
    pluginCreator = {
        /**
         * Adds a new stateful plugin to jQuery.
         *
         * A stateful plugin consists of the following optional components:
         * - An object defining default properties to be associated with a plugin instance via its options member
         * - An object defining member functions and values to be associated with a plugin instances prototype.
         *
         * @param {string} name
         * @param {Object} [defaults={}]
         * @param {Object} [members={}]
         * @param {boolean} [alwaysInjectSuper=false]
         * @return {string}
         */
        addPlugin: function addPlugin(name) {
            var defaults = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
            var members = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
            var alwaysInjectSuper = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];

            var defaults = $.extend(true, {}, defaults),
                baseMembers = {
                /**
                 * Default init function. Does nothing.
                 */
                init: noOp,
                /**
                 *
                 * @returns {Object}
                 */
                getInstance: function getInstance() {
                    return this;
                },
                /**
                 *
                 * @param {Object} [options]
                 * @returns {Object}
                 */
                update: function update(options) {
                    $.extend(true, this.options, options || {});
                },
                /**
                 *
                 * @param {Object} members
                 * @param {boolean} [alwaysInjectSuper=false]
                 * @returns {boolean}
                 */
                extend: function extend(members) {
                    var alwaysInjectSuper = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];

                    $.extend(true, this, wrapParents(members, this, this, alwaysInjectSuper));
                },
                /**
                 * Destructor function, performs the following:
                 *
                 * 1: Triggers a scopeName + name + ".destroy" (E.g. "jquery-plugincreator-myPlugin.destroy") event on the jQuery context (I.e. $(this) ) for the plugin instance.
                 * 2: Removes the scopeName + name (E.g. "jquery-plugincreator-myPlugin") class from the element linked to the plugin instance.
                 * 3: Removes the scopeName + name (E.g. "jquery-plugincreator-myPlugin") data value from the element linked to the plugin instance.
                 * 4: Removes the "data-" + scopeName + name (E.g. "data-jquery-plugincreator-myPlugin") attribute from the element linked to the plugin instance.
                 */
                destroy: function destroy() {
                    this.context.trigger(scopeName + name + ".destroy").removeClass(scopeName + name).removeData(scopeName + name).removeAttr("data-" + scopeName + name);
                }
            },
                members = $.isArray(members) ? members : [wrapParents(members, wrapParents(baseMembers, baseMembers, null, alwaysInjectSuper), null, alwaysInjectSuper)];

            /**
             * This function is used to instantiate an instance of the plugin on a given element.
             *
             * @param {Object} element
             * @param {Object} [options]
             * @param {Array} [initArguments]
             */
            function instantiatePlugin(element, options, initArguments) {
                var options = options || {},
                    prototype = $.extend(true, {}, members[0]),
                    instance = null;

                function pluginConstructor() {
                    this.instanceOf = name;
                    this.element = element;
                    this.context = $(element).addClass(scopeName + name);
                    this.options = $.extend(true, {}, defaults, options);
                    for (var memberName in prototype) {
                        if (typeof prototype[memberName] == "function" && prototype[memberName]._isParentGenerator) {
                            prototype[memberName] = prototype[memberName](this);
                        }
                    }
                    $.extend(true, this, prototype);
                    this.init.apply(this, initArguments);
                }

                instance = new pluginConstructor();
                $.data(element, scopeName + name, instance);
                return instance;
            }

            /**
             * A function to handle the actual process of instantiating a plugin instance or calling a method on
             * a given plugin instance.
             *
             * @param {Object} self
             * @param {Object|String} options
             * @param {Array} args
             * @returns {*}
             */
            function processPluginCall(self, options, args) {
                var instance = $.data(self, scopeName + name);
                if (instance) {
                    if (typeof options == "string" && typeof instance[options] == "function") {
                        // call a method on the instance
                        return instance[options].apply(instance, args.slice(1));
                    } else if (typeof instance.update == "function" && $.isPlainObject(options)) {
                        // call update on the instance
                        return instance.update.apply(instance, args);
                    } else {
                        throw options + " is not a member of " + self;
                    }
                } else {
                    return instantiatePlugin(self, options, args.slice(1));
                }
            }

            /**
             *
             * @param {Object|string} options
             * @returns {jQuery}
             */
            $.fn[name] = function (options) {
                var args = $.makeArray(arguments),
                    result = this;
                if (this.length === 1) {
                    result = processPluginCall(this[0], options, args);
                } else {
                    if (options === "map") {
                        result = this.map(function () {
                            return processPluginCall(this, args[1], args.slice(2));
                        });
                    } else {
                        result = this.each(function () {
                            processPluginCall(this, options, args);
                        });
                    }
                }
                if (typeof result == "undefined") result = this;
                return result;
            };

            /**
             *
             * @type {Object}
             */
            $.fn[name].defaults = defaults;

            /**
             *
             * @param {Object} options
             * @returns {Object}
             */
            $.fn[name].updateDefaultsWith = function (options) {
                $.extend(true, defaults, options);
                return defaults;
            };

            /**
             *
             * @param {Object} childMembers
             * @param {boolean} [alwaysInjectSuper=false]
             * @returns {function}
             */
            $.fn[name].extendMembersWith = function (childMembers) {
                var alwaysInjectSuper = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];

                members.unshift(wrapParents(childMembers, members[0], null, alwaysInjectSuper));
            };

            /**
             * Clones a plugin added using jQuery PluginCreator.
             *
             * While the defaults and members are cloned completely and are independent, the constructor is shared.
             *
             * @param {string} name
             * @param {string} newName
             * @returns {string}
             */
            $.fn[name].cloneTo = function (newName) {
                return pluginCreator.addPlugin(newName, defaults, $.extend(true, [], members));
            };

            /**
             * Extends a plugin added using jQuery PluginCreator.
             *
             * Defaults and members are cloned and extended from the original plugin while the extended constructor
             * functions such that the constructor for the original plugin is called first, then new new
             * constructor, if present.
             *
             * @param {string} name
             * @param {string} newName
             * @param {Object} [childMembers]
             * @return {string}
             */
            $.fn[name].extendTo = function (newName, childMembers) {
                $.fn[name].cloneTo(newName);
                $.fn[newName].extendMembersWith(childMembers);
            };

            return name;
        }
    };

    _jQuery2.default.extend(_jQuery2.default, pluginCreator);

    exports.default = pluginCreator.addPlugin;
});<|endoftext|>


<commit_before>/**
 * register singgle cell to sheet's cell registry
 * @param  {object} cell    cell object
 * @return {void}
 */
sheet.fx.registerCell = function(cell){
    this.cells[cell.getAddress()] = cell;

    if(this.affectedCell.indexOf(cell.getAddress()) == -1){
        this.affectedCell.push(cell.getAddress());
    }
};<commit_msg>add new config key: data , to instantiate the sheet data, format, and formula<commit_after>/**
 * register singgle cell to sheet's cell registry
 * @param  {object} cell    cell object
 * @return {void}
 */
sheet.fx.registerCell = function(cell){
    var address = cell.getAddress()
    this.cells[address] = cell;

    if(typeof this.config.data[address] != 'undefined'){
        var cellConfig = this.config.data[address];

        if(typeof cellConfig.value != 'undefined'){
            cell.setValue(cellConfig.value);
            cell.renderComputedValue();
        }

        if(typeof cellConfig.format != 'undefined'){
            cell.setFormat(cellConfig.format);
        }

        if(typeof cellConfig.formula != 'undefined'){
            cell.setFormula(cellConfig.formula);
        }
    }

    if(this.affectedCell.indexOf(cell.getAddress()) == -1){
        this.affectedCell.push(cell.getAddress());
    }
};<|endoftext|>


<commit_before>var express = require('express'),
    path = require('path'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    routes = require('./routes/index'),
    session = require('express-session'),
    fs = require('fs');

var app = express();
var port = 3000;

var root = '/home/songwooseok/Documents';
var dir = '/root';
var group = '/group';

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));
app.use(cookieParser());
app.use(session({secret : 'ssshhhhh'}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use(dir+'/', routes);

app.listen(port, function(){
    console.log('Server is running on ' + port);
    var watcher = require('./module/fileWatcher');
    watcher(root, dir);
    watcher(root, group);
});

module.exports = app;
<commit_msg>no message<commit_after>var express = require('express'),
    path = require('path'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    routes = require('./routes/index'),
    session = require('express-session'),
    fs = require('fs');

var app = express();
var port = 3000;

var root = '/home/songwooseok/Documents';
var dir = '/root';
var group = '/group';

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));
app.use(express.methodOverride());
app.use(express.multipart());
app.use(cookieParser());
app.use(session({secret : 'ssshhhhh'}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use(dir+'/', routes);

app.listen(port, function(){
    console.log('Server is running on ' + port);
    var watcher = require('./module/fileWatcher');
    watcher(root, dir);
    watcher(root, group);
});

module.exports = app;
<|endoftext|>


<commit_before>const yo = require('yo-yo')
const css = require('sheetify')
const barracks = require('barracks')
const chooPromise = require('choo-promise')

css('tachyons')
css`
  html, body {
    width: 100%;
    height: 100%;
  }

  main {
    width: 100%;
    min-height: 100%;
  }
`

const store = barracks()
store.use(chooPromise())
store.use({ onStateChange: render })
store.model(require('./model'))

const initView = require('./initView')
const mainView = require('./mainView')

const App = (state, send) => {
  var view = state.token ? mainView : initView
  return yo`

nanopush 📌

nanopush is a tool that sends push notifications. No installation. No registration.

${view(state, send)}

Created with 👌 by Rahat Ahmed

Github

  `
}

const createSend = store.start()
const _send = createSend('nanopush')
const send = (action, data) => _send(action, data, (err) => {
  // TODO: do something better with the errors
  if (err) console.error(err)
})

const el = App(store.state(), send)
document.body.appendChild(el)

function render (state) {
  setTimeout(() => {
    var newEl = App(state, send)
    yo.update(el, newEl)
  })
  console.log(state)
}
<commit_msg>Remove console.log<commit_after>const yo = require('yo-yo')
const css = require('sheetify')
const barracks = require('barracks')
const chooPromise = require('choo-promise')

css('tachyons')
css`
  html, body {
    width: 100%;
    height: 100%;
  }

  main {
    width: 100%;
    min-height: 100%;
  }
`

const store = barracks()
store.use(chooPromise())
store.use({ onStateChange: render })
store.model(require('./model'))

const initView = require('./initView')
const mainView = require('./mainView')

const App = (state, send) => {
  var view = state.token ? mainView : initView
  return yo`

nanopush 📌

nanopush is a tool that sends push notifications. No installation. No registration.

${view(state, send)}

Created with 👌 by Rahat Ahmed

Github

  `
}

const createSend = store.start()
const _send = createSend('nanopush')
const send = (action, data) => _send(action, data, (err) => {
  // TODO: do something better with the errors
  if (err) console.error(err)
})

const el = App(store.state(), send)
document.body.appendChild(el)

function render (state) {
  setTimeout(() => {
    var newEl = App(state, send)
    yo.update(el, newEl)
  })
}
<|endoftext|>


<commit_before>/*!
* jdMenu 1.4.1 (2008-03-31)
*
* Copyright (c) 2006,2007 Jonathan Sharp (http://jdsharp.us)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://jdsharp.us/
*
* Built upon jQuery 1.2.1 (http://jquery.com)
* This also requires the jQuery dimensions >= 1.2 plugin
*/

(function($){
	function addEvents(ul) {
		var settings = $.data( $(ul).parents().andSelf().filter('ul.jd_menu')[0], 'jdMenuSettings' );
		$('> li', ul)
			.bind('mouseenter.jdmenu mouseleave.jdmenu', function(evt) {
				$(this).toggleClass('jdm_hover');
				var ul = $('> ul', this);
				if ( ul.length == 1 ) {
					clearTimeout( this.$jdTimer );
					var enter = ( evt.type == 'mouseenter' );
					var fn = ( enter ? showMenu : hideMenu );
					this.$jdTimer = setTimeout(function() {
						fn( ul[0], settings.onAnimate, settings.isVertical );
					}, enter ? settings.showDelay : settings.hideDelay );
				}
			})
			.bind('click.jdmenu', function(evt) {
				var ul = $('> ul', this);
				if ( ul.length == 1 &&
					( settings.disableLinks == true || $(this).hasClass('accessible') ) ) {
					showMenu( ul, settings.onAnimate, settings.isVertical );
					return false;
				}

				// The user clicked the li and we need to trigger a click for the a
				if ( evt.target == this ) {
					var link = $('> a', evt.target).not('.accessible');
					if ( link.length > 0 ) {
						var a = link[0];
						if ( !a.onclick ) {
							window.open( a.href, a.target || '_self' );
						} else {
							$(a).trigger('click');
						}
					}
				}
				if ( settings.disableLinks ||
					( !settings.disableLinks && !$(this).parent().hasClass('jd_menu') ) ) {
					$(this).parent().jdMenuHide();
					evt.stopPropagation();
				}
			})
			.find('> a')
				.bind('focus.jdmenu blur.jdmenu', function(evt) {
					var p = $(this).parents('li:eq(0)');
					if ( evt.type == 'focus' ) {
						p.addClass('jdm_hover');
					} else {
						p.removeClass('jdm_hover');
					}
				})
				.filter('.accessible')
					.bind('click.jdmenu', function(evt) {
						evt.preventDefault();
					});
	}

	function showMenu(ul, animate, vertical) {
		var ul = $(ul);
		if ( ul.is(':visible') ) {
			return;
		}
		ul.bgiframe();
		var li = ul.parent();
		ul	.trigger('jdMenuShow')
			.positionBy({ 	target: 	li[0],
							targetPos: 	( vertical === true || !li.parent().hasClass('jd_menu') ? 1 : 3 ),
							elementPos: 0,
							hideAfterPosition: true
							});
		if ( !ul.hasClass('jdm_events') ) {
			ul.addClass('jdm_events');
			addEvents(ul);
		}
		li	.addClass('jdm_active')
			// Hide any adjacent menus
			.siblings('li').find('> ul:eq(0):visible')
				.each(function(){
					hideMenu( this );
				});
		if ( animate === undefined ) {
			ul.show();
		} else {
			animate.apply( ul[0], [true] );
		}
	}

	function hideMenu(ul, animate) {
		var ul = $(ul);
		$('.bgiframe', ul).remove();
		ul	.filter(':not(.jd_menu)')
			.find('> li > ul:eq(0):visible')
				.each(function() {
					hideMenu( this );
				})
			.end();
		if ( animate === undefined ) {
			ul.hide()
		} else {
			animate.apply( ul[0], [false] );
		}

		ul	.trigger('jdMenuHide')
			.parents('li:eq(0)')
				.removeClass('jdm_active jdm_hover')
			.end()
				.find('> li')
				.removeClass('jdm_active jdm_hover');
	}

	// Public methods
	$.fn.jdMenu = function(settings) {
		// Future settings: activateDelay
		var settings = $.extend({	// Time in ms before menu shows
									showDelay: 		200,
									// Time in ms before menu hides
									hideDelay: 		500,
									// Should items that contain submenus not
									// respond to clicks
									disableLinks:	true
									// This callback allows for you to animate menus
									//onAnimate:	null
									}, settings);
		if ( !$.isFunction( settings.onAnimate ) ) {
			settings.onAnimate = undefined;
		}
		return this.filter('ul.jd_menu').each(function() {
			$.data(	this,
					'jdMenuSettings',
					$.extend({ isVertical: $(this).hasClass('jd_menu_vertical') }, settings)
					);
			addEvents(this);
		});
	};

	$.fn.jdMenuUnbind = function() {
		$('ul.jdm_events', this)
			.unbind('.jdmenu')
			.find('> a').unbind('.jdmenu');
	};
	$.fn.jdMenuHide = function() {
		return this.filter('ul').each(function(){
			hideMenu( this );
		});
	};

	// Private methods and logic
	$(window)
		// Bind a click event to hide all visible menus when the document is clicked
		.bind('click.jdmenu', function(){
			$('ul.jd_menu ul:visible').jdMenuHide();
		});
})(jQuery);

// This initializes the menu
$(function() {
  $('ul.jd_menu').jdMenu();
});
<commit_msg>[PPP-4008] - Tweak in JDMenu because of jquery update. Use of andSelf() is deprecated<commit_after>/*!
* jdMenu 1.4.1 (2008-03-31)
*
* Copyright (c) 2006,2007 Jonathan Sharp (http://jdsharp.us)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://jdsharp.us/
*
* Built upon jQuery 1.2.1 (http://jquery.com)
* This also requires the jQuery dimensions >= 1.2 plugin
*/

(function($){
	function addEvents(ul) {
		var settings = $.data( $(ul).parents().addBack().filter('ul.jd_menu')[0], 'jdMenuSettings' );
		$('> li', ul)
			.bind('mouseenter.jdmenu mouseleave.jdmenu', function(evt) {
				$(this).toggleClass('jdm_hover');
				var ul = $('> ul', this);
				if ( ul.length == 1 ) {
					clearTimeout( this.$jdTimer );
					var enter = ( evt.type == 'mouseenter' );
					var fn = ( enter ? showMenu : hideMenu );
					this.$jdTimer = setTimeout(function() {
						fn( ul[0], settings.onAnimate, settings.isVertical );
					}, enter ? settings.showDelay : settings.hideDelay );
				}
			})
			.bind('click.jdmenu', function(evt) {
				var ul = $('> ul', this);
				if ( ul.length == 1 &&
					( settings.disableLinks == true || $(this).hasClass('accessible') ) ) {
					showMenu( ul, settings.onAnimate, settings.isVertical );
					return false;
				}

				// The user clicked the li and we need to trigger a click for the a
				if ( evt.target == this ) {
					var link = $('> a', evt.target).not('.accessible');
					if ( link.length > 0 ) {
						var a = link[0];
						if ( !a.onclick ) {
							window.open( a.href, a.target || '_self' );
						} else {
							$(a).trigger('click');
						}
					}
				}
				if ( settings.disableLinks ||
					( !settings.disableLinks && !$(this).parent().hasClass('jd_menu') ) ) {
					$(this).parent().jdMenuHide();
					evt.stopPropagation();
				}
			})
			.find('> a')
				.bind('focus.jdmenu blur.jdmenu', function(evt) {
					var p = $(this).parents('li:eq(0)');
					if ( evt.type == 'focus' ) {
						p.addClass('jdm_hover');
					} else {
						p.removeClass('jdm_hover');
					}
				})
				.filter('.accessible')
					.bind('click.jdmenu', function(evt) {
						evt.preventDefault();
					});
	}

	function showMenu(ul, animate, vertical) {
		var ul = $(ul);
		if ( ul.is(':visible') ) {
			return;
		}
		ul.bgiframe();
		var li = ul.parent();
		ul	.trigger('jdMenuShow')
			.positionBy({ 	target: 	li[0],
							targetPos: 	( vertical === true || !li.parent().hasClass('jd_menu') ? 1 : 3 ),
							elementPos: 0,
							hideAfterPosition: true
							});
		if ( !ul.hasClass('jdm_events') ) {
			ul.addClass('jdm_events');
			addEvents(ul);
		}
		li	.addClass('jdm_active')
			// Hide any adjacent menus
			.siblings('li').find('> ul:eq(0):visible')
				.each(function(){
					hideMenu( this );
				});
		if ( animate === undefined ) {
			ul.show();
		} else {
			animate.apply( ul[0], [true] );
		}
	}

	function hideMenu(ul, animate) {
		var ul = $(ul);
		$('.bgiframe', ul).remove();
		ul	.filter(':not(.jd_menu)')
			.find('> li > ul:eq(0):visible')
				.each(function() {
					hideMenu( this );
				})
			.end();
		if ( animate === undefined ) {
			ul.hide()
		} else {
			animate.apply( ul[0], [false] );
		}

		ul	.trigger('jdMenuHide')
			.parents('li:eq(0)')
				.removeClass('jdm_active jdm_hover')
			.end()
				.find('> li')
				.removeClass('jdm_active jdm_hover');
	}

	// Public methods
	$.fn.jdMenu = function(settings) {
		// Future settings: activateDelay
		var settings = $.extend({	// Time in ms before menu shows
									showDelay: 		200,
									// Time in ms before menu hides
									hideDelay: 		500,
									// Should items that contain submenus not
									// respond to clicks
									disableLinks:	true
									// This callback allows for you to animate menus
									//onAnimate:	null
									}, settings);
		if ( !$.isFunction( settings.onAnimate ) ) {
			settings.onAnimate = undefined;
		}
		return this.filter('ul.jd_menu').each(function() {
			$.data(	this,
					'jdMenuSettings',
					$.extend({ isVertical: $(this).hasClass('jd_menu_vertical') }, settings)
					);
			addEvents(this);
		});
	};

	$.fn.jdMenuUnbind = function() {
		$('ul.jdm_events', this)
			.unbind('.jdmenu')
			.find('> a').unbind('.jdmenu');
	};
	$.fn.jdMenuHide = function() {
		return this.filter('ul').each(function(){
			hideMenu( this );
		});
	};

	// Private methods and logic
	$(window)
		// Bind a click event to hide all visible menus when the document is clicked
		.bind('click.jdmenu', function(){
			$('ul.jd_menu ul:visible').jdMenuHide();
		});
})(jQuery);

// This initializes the menu
$(function() {
  $('ul.jd_menu').jdMenu();
});
<|endoftext|>


<commit_before>/*jslint white: true */
/*global SamsungController, String, Buffer, require, console */

var SamsungController = SamsungController || (function () {
  'use strict';

  /**
   * @author brian@bevey.org
   * @fileoverview Basic control over Samsung SmartTVs from 2011 onward via TCP
   *               web sockets using Node.js.
   * @note This is a full-scale rip-off of the fine work done here:
   *       http://forum.samygo.tv/viewtopic.php?f=12&t=1792
   */
  return {
    version : '0.0.0.0.1 alpha',
    /**
     * Whitelist of available key codes to use.  I'll probably put these in a
     * validator or something.
     */
    keymap  : ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'UP', 'DOWN', 'LEFT', 'RIGHT',
               'MENU', 'PRECH', 'GUIDE', 'INFO', 'RETURN', 'CH_LIST', 'EXIT', 'ENTER', 'SOURCE',
               'AD', 'PLAY', 'PAUSE', 'MUTE', 'PICTURE_SIZE', 'VOLUP', 'VOLDOWN', 'TOOLS',
               'POWEROFF', 'CHUP', 'CHDOWN', 'CONTENTS', 'W_LINK', 'RSS', 'MTS', 'CAPTION',
               'REWIND', 'FF', 'REC', 'STOP', 'TV', 'CONTENT', 'INTERNET', 'PC', 'HDMI1', 'OFF',
               'POWER', 'STANDBY', 'DUAL', 'SUBT', 'CHANUP', 'CHAN_UP', 'PROGUP', 'PROG_UP'
              ],

    base64_encode : function (string) {
      return new Buffer(string).toString('base64');
    },

    /**
     * Once the connection has been established, this chunk seems to validate
     * input source.
     * "This is who I am."
     */
    chunkOne : function () {
      var ipencoded  = this.base64_encode(this.myip),
          macencoded = this.base64_encode(this.mymac),
          message    = String.fromCharCode(0x64) + String.fromCharCode(0x00) + String.fromCharCode(ipencoded.length) + String.fromCharCode(0x00) + ipencoded + String.fromCharCode(macencoded.length) + String.fromCharCode(0x00) + macencoded + String.fromCharCode(this.base64_encode(this.remotename).length) + String.fromCharCode(0x00) + this.base64_encode(this.remotename);

      return String.fromCharCode(0x00) + String.fromCharCode(this.appstring.length) + String.fromCharCode(0x00) + this.appstring + String.fromCharCode(message.length) + String.fromCharCode(0x00) + message;
    },

    /**
     * This chunk seems to ask for permission to be used.  Once executed, it
     * should prompt you on your TV to allow the connection.
     * "May I come in?"
     */
    // TODO: Figure out how to intelligently ignore this method if already authenticated
    chunkTwo : function () {
      var message = String.fromCharCode(0xc8) + String.fromCharCode(0x00); // TODO: Something may be wrong here

      console.log('Authenticating');

      return String.fromCharCode(0x00) + String.fromCharCode(this.appstring.length) + String.fromCharCode(0x00) + this.appstring + String.fromCharCode(message.length) + String.fromCharCode(0x00) + message;
    },

    /**
     * This chunk seems to tell the TV which command to execute - or, text to
     * be inputted into fields.
     * "Will you please do this for me?"
     */
    // TODO: Allow text input.
    chunkThree : function () {
      var command = 'KEY_' + this.command,
          message = String.fromCharCode(0x00) + String.fromCharCode(0x00) + String.fromCharCode(0x00) + String.fromCharCode(this.base64_encode(command).length) + String.fromCharCode(0x00) + this.base64_encode(command);

      console.log('Executing: ' + this.command);

      return String.fromCharCode(0x00) + String.fromCharCode(this.tvappstring.length) + String.fromCharCode(0x00) + this.tvappstring + String.fromCharCode(message.length) + String.fromCharCode(0x00) + message;
    },

    send : function (config) {
      this.tvip        = config.tvip;
      this.myip        = config.myip;
      this.mymac       = config.mymac;
      this.command     = config.command     || '';
      this.text        = config.text        || '';
      this.tvport      = config.tvport      || 55000;
      this.appstring   = config.appstring   || "iphone..iapp.samsung";
      this.tvappstring = config.tvappstring || "iphone.UN60ES8000.iapp.samsung";
      this.remotename  = config.remotename  || "Raspberry Pi Samsung Remote";

      var that         = this,
          net          = require('net'),
          socket       = net.connect(this.tvport, this.tvip);

      socket.on('connect', function() {
        console.log('connected');

        socket.write(that.chunkOne());
      //   socket.write(that.chunkTwo());
        socket.write(that.chunkThree());

        socket.end();
      });

      socket.on('error', function(error) {
        console.log(error);
      });
    }
  };
} ());

// Example Usage (for now):
SamsungController.send({ command: 'VOLDOWN', tvip: '192.168.1.100', myip: '192.168.1.101', mymac: "00-00-00-00-00-00" });<commit_msg>Add comments regarding authentication problems.  Add in text input (tested and works).<commit_after>/*jslint white: true */
/*global SamsungController, String, Buffer, require, console */

var SamsungController = SamsungController || (function () {
  'use strict';

  /**
   * @author brian@bevey.org
   * @fileoverview Basic control over Samsung SmartTVs from 2011 onward via TCP
   *               web sockets using Node.js.
   * @note This is a full-scale rip-off of the fine work done here:
   *       http://forum.samygo.tv/viewtopic.php?f=12&t=1792
   */
  return {
    version : '0.0.0.0.1 alpha',
    /**
     * Whitelist of available key codes to use.  I'll probably put these in a
     * validator or something.
     */
    keymap  : ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'UP', 'DOWN', 'LEFT', 'RIGHT',
               'MENU', 'PRECH', 'GUIDE', 'INFO', 'RETURN', 'CH_LIST', 'EXIT', 'ENTER', 'SOURCE',
               'AD', 'PLAY', 'PAUSE', 'MUTE', 'PICTURE_SIZE', 'VOLUP', 'VOLDOWN', 'TOOLS',
               'POWEROFF', 'CHUP', 'CHDOWN', 'CONTENTS', 'W_LINK', 'RSS', 'MTS', 'CAPTION',
               'REWIND', 'FF', 'REC', 'STOP', 'TV', 'CONTENT', 'INTERNET', 'PC', 'HDMI1', 'OFF',
               'POWER', 'STANDBY', 'DUAL', 'SUBT', 'CHANUP', 'CHAN_UP', 'PROGUP', 'PROG_UP'
              ],

    base64_encode : function (string) {
      return new Buffer(string).toString('base64');
    },

    /**
     * Once the connection has been established, this chunk seems to validate
     * input source.
     * "This is who I am."
     */
    chunkOne : function () {
      var ipencoded  = this.base64_encode(this.myip),
          macencoded = this.base64_encode(this.mymac),
          message    = String.fromCharCode(0x64) + String.fromCharCode(0x00) + String.fromCharCode(ipencoded.length) + String.fromCharCode(0x00) + ipencoded + String.fromCharCode(macencoded.length) + String.fromCharCode(0x00) + macencoded + String.fromCharCode(this.base64_encode(this.remotename).length) + String.fromCharCode(0x00) + this.base64_encode(this.remotename);

      return String.fromCharCode(0x00) + String.fromCharCode(this.appstring.length) + String.fromCharCode(0x00) + this.appstring + String.fromCharCode(message.length) + String.fromCharCode(0x00) + message;
    },

    /**
     * This chunk seems to ask for permission to be used.  Once executed, it
     * should prompt you on your TV to allow the connection.
     * "May I come in?"
     */
    chunkTwo : function () {
      var message = String.fromCharCode(0xc8) + String.fromCharCode(0x00);
//                   TODO: ^^ Busted ^^
// fromCharCode starts to return unexpected (to me) results after it hits 128.  Not sure how to properly encode something as high as 200 (0xc8).
// Have been comparing base64 outputs from Perl (yA==) to base64 outputs from this (w5g=).  base64_decoding w56= seems to be 195 (0xc3).
      console.log('Authenticating');

      return String.fromCharCode(0x00) + String.fromCharCode(this.appstring.length) + String.fromCharCode(0x00) + this.appstring + String.fromCharCode(message.length) + String.fromCharCode(0x00) + message;
    },

    /**
     * This chunk seems to tell the TV which command to execute - or, text to
     * be inputted into fields.
     * "Will you please do this for me?"
     */
    chunkThree : function () {
      var command = 'KEY_' + this.command,
          message = '';

      if(this.command) {
        message = String.fromCharCode(0x00) + String.fromCharCode(0x00) + String.fromCharCode(0x00) + String.fromCharCode(this.base64_encode(command).length) + String.fromCharCode(0x00) + this.base64_encode(command);

        console.log('Executing: ' + this.command);

        return String.fromCharCode(0x00) + String.fromCharCode(this.tvappstring.length) + String.fromCharCode(0x00) + this.tvappstring + String.fromCharCode(message.length) + String.fromCharCode(0x00) + message;
      }

      if(this.text) {
        message = String.fromCharCode(0x01) + String.fromCharCode(0x00) + String.fromCharCode(this.base64_encode(this.text).length) + String.fromCharCode(0x00) + this.base64_encode(this.text);

        console.log('Text: ' + this.text);

        return String.fromCharCode(0x01) + String.fromCharCode(this.appstring.length) + String.fromCharCode(0x00) + this.appstring + String.fromCharCode(message.length) + String.fromCharCode(0x00) + message;
      }
    },

    send : function (config) {
      this.tvip        = config.tvip;
      this.myip        = config.myip;
      this.mymac       = config.mymac;
      this.command     = config.command     || '';
      this.text        = config.text        || '';
      this.tvport      = config.tvport      || 55000;
      this.appstring   = config.appstring   || "iphone..iapp.samsung";
      this.tvappstring = config.tvappstring || "iphone.UN60ES8000.iapp.samsung";
      this.remotename  = config.remotename  || "Raspberry Pi Samsung Remote";

      var that         = this,
          net          = require('net'),
          socket       = net.connect(this.tvport, this.tvip);

      socket.on('connect', function() {
        console.log('connected');

        socket.write(that.chunkOne());
// If you're already (somehow) authenticated, it'll work just commenting this line out.
// If you are not already authenticated...well...this script isn't very helpful (yet).
//        socket.write(that.chunkTwo());
        socket.write(that.chunkThree());

        socket.end();
      });

      socket.on('error', function(error) {
        console.log(error);
      });
    }
  };
} ());

// Example Usage (for now):
//SamsungController.send({ command: 'VOLDOWN', tvip: '192.168.1.100', myip: '192.168.1.101', mymac: "00-00-00-00-00-00" });<|endoftext|>