<commit_before>/**
 *  nodeca.io
 *
 *  This module provides realtime communication methods for nodeca/nlib based
 *  applications.
 **/

//= depend_on nodeca
//= require faye-browser

/*global window, $, _, Faye, nodeca*/

(function () {
  'use strict';

  var // registered events
      events = {},
      // underlying bayeux client
      bayeux = null,
      // stores last msg id for debug purposes
      // and last xhr to allow interrupt it
      rpc = {idx: 0, xhr: null};

  // exported IO object
  var io = nodeca.io = {};

  //
  // Errors
  //

  io.EWRONGVER  = 'IO_EWRONGVER';

  // error constructor
  function ioerr(code, message) {
    var err = new Error(message);
    err.code = code;
    return err;
  }

  //
  // Events
  //

  // executes all handlers registered for given `event`
  function emit(event, args) {
    _.each(events[event] || [], function (handler) {
      handler.apply(null, args);
    });
  }

  /**
   *  nodeca.io.on(event, handler) -> Void
   *  - event (String)
   *  - handler (Function)
   *
   *  Registers `handler` for an `event`.
   *
   *
   *  ##### Known events
   *
   *  - `connected`
   *  - `disconnected`
   *  - `rpc:version-mismatch({client: "str", server: "str"})`
   **/
  io.on = function on(event, handler) {
    if (!events[event]) {
      events[event] = [];
    }

    events[event].push(handler);
  };

  /**
   *  nodeca.io.off(event[, handler]) -> Void
   *  - event (String)
   *  - handler (Function)
   *
   *  Unsubscribes `handler` (or all handlers) from specified `event`.
   *
   *
   *  ##### See also
   *
   *  - [nodeca.io.on]
   **/
  io.off = function off(event, handler) {
    events[event] = (!handler) ? [] : _.without(events[event], handler);
  };

  //
  // Main API
  //

  function bayeux_call(name, args) {
    var result = bayeux[name].apply(bayeux, args);

    //
    // provide jQuery.Defered style methods
    //

    // FAYE DOCUMENTATION:
    //
    //  Bear in mind that ‘success’ here just means the server received and
    //  routed the message successfully, not that it has been received by all
    //  other clients.
    result.done = _.bind(function (fn) { this.callback(fn); return this; }, result);

    // FAYE DOCUMENTATION:
    //
    //  An error means the server found a problem processing the message.
    //  Network errors are not covered by this.
    result.fail = _.bind(function (fn) { this.errback(fn); return this; }, result);

    return result;
  }

  /**
   *  nodeca.io.subscribe(channel, handler) -> Object
   **/
  io.subscribe = function subscribe(channel, handler) {
    return bayeux_call('subscribe', [channel, handler]);
  };

  /**
   *  nodeca.io.unsubscribe(channel[, handler]) -> Object
   **/
  io.unsubscribe = function unsubscribe(channel, handler) {
    return bayeux_call('unsubscribe', [channel, handler]);
  };

  /**
   *  nodeca.io.publish(channel, message) -> Object
   **/
  io.publish = function publish(channel, message) {
    return bayeux_call('publish', [channel, message]);
  };

  /**
   *  nodeca.io.apiTree(name, params, options, callback) -> Void
   *  nodeca.io.apiTree(name, params[, callback]) -> Void
   *  nodeca.io.apiTree(name, callback) -> Void
   **/
  io.apiTree = function apiTree(name, params, options, callback) {
    var xhr, id = rpc.idx++, data = {id: id};

    // Scenario: rpc(name, callback);
    if (_.isFunction(params)) {
      callback = params;
      params   = options  = {};
    }

    // Scenario: rpc(name, params[, callback]);
    if (_.isFunction(options)) {
      callback = options;
      options = {};
    }

    // fill in defaults
    options   = options || {};
    callback  = callback || $.noop;

    //
    // Interrupt previous rpc request
    //

    if (rpc.xhr) {
      (rpc.xhr.reject || $.noop)();
      rpc.xhr = null;
    }

    // fill in message
    data.msg = {
      version:  nodeca.runtime.version,
      method:   name,
      params:   params
    };

    //
    // Send request
    //

    nodeca.logger.debug('API3 [' + id + '] Sending request', data.msg);
    xhr = rpc.xhr = $.post('/rpc', data);

    //
    // Listen for a response
    //

    xhr.success(function (msg) {
      nodeca.logger.debug('API3 [' + id + '] Received response ' +
                          '(' + String((msg || {}).result).length + ')', msg);

      if (msg.version !== nodeca.runtime.version) {
        // emit version mismatch error
        emit('rpc:version-mismatch', {
          client: nodeca.runtime.version,
          server: msg.version
        });
        callback(ioerr(io.EWRONGVER, 'Client version does not match server.'));
        return;
      }

      try {
        msg.result = JSON.parse(msg.result);
      } catch (err) {
        nodeca.logger.error('Failed parse result', err);
        callback(err);
        return;
      }

      // run actual callback
      callback(msg.err, msg.result);
    });

    //
    // Listen for an error
    //

    xhr.fail(function (err) {
      if (err) {
        // fire callback with error only in case of real error
        // and not due to our "previous request interruption"
        callback(err);
      }
    });
  };

  //
  // Initialization API
  //

  /**
   *  nodeca.io.init() -> Void
   **/
  io.init = function () {
    bayeux = new Faye.Client('/faye');

    if ('development' === nodeca.runtime.env) {
      // export some internals for debugging
      window.fontello_bayeux = bayeux;
    }

    //
    // once connected, client.getState() always returns 'CONNECTED' regardless
    // to the real state, so instead of relying on this state we use our own
    //

    bayeux.bind('transport:up',   function () {
      emit('connected');
    });

    bayeux.bind('transport:down', function () {
      emit('disconnected');
    });
  };
}());
<commit_msg>Fix io payload send<commit_after>/**
 *  nodeca.io
 *
 *  This module provides realtime communication methods for nodeca/nlib based
 *  applications.
 **/

//= depend_on nodeca
//= require faye-browser

/*global window, $, _, Faye, nodeca*/

(function () {
  'use strict';

  var // registered events
      events = {},
      // underlying bayeux client
      bayeux = null,
      // stores last msg id for debug purposes
      // and last xhr to allow interrupt it
      rpc = {idx: 0, xhr: null};

  // exported IO object
  var io = nodeca.io = {};

  //
  // Errors
  //

  io.EWRONGVER  = 'IO_EWRONGVER';

  // error constructor
  function ioerr(code, message) {
    var err = new Error(message);
    err.code = code;
    return err;
  }

  //
  // Events
  //

  // executes all handlers registered for given `event`
  function emit(event, args) {
    _.each(events[event] || [], function (handler) {
      handler.apply(null, args);
    });
  }

  /**
   *  nodeca.io.on(event, handler) -> Void
   *  - event (String)
   *  - handler (Function)
   *
   *  Registers `handler` for an `event`.
   *
   *
   *  ##### Known events
   *
   *  - `connected`
   *  - `disconnected`
   *  - `rpc:version-mismatch({client: "str", server: "str"})`
   **/
  io.on = function on(event, handler) {
    if (!events[event]) {
      events[event] = [];
    }

    events[event].push(handler);
  };

  /**
   *  nodeca.io.off(event[, handler]) -> Void
   *  - event (String)
   *  - handler (Function)
   *
   *  Unsubscribes `handler` (or all handlers) from specified `event`.
   *
   *
   *  ##### See also
   *
   *  - [nodeca.io.on]
   **/
  io.off = function off(event, handler) {
    events[event] = (!handler) ? [] : _.without(events[event], handler);
  };

  //
  // Main API
  //

  function bayeux_call(name, args) {
    var result = bayeux[name].apply(bayeux, args);

    //
    // provide jQuery.Defered style methods
    //

    // FAYE DOCUMENTATION:
    //
    //  Bear in mind that ‘success’ here just means the server received and
    //  routed the message successfully, not that it has been received by all
    //  other clients.
    result.done = _.bind(function (fn) { this.callback(fn); return this; }, result);

    // FAYE DOCUMENTATION:
    //
    //  An error means the server found a problem processing the message.
    //  Network errors are not covered by this.
    result.fail = _.bind(function (fn) { this.errback(fn); return this; }, result);

    return result;
  }

  /**
   *  nodeca.io.subscribe(channel, handler) -> Object
   **/
  io.subscribe = function subscribe(channel, handler) {
    return bayeux_call('subscribe', [channel, handler]);
  };

  /**
   *  nodeca.io.unsubscribe(channel[, handler]) -> Object
   **/
  io.unsubscribe = function unsubscribe(channel, handler) {
    return bayeux_call('unsubscribe', [channel, handler]);
  };

  /**
   *  nodeca.io.publish(channel, message) -> Object
   **/
  io.publish = function publish(channel, message) {
    return bayeux_call('publish', [channel, message]);
  };

  /**
   *  nodeca.io.apiTree(name, params, options, callback) -> Void
   *  nodeca.io.apiTree(name, params[, callback]) -> Void
   *  nodeca.io.apiTree(name, callback) -> Void
   **/
  io.apiTree = function apiTree(name, params, options, callback) {
    var xhr, id = rpc.idx++,
        payload = {id: id, version: nodeca.runtime.version, method: name};

    // Scenario: rpc(name, callback);
    if (_.isFunction(params)) {
      callback = params;
      params   = options  = {};
    }

    // Scenario: rpc(name, params[, callback]);
    if (_.isFunction(options)) {
      callback = options;
      options = {};
    }

    // fill in defaults
    options   = options || {};
    callback  = callback || $.noop;

    //
    // Interrupt previous rpc request
    //

    if (rpc.xhr) {
      (rpc.xhr.reject || $.noop)();
      rpc.xhr = null;
    }

    // fill in payload params
    payload.params = params;

    //
    // Send request
    //

    nodeca.logger.debug('API3 [' + id + '] Sending request', payload);
    xhr = rpc.xhr = $.post('/rpc', payload);

    //
    // Listen for a response
    //

    xhr.success(function (msg) {
      nodeca.logger.debug('API3 [' + id + '] Received response ' +
                          '(' + String((msg || {}).result).length + ')', msg);

      if (msg.version !== nodeca.runtime.version) {
        // emit version mismatch error
        emit('rpc:version-mismatch', {
          client: nodeca.runtime.version,
          server: msg.version
        });
        callback(ioerr(io.EWRONGVER, 'Client version does not match server.'));
        return;
      }

      try {
        msg.result = JSON.parse(msg.result);
      } catch (err) {
        nodeca.logger.error('Failed parse result', err);
        callback(err);
        return;
      }

      // run actual callback
      callback(msg.err, msg.result);
    });

    //
    // Listen for an error
    //

    xhr.fail(function (err) {
      if (err) {
        // fire callback with error only in case of real error
        // and not due to our "previous request interruption"
        callback(err);
      }
    });
  };

  //
  // Initialization API
  //

  /**
   *  nodeca.io.init() -> Void
   **/
  io.init = function () {
    bayeux = new Faye.Client('/faye');

    if ('development' === nodeca.runtime.env) {
      // export some internals for debugging
      window.fontello_bayeux = bayeux;
    }

    //
    // once connected, client.getState() always returns 'CONNECTED' regardless
    // to the real state, so instead of relying on this state we use our own
    //

    bayeux.bind('transport:up',   function () {
      emit('connected');
    });

    bayeux.bind('transport:down', function () {
      emit('disconnected');
    });
  };
}());
<|endoftext|>


<commit_before>var teammoldeApp = angular.module(
	"teammoldeApp",
	[
		'ngAnimate', 'ui.router'
	]
);

teammoldeApp
.config(
[
'$stateProvider', '$urlRouterProvider', '$sceProvider',
function ($stateProvider, $urlRouterProvider, $sceProvider)
{
	$sceProvider.enabled(false);

	$urlRouterProvider
		.otherwise('/');

	$stateProvider
		.state('home', {
			url: '/',
			views: {
				"main": {
					templateUrl: '/partials/home.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('priser', {
			url: '/priser',
			views: {
				"main": {
					templateUrl: '/partials/priser.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('larere', {
			url: '/larere',
			views: {
				"main": {
					templateUrl: '/partials/larere.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('bestill', {
			url: '/bestill',
			views: {
				"main": {
					templateUrl: '/partials/bestill.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('elevside', {
			url: '/elevside',
			views: {
				"main": {
					templateUrl: '/partials/elevside.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('manedensbestatt', {
			url: '/manedensbestatt',
			views: {
				"main": {
					templateUrl: '/partials/manedensbestatt.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('kontakt', {
			abstract: true,
			url: '/kontakt',
			views: {
				"main": {
					templateUrl: '/partials/kontakt.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})
	;

}
]
);

teammoldeApp
.filter('bstableizer',
function () {
	return function ( markup ) {
		return markup.replace('
', '
');
	};
}
);

teammoldeApp
.controller('homeCtrl',
[
'$scope',
function($scope) {
	var s = Snap("#background");

	Snap.load("assets/svg/background.svg", function (f) {
		s.append(f);
	});
}
]
);

teammoldeApp
.controller('PriserCtrl',
[
'$scope', 'wpData',
function($scope, wpData) {
	var s = Snap("#background");

	s.attr({
		filter : s.filter(Snap.filter.blur(10, 10))
	});

	$scope.pricelist = '';

	wpData.getPage('priser')
		.then(function(html) {
			$scope.pricelist = html;
		});
}
]
);

teammoldeApp
.service('wpData',
[
'$q', '$http',
function ( $q, $http )
{
	this.getPage = function( url ) {
		var deferred = $q.defer();

		$http.get('wordpress/' + url + '/?json=1', {cache: true})
			.success(function(result) {
				deferred.resolve(result.page.content);
			})
			.error(function(){
				deferred.reject();
			});

		return deferred.promise;
	};
}
]
);
<commit_msg>moving stuff to a service<commit_after>var teammoldeApp = angular.module(
	"teammoldeApp",
	[
		'ngAnimate', 'ui.router'
	]
);

teammoldeApp
.config(
[
'$stateProvider', '$urlRouterProvider', '$sceProvider',
function ($stateProvider, $urlRouterProvider, $sceProvider)
{
	$sceProvider.enabled(false);

	$urlRouterProvider
		.otherwise('/');

	$stateProvider
		.state('home', {
			url: '/',
			views: {
				"main": {
					templateUrl: '/partials/home.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('priser', {
			url: '/priser',
			views: {
				"main": {
					templateUrl: '/partials/priser.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('larere', {
			url: '/larere',
			views: {
				"main": {
					templateUrl: '/partials/larere.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('bestill', {
			url: '/bestill',
			views: {
				"main": {
					templateUrl: '/partials/bestill.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('elevside', {
			url: '/elevside',
			views: {
				"main": {
					templateUrl: '/partials/elevside.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('manedensbestatt', {
			url: '/manedensbestatt',
			views: {
				"main": {
					templateUrl: '/partials/manedensbestatt.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('kontakt', {
			abstract: true,
			url: '/kontakt',
			views: {
				"main": {
					templateUrl: '/partials/kontakt.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})
	;

}
]
);

teammoldeApp
.filter('bstableizer',
function () {
	return function ( markup ) {
		return markup.replace('
', '
');
	};
}
);

teammoldeApp
.controller('homeCtrl',
[
'$scope', 'bgSVG',
function($scope, bgSVG) {
}
]
);

teammoldeApp
.controller('PriserCtrl',
[
'$scope', 'wpData',
function($scope, wpData) {
	$scope.pricelist = '';

	wpData.getPage('priser')
		.then(function(html) {
			$scope.pricelist = html;
		});
}
]
);

teammoldeApp
.service('wpData',
[
'$q', '$http',
function ( $q, $http )
{
	this.getPage = function( url ) {
		var deferred = $q.defer();

		$http.get('wordpress/' + url + '/?json=1', {cache: true})
			.success(function(result) {
				deferred.resolve(result.page.content);
			})
			.error(function(){
				deferred.reject();
			});

		return deferred.promise;
	};
}
]
);

teammoldeApp
.service('bgSVG',
[
'$q',
function ( $q )
{
	var s = Snap("#background");

	Snap.load("assets/svg/background.svg", function (f) {
		s.append(f);
	});

	this.blur = function( url ) {

	};
}
]
);
<|endoftext|>


<commit_before>/**
 * @file MOZTracker main script
 * @author Matt Schoen
 * @version 0.1
 *
 * @namespace moztrack
 */
var moztrack = moztrack || {};
(function(){
	var progress;

	var startDate = new Date(2015, 5, 26, 12);
	var endDate = new Date(2015, 7, 6, 19, 17);

	var episodeNum = 2659;

	var showStartDate = new Date(1999, 0, 11);
	var showEndDate = new Date(2015, 8, 6);

	var showTime, realTime;

	var perEpisode = 28;
	var perEpisodeOverride = 24;
	moztrack.startOverride = new Date(2015,5,26,2,42);

	$(document).ready(function() {
		//Setup local DB
		moztrack.db = openDatabase('moztrack', '0.1', 'Daily show episodes', 1*1024*1024);
		//moztrack.createLocalStorage();
		//Screw it, just reset every time
		moztrack.clearLocalStorage();

		//Create tracker
		var content = document.getElementById("moztrack-content");
		progress = Div();

		content.appendChild(Div({}, ["Stream started at " + startDate]));
		content.appendChild(Div({}, ["Stream ends at " + endDate]));
		content.appendChild(Div({}, [sprintf("Stream duration: %.2f hours", (endDate - startDate) / (60 * 60 * 1000))]));
		content.appendChild(Div({}, ["Episode count: " + episodeNum]));
		perEpisode = (endDate - startDate) / episodeNum;
		content.appendChild(Div({}, [sprintf("Computed %.2f minutes per episode", ((perEpisode / (60 * 1000))))]));
		content.appendChild(Div({}, ["Episode length overridden to: " + perEpisodeOverride]));
		var realEpCount = ((endDate - startDate) / (60 * 1000) / perEpisodeOverride);
		content.appendChild(Div({}, [sprintf("Actual stream length: %.2f episodes", realEpCount)]));
		content.appendChild(Div({}, [sprintf("Skipped about %.2f episodes", (episodeNum - realEpCount))]));
		var overDiff = (startDate - moztrack.startOverride) / (24 * 60 * 1000);
		content.appendChild(Div({}, [sprintf("Start time override: " + moztrack.startOverride + ", which means %.2f/180 skipped episodes so far", overDiff)]));

		showTime = Input({},[],{"onkeyup":function(){
			var date = new Date(this.value);
			moztrack.getRealTime(date);
		}});

		realTime = Input({},[],{"onkeyup":function(){
			var date = new Date(this.value);
			moztrack.getShowTime(date);
		}});

		content.appendChild(Div({"style":"margin-top:25px;"},[
			Div({},[
				"Show Time: ", showTime,
				" Real Time: ", realTime
			]),
			Elm("button", {"type":"button"}, ["Reset Local Storage"], {"onclick":moztrack.clearLocalStorage}),
			progress
		]));

		//start on a delay for the first load
		// setTimeout(function(){
			// realTime.value = new Date().format("Y-m-d H:i:s");
			// moztrack.getShowTime(new Date());
		// }, 1500);
	});
	moztrack.createLocalStorage = function(){
		//If table exists, assume we've done this before
		doIfTableNotExist(moztrack.db, "episodes", function(){
			moztrack.db.transaction(function(tx){
				tx.executeSql('CREATE TABLE IF NOT EXISTS "episodes" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "guest" VARCHAR, "date" DATETIME NOT NULL, "realtime" DATETIME NOT NULL );', [],
					function(tx, results){
						//TODO: non-blocking solution
						$.ajax({
							//Use absolute URL for local testing, Chrome blocks ajax requests to file:///
							"url":"http://mtschoen.github.io/month-of-zen-tracker/episodes/all.json",
							//"url":"http://mtschoen.github.io/month-of-zen-tracker/episodes/" + 1999 + ".json",
							//"url":"episodes/" + episodeLists[i] + ".json",
							"crossDomain":true,
							"async":false,
							"success":function(data){
								episodeNum = data.length - 1;	//-1 for sept11
								var perEpisode = (endDate - startDate) / episodeNum;

								perEpisode = perEpisodeOverride * 60 * 1000;
								var streamTime = 0;
								var query = "INSERT INTO episodes (guest,date,realtime) VALUES (?,?,?)";
								episodeNum = 0;
								console.log(moztrack.startOverride);
								for(var j in data){
									//Skip over the unaired sept11 episode
									if(data[j].extra == "sept11")
										continue;
									episodeNum++;
									data[j].date = new Date(data[j].date);

									progress.innerHTML = j;

									var realtime = moztrack.startOverride.getTime() + streamTime;
									tx.executeSql(query, [data[j].guest, data[j].date.getTime(), realtime],
										function(tx, results){

										},
										function(tx, error){
											console.log(error);
											console.log(query);
											console.log(data[j].guest, data[j].date.format("Y-m-d"));
											throw error;
										}
									);
									streamTime += perEpisode;
								}
							}
						});
					},
					function(tx, error){
						console.log(error);
						throw error;
					}
				);
			});
		});
	};
	moztrack.clearLocalStorage = function(){
		moztrack.db.transaction(function(tx){
			tx.executeSql("DROP TABLE IF EXISTS episodes;",[],
			function(){

			},
			function(tx, error){
				throw error;
			});
		});
		moztrack.createLocalStorage();
		setTimeout(function(){
			realTime.value = new Date().format("Y-m-d H:i:s");
			moztrack.getShowTime(new Date());
		}, 1000);
		ga('send', 'event', 'clearStorage');
	};

	function doIfTableNotExist(db, table, callback){
		db.transaction(function(tx){
			tx.executeSql("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", ["table", table],
				function(tx, results){
					if(results.rows[0]["COUNT(*)"] == 0)
						callback();
				},
				function(tx, error){
					throw error;
				}
			);
		});
	}

	moztrack.getRealTime = function(date){
		if(date < showStartDate || date > showEndDate){
			console.log("Invalid show date: ", date, showStartDate);
			ga('send', 'event', 'getRealTimeInvalid', date.format("Y-m-d H:i:s"));
			return;
		}
		ga('send', 'event', 'getRealTime', date.format("Y-m-d"));
		ga('send', 'event', 'getRealTimeFull', date.format("Y-m-d H:i:s"));
		moztrack.db.transaction(function(tx){
			tx.executeSql("SELECT * FROM episodes WHERE date >= ? ORDER BY date LIMIT 1", [date.getTime()],
			function(tx, results){
				if(results.rows.length > 0){
					progress.innerHTML = "Guest: " + results.rows[0].guest + "";
					realTime.value = new Date(results.rows[0].realtime).format("Y-m-d H:i:s");
				} else {
					console.log("no results?");
				}
			},
			function(tx, error){
				console.log(error);
				throw error;
			});
		});
	};
	moztrack.getShowTime = function(date){
		if(date < startDate || date > endDate){
			console.log("Invalid real date");
			ga('send', 'event', 'getShowTimeInvalid', date.format("Y-m-d H:i:s"));
			return;
		}
		ga('send', 'event', 'getShowTimeFull', date.format("Y-m-d H:i:s"));
		moztrack.db.transaction(function(tx){
			tx.executeSql("SELECT * FROM episodes WHERE realtime <= ? ORDER BY date DESC LIMIT 1", [date.getTime()],
			function(tx, results){
				if(results.rows.length > 0){
					progress.innerHTML = "Guest: " + results.rows[0].guest + "";
					showTime.value = new Date(results.rows[0].date).format("Y-m-d");
				} else {
					console.log("no results?");
				}
			},
			function(tx, error){
				console.log(error);
				throw error;
			});
		});
	};
})();
<commit_msg>Update main.js<commit_after>/**
 * @file MOZTracker main script
 * @author Matt Schoen
 * @version 0.1
 *
 * @namespace moztrack
 */
var moztrack = moztrack || {};
(function(){
	var progress;

	var startDate = new Date(2015, 5, 26, 12);
	var endDate = new Date(2015, 7, 6, 19, 17);

	var episodeNum = 2659;

	var showStartDate = new Date(1999, 0, 11);
	var showEndDate = new Date(2015, 8, 6);

	var showTime, realTime;

	var perEpisode = 28;
	var perEpisodeOverride = 24;
	moztrack.startOverride = new Date(2015,5,26,2,38);

	$(document).ready(function() {
		//Setup local DB
		moztrack.db = openDatabase('moztrack', '0.1', 'Daily show episodes', 1*1024*1024);
		//moztrack.createLocalStorage();
		//Screw it, just reset every time
		moztrack.clearLocalStorage();

		//Create tracker
		var content = document.getElementById("moztrack-content");
		progress = Div();

		content.appendChild(Div({}, ["Stream started at " + startDate]));
		content.appendChild(Div({}, ["Stream ends at " + endDate]));
		content.appendChild(Div({}, [sprintf("Stream duration: %.2f hours", (endDate - startDate) / (60 * 60 * 1000))]));
		content.appendChild(Div({}, ["Episode count: " + episodeNum]));
		perEpisode = (endDate - startDate) / episodeNum;
		content.appendChild(Div({}, [sprintf("Computed %.2f minutes per episode", ((perEpisode / (60 * 1000))))]));
		content.appendChild(Div({}, ["Episode length overridden to: " + perEpisodeOverride]));
		var realEpCount = ((endDate - startDate) / (60 * 1000) / perEpisodeOverride);
		content.appendChild(Div({}, [sprintf("Actual stream length: %.2f episodes", realEpCount)]));
		content.appendChild(Div({}, [sprintf("Skipped about %.2f episodes", (episodeNum - realEpCount))]));
		var overDiff = (startDate - moztrack.startOverride) / (24 * 60 * 1000);
		content.appendChild(Div({}, [sprintf("Start time override: " + moztrack.startOverride + ", which means %.2f/180 skipped episodes so far", overDiff)]));

		showTime = Input({},[],{"onkeyup":function(){
			var date = new Date(this.value);
			moztrack.getRealTime(date);
		}});

		realTime = Input({},[],{"onkeyup":function(){
			var date = new Date(this.value);
			moztrack.getShowTime(date);
		}});

		content.appendChild(Div({"style":"margin-top:25px;"},[
			Div({},[
				"Show Time: ", showTime,
				" Real Time: ", realTime
			]),
			Elm("button", {"type":"button"}, ["Reset Local Storage"], {"onclick":moztrack.clearLocalStorage}),
			progress
		]));

		//start on a delay for the first load
		// setTimeout(function(){
			// realTime.value = new Date().format("Y-m-d H:i:s");
			// moztrack.getShowTime(new Date());
		// }, 1500);
	});
	moztrack.createLocalStorage = function(){
		//If table exists, assume we've done this before
		doIfTableNotExist(moztrack.db, "episodes", function(){
			moztrack.db.transaction(function(tx){
				tx.executeSql('CREATE TABLE IF NOT EXISTS "episodes" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "guest" VARCHAR, "date" DATETIME NOT NULL, "realtime" DATETIME NOT NULL );', [],
					function(tx, results){
						//TODO: non-blocking solution
						$.ajax({
							//Use absolute URL for local testing, Chrome blocks ajax requests to file:///
							"url":"http://mtschoen.github.io/month-of-zen-tracker/episodes/all.json",
							//"url":"http://mtschoen.github.io/month-of-zen-tracker/episodes/" + 1999 + ".json",
							//"url":"episodes/" + episodeLists[i] + ".json",
							"crossDomain":true,
							"async":false,
							"success":function(data){
								episodeNum = data.length - 1;	//-1 for sept11
								var perEpisode = (endDate - startDate) / episodeNum;

								perEpisode = perEpisodeOverride * 60 * 1000;
								var streamTime = 0;
								var query = "INSERT INTO episodes (guest,date,realtime) VALUES (?,?,?)";
								episodeNum = 0;
								console.log(moztrack.startOverride);
								for(var j in data){
									//Skip over the unaired sept11 episode
									if(data[j].extra == "sept11")
										continue;
									episodeNum++;
									data[j].date = new Date(data[j].date);

									progress.innerHTML = j;

									var realtime = moztrack.startOverride.getTime() + streamTime;
									tx.executeSql(query, [data[j].guest, data[j].date.getTime(), realtime],
										function(tx, results){

										},
										function(tx, error){
											console.log(error);
											console.log(query);
											console.log(data[j].guest, data[j].date.format("Y-m-d"));
											throw error;
										}
									);
									streamTime += perEpisode;
								}
							}
						});
					},
					function(tx, error){
						console.log(error);
						throw error;
					}
				);
			});
		});
	};
	moztrack.clearLocalStorage = function(){
		moztrack.db.transaction(function(tx){
			tx.executeSql("DROP TABLE IF EXISTS episodes;",[],
			function(){

			},
			function(tx, error){
				throw error;
			});
		});
		moztrack.createLocalStorage();
		setTimeout(function(){
			realTime.value = new Date().format("Y-m-d H:i:s");
			moztrack.getShowTime(new Date());
		}, 1000);
		ga('send', 'event', 'clearStorage');
	};

	function doIfTableNotExist(db, table, callback){
		db.transaction(function(tx){
			tx.executeSql("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", ["table", table],
				function(tx, results){
					if(results.rows[0]["COUNT(*)"] == 0)
						callback();
				},
				function(tx, error){
					throw error;
				}
			);
		});
	}

	moztrack.getRealTime = function(date){
		if(date < showStartDate || date > showEndDate){
			console.log("Invalid show date: ", date, showStartDate);
			ga('send', 'event', 'getRealTimeInvalid', date.format("Y-m-d H:i:s"));
			return;
		}
		ga('send', 'event', 'getRealTime', date.format("Y-m-d"));
		ga('send', 'event', 'getRealTimeFull', date.format("Y-m-d H:i:s"));
		moztrack.db.transaction(function(tx){
			tx.executeSql("SELECT * FROM episodes WHERE date >= ? ORDER BY date LIMIT 1", [date.getTime()],
			function(tx, results){
				if(results.rows.length > 0){
					progress.innerHTML = "Guest: " + results.rows[0].guest + "";
					realTime.value = new Date(results.rows[0].realtime).format("Y-m-d H:i:s");
				} else {
					console.log("no results?");
				}
			},
			function(tx, error){
				console.log(error);
				throw error;
			});
		});
	};
	moztrack.getShowTime = function(date){
		if(date < startDate || date > endDate){
			console.log("Invalid real date");
			ga('send', 'event', 'getShowTimeInvalid', date.format("Y-m-d H:i:s"));
			return;
		}
		ga('send', 'event', 'getShowTimeFull', date.format("Y-m-d H:i:s"));
		moztrack.db.transaction(function(tx){
			tx.executeSql("SELECT * FROM episodes WHERE realtime <= ? ORDER BY date DESC LIMIT 1", [date.getTime()],
			function(tx, results){
				if(results.rows.length > 0){
					progress.innerHTML = "Guest: " + results.rows[0].guest + "";
					showTime.value = new Date(results.rows[0].date).format("Y-m-d");
				} else {
					console.log("no results?");
				}
			},
			function(tx, error){
				console.log(error);
				throw error;
			});
		});
	};
})();
<|endoftext|>


<commit_before>module.exports = {
  title: 'Animación',
  subtitle: '',
  description: `
    Para hacer animaciones con glamorous, puedes usar las transiciones regulares de CSS para cosas sencillas,
    y para cosas más avanzadas, puedes usar ~keyframes~ vía ~glamor~'s ~css.keyframes~
    API.

    ~~~js
    // importamos css desde glamor
    import { css } from 'glamor'

    // Definimos los estilos de animación
    const animationStyles = props => {
      const bounce = css.keyframes({
        '0%': { transform: ~scale(1.01)~ },
        '100%': { transform: ~scale(0.99)~ }
      })
      return {animation: ~\${bounce} 0.2s infinite ease-in-out alternate~}
    }

    // Definimos el elemento
    const AnimatedDiv = glamorous.div(animationStyles)

    // Y lo Utilizamos en una función render
    <AnimatedDiv>
      Bounce.
    </AnimatedDiv>
    ~~~
  `.replace(/~/g, '`'),
  codeSandboxId: '31VMyP7XO',
  codeSandboxSummary: 'Ejemplo de animación',
  filename: __filename,
}
<commit_msg>Correct translation of the description.<commit_after>module.exports = {
  title: 'Animación',
  subtitle: '',
  description: `
    Para hacer animaciones con glamorous, puedes usar las transiciones regulares de CSS para cosas sencillas,
    y para cosas más avanzadas, puedes usar ~keyframes~ a través de la API ~css.keyframes~ de ~glamor~.

    ~~~js
    // importamos css desde glamor
    import { css } from 'glamor'

    // Definimos los estilos de animación
    const animationStyles = props => {
      const bounce = css.keyframes({
        '0%': { transform: ~scale(1.01)~ },
        '100%': { transform: ~scale(0.99)~ }
      })
      return {animation: ~\${bounce} 0.2s infinite ease-in-out alternate~}
    }

    // Definimos el elemento
    const AnimatedDiv = glamorous.div(animationStyles)

    // Y lo utilizamos en una función render
    <AnimatedDiv>
      Bounce.
    </AnimatedDiv>
    ~~~
  `.replace(/~/g, '`'),
  codeSandboxId: '31VMyP7XO',
  codeSandboxSummary: 'Ejemplo de animación',
  filename: __filename,
}
<|endoftext|>


<commit_before>module.exports = {
  modulePaths: ['<rootDir>/dist'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  verbose: true,
  collectCoverage: false,
  coverageReporters: ['lcov', 'text', 'text-summary'],
  collectCoverageFrom: ['<rootDir>/dist/**/*js'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.test.json',
    },
  },
};
<commit_msg>Increase testTimeout<commit_after>module.exports = {
  modulePaths: ['<rootDir>/dist'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  verbose: true,
  collectCoverage: false,
  coverageReporters: ['lcov', 'text', 'text-summary'],
  collectCoverageFrom: ['<rootDir>/dist/**/*js'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.test.json',
    },
  },
  testTimeout: 30000,
};
<|endoftext|>


<commit_before>'use strict'

let Rescue = require('../db').Rescue
let User = require('../db').User
let Rat = require('../db').Rat
let Decals = require('../db').Decal
let Error = require('../errors')

const originalDecalDeadline = '2016-04-01 00:00:00+00'
const currentDecalDeadline = '2017-05-01 00:00:00+00'
const rescueParticipationRequirement = 10

class Decal {
  static checkEligble (user) {
    return new Promise(function (resolve, reject) {
      Decals.findOne({
        where: {
          userId: user.id
        }
      }).then(function (decal) {
        if (decal) {
          return resolve(decal)
        }

        checkEligibleForOriginalDecal(user).then(function (previouslyEligible) {
          if (previouslyEligible && previouslyEligible.rats) {
            for (let rat of previouslyEligible.rats) {
              if (rat.firstLimpet.length > 0) {
                return reject(Error.throw('bad_request', 'User qualifies for originally issued decal'))
              }
            }
          }

          checkEligibleForRescueDecal(user).then(function (eligible) {
            if (eligible && eligible.rats) {
              for (let rat of eligible.rats) {
                if (rat.firstLimpet.length >= rescueParticipationRequirement) {
                  return resolve(true)
                }
              }
            }
            reject(Error.throw('bad_request', 'User does not qualify for any decal'))
          })
        })
      }).catch(function (error) {
        reject (Error.throw('server_error', error))
      })
    })
  }

  static getDecalForUser (user) {
    return new Promise(function (resolve, reject) {
      Decal.checkEligble(user).then(function (decal) {
        if (decal === true) {
          Decal.redeem(user, 'Rescues').then(function (decal) {
            if (!decal) {
              return reject('Could not find decal')
            }
            resolve(decal)
          })
        } else {
          resolve(decal)
        }
      }).catch(function (error) {
        reject(error)
      })
    })
  }

  static redeem (user, type, notes = '') {
    return new Promise(function (resolve, reject) {
      Decals.findOne({
        where: {
          userId: null,
          type: 'Rescues'
        }
      }).then(function (availableDecal) {
        if (!availableDecal) {
          reject('Could not find any available decals')
        }

        availableDecal.update({
          userId: user.id,
          notes: notes,
          claimedAt: Date.now()
        }).then(function (decal) {
          resolve(decal)
        })
      }).catch(function (error) {
        reject(error)
      })
    })
  }
}

function checkEligibleForOriginalDecal (user) {
  return User.findOne({
    where: {
      id: user.id
    },
    include: [{
      required: true,
      model: Rat,
      as: 'rats',
      include: [{
        required: true,
        where: {
          createdAt: {
            $lt: originalDecalDeadline
          },
          successful: true
        },
        limit: rescueParticipationRequirement,
        model: Rescue,
        as: 'firstLimpet'
      }]
    }]
  })
}

function checkEligibleForRescueDecal (user) {
  return User.findOne({
    where: {
      id: user.id
    },
    include: [{
      required: true,
      model: Rat,
      as: 'rats',
      include: [{
        required: true,
        where: {
          createdAt: {
            $lt: currentDecalDeadline
          },
          successful: true
        },
        limit: rescueParticipationRequirement,
        model: Rescue,
        as: 'firstLimpet'
      }]
    }]
  })
}

module.exports = Decal<commit_msg>Remove query limit in decal verification due to ORM bug (temporary quick fix)<commit_after>'use strict'

let Rescue = require('../db').Rescue
let User = require('../db').User
let Rat = require('../db').Rat
let Decals = require('../db').Decal
let Error = require('../errors')

const originalDecalDeadline = '2016-04-01 00:00:00+00'
const currentDecalDeadline = '2017-05-01 00:00:00+00'
const rescueParticipationRequirement = 10

class Decal {
  static checkEligble (user) {
    return new Promise(function (resolve, reject) {
      Decals.findOne({
        where: {
          userId: user.id
        }
      }).then(function (decal) {
        if (decal) {
          return resolve(decal)
        }

        checkEligibleForOriginalDecal(user).then(function (previouslyEligible) {
          if (previouslyEligible && previouslyEligible.rats) {
            for (let rat of previouslyEligible.rats) {
              if (rat.firstLimpet.length > 0) {
                return reject(Error.throw('bad_request', 'User qualifies for originally issued decal'))
              }
            }
          }

          checkEligibleForRescueDecal(user).then(function (eligible) {
            if (eligible && eligible.rats) {
              for (let rat of eligible.rats) {
                if (rat.firstLimpet.length >= rescueParticipationRequirement) {
                  return resolve(true)
                }
              }
            }
            reject(Error.throw('bad_request', 'User does not qualify for any decal'))
          })
        })
      }).catch(function (error) {
        reject (Error.throw('server_error', error))
      })
    })
  }

  static getDecalForUser (user) {
    return new Promise(function (resolve, reject) {
      Decal.checkEligble(user).then(function (decal) {
        if (decal === true) {
          Decal.redeem(user, 'Rescues').then(function (decal) {
            if (!decal) {
              return reject('Could not find decal')
            }
            resolve(decal)
          })
        } else {
          resolve(decal)
        }
      }).catch(function (error) {
        reject(error)
      })
    })
  }

  static redeem (user, type, notes = '') {
    return new Promise(function (resolve, reject) {
      Decals.findOne({
        where: {
          userId: null,
          type: 'Rescues'
        }
      }).then(function (availableDecal) {
        if (!availableDecal) {
          reject('Could not find any available decals')
        }

        availableDecal.update({
          userId: user.id,
          notes: notes,
          claimedAt: Date.now()
        }).then(function (decal) {
          resolve(decal)
        })
      }).catch(function (error) {
        reject(error)
      })
    })
  }
}

function checkEligibleForOriginalDecal (user) {
  return User.findOne({
    where: {
      id: user.id
    },
    include: [{
      required: true,
      model: Rat,
      as: 'rats',
      include: [{
        required: true,
        where: {
          createdAt: {
            $lt: originalDecalDeadline
          },
          successful: true
        },
        model: Rescue,
        as: 'firstLimpet'
      }]
    }]
  })
}

function checkEligibleForRescueDecal (user) {
  return User.findOne({
    where: {
      id: user.id
    },
    include: [{
      required: true,
      model: Rat,
      as: 'rats',
      include: [{
        required: true,
        where: {
          createdAt: {
            $lt: currentDecalDeadline
          },
          successful: true
        },
        model: Rescue,
        as: 'firstLimpet'
      }]
    }]
  })
}

module.exports = Decal<|endoftext|>


<commit_before>var _ = require('lodash')
var Device = require('./Device')

module.exports =  _.merge(_.cloneDeep(Device), {
  attributes: {
    getStatus: function () {
      return new Promise((resolve, reject) => {
        this.insteonClient().level()
        .then((result) => {
          if (result !== undefined && result !== null && result !== '') {
            var level = parseInt(result)
            var status = (level === 0 ? 'off' : 'on')
            console.log(`[${this.insteonId}] Dimmer is at ${level}%`)
            resolve({ status: status, level: level })
          } else {
            reject(new Error(`Unable to get status for dimmer ${this.insteonId}`))
          }
        }, reason => {
          reject(reason)
        })
      })
    },

    refresh: function () {
      this.insteonClient().level()
      .then((result) => {
        if (result !== undefined && result !== null && result !== '') {
          var level = parseInt(result)
          var status = (level === 0 ? 'off' : 'on')
          console.log(`[${this.insteonId}] Dimmer is at ${level}%`)
          this.sendSmartThingsUpdate({ command: 'refresh', status: status, level: level })
        } else {
          console.log(`Unable to get status for dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error getting status for dimmer ${this.insteonId}`)
      })
    },

    turnOn: function () {
      this.insteonClient().turnOn()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'turn_on', status: 'on', level: '100' })
        } else {
          console.log(`Unable to turn on dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error turning on dimmer ${this.insteonId}`)
      })
    },

    turnOff: function () {
      this.insteonClient().turnOff()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'turn_off', status: 'off', level: 0 })
        } else {
          console.log(`Unable to turn off dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error turning off dimmer ${this.insteonId}`)
      })
    },

    setLevel: function (level) {
      this.insteonClient().level(level)
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          var status = (level === 0 ? 'off' : 'on')
          this.sendSmartThingsUpdate({ command: 'set_level', status: status, level: level })
        } else {
          console.log(`Unable to set level for dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error setting level for dimmer ${this.insteonId}`)
      })
    },

    brighten: function () {
      this.insteonClient().brighten()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'brighten' })
        } else {
          console.log(`Unable to brighten dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error brightening dimmer ${this.insteonId}`)
      })
    },

    dim: function () {
      this.insteonClient().dim()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
        } else {
          console.log(`Unable to lower dimmer ${this.insteonId}`)
          this.sendSmartThingsUpdate({ command: 'dim' })
        }
      }, reason => {
        console.log(`Error lowering dimmer ${this.insteonId}`)
      })
    },

    subscribeEvents: function () {
      console.log(`[${this.insteonId}] Subscribing to dimmer events...`)
      var light = this.insteonClient()

      light.on('turnOn', (group, level) => {
        console.log(`[${this.insteonId}] Dimmer turned ON`)
        if (level === null) {
          this.getStatus()
          .then((result) => {
            this.sendSmartThingsUpdate({ event: 'turn_on', status: result['status'], level: result['level'] })
          }, reason => {
            this.sendSmartThingsUpdate({ event: 'turn_on', status: 'on' })
          })
        } else {
          this.sendSmartThingsUpdate({ event: 'turn_on', status: 'on', level: level })
        }
      })

      light.on('turnOnFast', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned ON FAST`)
        this.sendSmartThingsUpdate({ event: 'turn_on_fast', status: 'on', level: 100 })
      })

      light.on('turnOff', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned OFF`)
        this.sendSmartThingsUpdate({ event: 'turn_off', status: 'off', level: 0 })
      })

      light.on('turnOffFast', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned OFF FAST`)
        this.sendSmartThingsUpdate({ event: 'turn_off_fast', status: 'off', level: 0 })
      })

      light.on('brightening', (group) => {
        console.log(`[${this.insteonId}] Dimmer brightening`)
        this.sendSmartThingsUpdate({ event: 'brightening' })
      })

      light.on('brightened', (group) => {
        console.log(`[${this.insteonId}] Dimmer brightened`)
        this.getStatus()
        .then((result) => {
          this.sendSmartThingsUpdate({ event: 'brightened', status: result['status'], level: result['level'] })
        }, reason => {
          this.sendSmartThingsUpdate({ event: 'brightened' })
        })
      })

      light.on('dimming', (group) => {
        console.log(`[${this.insteonId}] Dimmer dimming`)
        this.sendSmartThingsUpdate({ event: 'dimming' })
      })

      light.on('dimmed', (group) => {
        console.log(`[${this.insteonId}] Dimmer dimmed`)
        this.sendSmartThingsUpdate({ event: 'dimmed' })
        this.getStatus()
        .then((result) => {
          this.sendSmartThingsUpdate({ event: 'dimmed', status: result['status'], level: result['level'] })
        }, reason => {
          this.sendSmartThingsUpdate({ event: 'dimmed' })
        })
      })

      console.log(`[${this.insteonId}] Subscribed to dimmer events`)
    },

    startPolling: function () {
      this.refresh()
      setInterval(() => {
        this.refresh()
      }, this.refreshSeconds * 1000)
    }
  },

  beforeValidate: function (attrs, cb) {
    attrs.type = 'dimmer'
    cb()
  }
})
<commit_msg>Bug fix<commit_after>var _ = require('lodash')
var Device = require('./Device')

module.exports =  _.merge(_.cloneDeep(Device), {
  attributes: {
    getStatus: function () {
      return new Promise((resolve, reject) => {
        this.insteonClient().level()
        .then((result) => {
          if (result !== undefined && result !== null && result !== '') {
            var level = parseInt(result)
            var status = (level === 0 ? 'off' : 'on')
            console.log(`[${this.insteonId}] Dimmer is at ${level}%`)
            resolve({ status: status, level: level })
          } else {
            reject(new Error(`Unable to get status for dimmer ${this.insteonId}`))
          }
        }, reason => {
          reject(reason)
        })
      })
    },

    refresh: function () {
      this.insteonClient().level()
      .then((result) => {
        if (result !== undefined && result !== null && result !== '') {
          var level = parseInt(result)
          var status = (level === 0 ? 'off' : 'on')
          console.log(`[${this.insteonId}] Dimmer is at ${level}%`)
          this.sendSmartThingsUpdate({ command: 'refresh', status: status, level: level })
        } else {
          console.log(`Unable to get status for dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error getting status for dimmer ${this.insteonId}`)
      })
    },

    turnOn: function () {
      this.insteonClient().turnOn()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'turn_on', status: 'on', level: '100' })
        } else {
          console.log(`Unable to turn on dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error turning on dimmer ${this.insteonId}`)
      })
    },

    turnOff: function () {
      this.insteonClient().turnOff()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'turn_off', status: 'off', level: 0 })
        } else {
          console.log(`Unable to turn off dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error turning off dimmer ${this.insteonId}`)
      })
    },

    setLevel: function (level) {
      level = parseInt(level)
      this.insteonClient().level(level)
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          var status = (level === 0 ? 'off' : 'on')
          this.sendSmartThingsUpdate({ command: 'set_level', status: status, level: level })
        } else {
          console.log(`Unable to set level for dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error setting level for dimmer ${this.insteonId}`)
      })
    },

    brighten: function () {
      this.insteonClient().brighten()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'brighten' })
        } else {
          console.log(`Unable to brighten dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error brightening dimmer ${this.insteonId}`)
      })
    },

    dim: function () {
      this.insteonClient().dim()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
        } else {
          console.log(`Unable to lower dimmer ${this.insteonId}`)
          this.sendSmartThingsUpdate({ command: 'dim' })
        }
      }, reason => {
        console.log(`Error lowering dimmer ${this.insteonId}`)
      })
    },

    subscribeEvents: function () {
      console.log(`[${this.insteonId}] Subscribing to dimmer events...`)
      var light = this.insteonClient()

      light.on('turnOn', (group, level) => {
        console.log(`[${this.insteonId}] Dimmer turned ON`)
        if (level === null) {
          this.getStatus()
          .then((result) => {
            this.sendSmartThingsUpdate({ event: 'turn_on', status: result['status'], level: result['level'] })
          }, reason => {
            this.sendSmartThingsUpdate({ event: 'turn_on', status: 'on' })
          })
        } else {
          level = parseInt(level)
          this.sendSmartThingsUpdate({ event: 'turn_on', status: 'on', level: level })
        }
      })

      light.on('turnOnFast', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned ON FAST`)
        this.sendSmartThingsUpdate({ event: 'turn_on_fast', status: 'on', level: 100 })
      })

      light.on('turnOff', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned OFF`)
        this.sendSmartThingsUpdate({ event: 'turn_off', status: 'off', level: 0 })
      })

      light.on('turnOffFast', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned OFF FAST`)
        this.sendSmartThingsUpdate({ event: 'turn_off_fast', status: 'off', level: 0 })
      })

      light.on('brightening', (group) => {
        console.log(`[${this.insteonId}] Dimmer brightening`)
        this.sendSmartThingsUpdate({ event: 'brightening' })
      })

      light.on('brightened', (group) => {
        console.log(`[${this.insteonId}] Dimmer brightened`)
        this.getStatus()
        .then((result) => {
          this.sendSmartThingsUpdate({ event: 'brightened', status: result['status'], level: result['level'] })
        }, reason => {
          this.sendSmartThingsUpdate({ event: 'brightened' })
        })
      })

      light.on('dimming', (group) => {
        console.log(`[${this.insteonId}] Dimmer dimming`)
        this.sendSmartThingsUpdate({ event: 'dimming' })
      })

      light.on('dimmed', (group) => {
        console.log(`[${this.insteonId}] Dimmer dimmed`)
        this.sendSmartThingsUpdate({ event: 'dimmed' })
        this.getStatus()
        .then((result) => {
          this.sendSmartThingsUpdate({ event: 'dimmed', status: result['status'], level: result['level'] })
        }, reason => {
          this.sendSmartThingsUpdate({ event: 'dimmed' })
        })
      })

      console.log(`[${this.insteonId}] Subscribed to dimmer events`)
    },

    startPolling: function () {
      this.refresh()
      setInterval(() => {
        this.refresh()
      }, this.refreshSeconds * 1000)
    }
  },

  beforeValidate: function (attrs, cb) {
    attrs.type = 'dimmer'
    cb()
  }
})
<|endoftext|>


<commit_before>var mongodb = require('../mongo_connection');
var xmldoc = require('xmldoc');
var fs = require('fs');
var path = process.env.npm_package_config_upload_path;

function parser(req, res) {
    // Open file
    try {
        var buffer = fs.readFileSync(path + '/' + req.params.name);
    }
    catch(err) {
        res.sseError(err.message);
	return;
    }
    res.sseSend('Processing file...');

    // Parse XML data
    try {
        var doc = new xmldoc.XmlDocument(buffer);
    }
    catch(err) {
        res.sseError('Invalid XML file.');
	return;
    }

    // Init file processing
    if (doc.name != 'centro') {
        res.sseError('Invalid file format.');
	return;
    }

    // Insert school data...
    mongodb.db.collection('schools').updateOne(
	{_id: doc.attr.codigo },
	{ $set: { name: doc.attr.denominacion } },
	{ upsert: true })
	.then(result => {
	    //parseDoc(doc, 0, {}, res);
            parseDoc(doc, 'ensenanzas', res);
	})
	.catch(error => {
	    res.sseError(error);
	});
}

// Use recursion to parse data file...
function parseDoc(doc, childName, res) {
    if (childName != null) {
    	var child = doc.childNamed(childName);

    	if (child != undefined) {
	    switch (child.name) {
                case 'ensenanzas':
		    res.sseSend('Processing stages...');
                    parseChildren(child, processStage, 'stages', 'cursos', doc, res);
                    break;
                case 'cursos':
                    res.sseSend('Processing courses...');
                    parseChildren(child, processCourse, 'courses', 'contenidos', doc, res);
                    break;
	        case 'contenidos':
                    res.sseSend('Processing subjects...');
                    parseChildren(child, processSubject, 'subjects', 'grupos', doc, res);
                    break;
		case 'grupos':
                    res.sseSend('Processing groups...');
                    parseChildren(child, processGroup, 'groups','cursos_grupo', doc, res);
                    break;
		case 'cursos_grupo':
                    parseChildren(child, processCourseGroup, 'groups', null, doc, res);
                    break;
                default: // Error...
                    res.sseError('"' + childName + '" entity data not processed.');
            }
        }
	else {
	    res.sseError('"' + childName + '" entity not found in data file.');
	}
    }
    else {
	res.sseEnd('OK');
    }
}

function parseChildren(item, process, collection, next, doc, res) {
    var operations = [];

    for (var i=0; i<item.children.length; i++) {
        var child = item.children[i];

	var op = process(child, doc);
	if (op != null) {
	    operations.push(op);
	}
    }

    if (operations.length > 0) {
	mongodb.db.collection(collection).bulkWrite(operations)
	    .then(resp => {
		parseDoc(doc, next, res);
	    })
	    .catch(error => {
		res.sseError(error);
	    });
    }
    else {
	res.sseError('No ' + collection + ' found in data file');
    }
}

function processStage(child, doc) {
    if (child.name == 'ensenanza') {
        var op = {
            updateOne: {
                filter: { _id: child.attr.ensenanza },
                update: { $set: {
                    name: child.attr.nombre_val,
                    short_name: child.attr.abreviatura
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

function processCourse(child, doc) {
    if (child.name == 'curso') {
        var op = {
            updateOne: {
                filter: { _id: child.attr.codigo },
                update: { $set: {
                    stage_id: child.attr.ensenanza,
                    name: child.attr.nombre_val,
                    short_name: child.attr.abreviatura,
                    parent_id: child.attr.padre
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

function processSubject(child, doc) {
    if (child.name == 'contenido') {
        var op = {
            updateOne: {
                filter: { _id: child.attr.codigo },
                update: { $set: {
                    name: child.attr.nombre_val,
                    stage_id: child.attr.ensenanza,
                    course_id: child.attr.curso
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

function processGroup(child, doc) {
    if (child.name == 'grupo') {
	var id = doc.attr.codigo + child.attr.codigo + doc.attr.curso;
        var op = {
            updateOne: {
                filter: { _id: id },
                update: { $set: {
                    short_name: child.attr.codigo,
		    school_id: doc.attr.codigo,
		    year: doc.attr.curso,
		    name: child.attr.nombre,
                    stage_id: child.attr.ensenanza,
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

function processCourseGroup(child, doc) {
    if (child.name == 'curso_grupo') {
        var id = doc.attr.codigo + child.attr.grupo + doc.attr.curso;
        var op = {
            updateOne: {
                filter: { _id: id },
                update: { $addToSet: {
                    courses: child.attr.curso
                } }
            }
        };

        return op;
    }

    return null;
}

function processStudent(st, doc) {
    if (st.name == 'alumno') {
        var op = {
            updateOne: {
                filter: { _id: st.attr.NIA },
                update: { $set: {
                    last_name: st.attr.apellido1 + ' ' + st.attr.apellido2,
                    first_name: st.attr.nombre,
                    birth_date: new Date(st.attr.fecha_nac),
                    gender: st.attr.sexo == 'H' ? 'M' : 'F',
                    school_id: doc.attr.codigo
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

module.exports = parser;
<commit_msg>Itaca parser WIP.<commit_after>var mongodb = require('../mongo_connection');
var xmldoc = require('xmldoc');
var fs = require('fs');
var path = process.env.npm_package_config_upload_path;

function parser(req, res) {
    // Open file
    try {
        var buffer = fs.readFileSync(path + '/' + req.params.name);
    }
    catch(err) {
        res.sseError(err.message);
	return;
    }
    res.sseSend('Processing file...');

    // Parse XML data
    try {
        var doc = new xmldoc.XmlDocument(buffer);
    }
    catch(err) {
        res.sseError('Invalid XML file.');
	return;
    }

    // Init file processing
    if (doc.name != 'centro') {
        res.sseError('Invalid file format.');
	return;
    }

    // Insert school data...
    mongodb.db.collection('schools').updateOne(
	{_id: doc.attr.codigo },
	{ $set: { name: doc.attr.denominacion } },
	{ upsert: true })
	.then(result => {
	    //parseDoc(doc, 0, {}, res);
            parseDoc(doc, 'ensenanzas', res);
	})
	.catch(error => {
	    res.sseError(error);
	});
}

// Use recursion to parse data file...
function parseDoc(doc, childName, res) {
    if (childName != null) {
    	var child = doc.childNamed(childName);

    	if (child != undefined) {
	    switch (child.name) {
                case 'ensenanzas':
		    res.sseSend('Processing stages...');
                    parseChildren(child, processStage, 'stages', 'cursos', doc, res);
                    break;
                case 'cursos':
                    res.sseSend('Processing courses...');
                    parseChildren(child, processCourse, 'courses', 'contenidos', doc, res);
                    break;
	        case 'contenidos':
                    res.sseSend('Processing subjects...');
                    parseChildren(child, processSubject, 'subjects', 'grupos', doc, res);
                    break;
		case 'grupos':
                    res.sseSend('Processing groups...');
                    parseChildren(child, processGroup, 'groups', 'cursos_grupo', doc, res);
                    break;
		case 'cursos_grupo':
                    parseChildren(child, processCourseGroup, 'groups', 'alumnos', doc, res);
                    break;
		case 'alumnos':
                    res.sseSend('Processing students...');
                    parseChildren(child, processStudent, 'students', null, doc, res);
                    break;
                default: // Error...
                    res.sseError('"' + childName + '" entity data not processed.');
            }
        }
	else {
	    res.sseError('"' + childName + '" entity not found in data file.');
	}
    }
    else {
	res.sseEnd('OK');
    }
}

function parseChildren(item, process, collection, next, doc, res) {
    var operations = [];

    for (var i=0; i<item.children.length; i++) {
        var child = item.children[i];

	var op = process(child, doc);
	if (op != null) {
	    operations.push(op);
	}
    }

    if (operations.length > 0) {
	mongodb.db.collection(collection).bulkWrite(operations)
	    .then(resp => {
		parseDoc(doc, next, res);
	    })
	    .catch(error => {
		res.sseError(error);
	    });
    }
    else {
	res.sseError('No ' + collection + ' found in data file');
    }
}

function processStage(child, doc) {
    if (child.name == 'ensenanza') {
        var op = {
            updateOne: {
                filter: { _id: child.attr.ensenanza },
                update: { $set: {
                    name: child.attr.nombre_val,
                    short_name: child.attr.abreviatura
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

function processCourse(child, doc) {
    if (child.name == 'curso') {
        var op = {
            updateOne: {
                filter: { _id: child.attr.codigo },
                update: { $set: {
                    stage_id: child.attr.ensenanza,
                    name: child.attr.nombre_val,
                    short_name: child.attr.abreviatura,
                    parent_id: child.attr.padre
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

function processSubject(child, doc) {
    if (child.name == 'contenido') {
        var op = {
            updateOne: {
                filter: { _id: child.attr.codigo },
                update: { $set: {
                    name: child.attr.nombre_val,
                    stage_id: child.attr.ensenanza,
                    course_id: child.attr.curso
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

function processGroup(child, doc) {
    if (child.name == 'grupo') {
	var id = doc.attr.codigo + child.attr.codigo + doc.attr.curso;
        var op = {
            updateOne: {
                filter: { _id: id },
                update: { $set: {
                    short_name: child.attr.codigo,
		    school_id: doc.attr.codigo,
		    year: doc.attr.curso,
		    name: child.attr.nombre,
                    stage_id: child.attr.ensenanza,
                } },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

function processCourseGroup(child, doc) {
    if (child.name == 'curso_grupo') {
        var id = doc.attr.codigo + child.attr.grupo + doc.attr.curso;
        var op = {
            updateOne: {
                filter: { _id: id },
                update: { $addToSet: {
                    courses: child.attr.curso
                } }
            }
        };

        return op;
    }

    return null;
}

function processStudent(child, doc) {
    if (child.name == 'alumno') {
        var op = {
            updateOne: {
                filter: { _id: child.attr.NIA },
                update: { $set: {
                    last_name: child.attr.apellido1 + ' ' + child.attr.apellido2,
                    first_name: child.attr.nombre,
                    birth_date: new Date(child.attr.fecha_nac),
                    gender: child.attr.sexo == 'H' ? 'M' : 'F'
                }, $addToSet: {
		    enrolments: {
			school_id: doc.attr.codigo,
			stage_id: child.attr.ensenanza,
			course_id: child.attr.curso,
			group_id: doc.attr.codigo + child.attr.grupo + doc.attr.curso,
			active: child.attr.estado_matricula == 'M',
			repeats: child.attr.repite != '0'
		    }
		} },
                upsert: true
            }
        };

        return op;
    }

    return null;
}

module.exports = parser;
<|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames';

const statusColorMap = {
  null: 'text-grey-light',
  error: 'text-red-light',
  queued: 'text-orange-light',
  running: 'text-blue-light',
  success: 'text-green-light'
};

const statusTextMap = {
  null: 'This task has never been scheduled',
  error: 'Last execution of this task failed',
  queued: 'This task is currently queued',
  running: 'This task is running',
  success: 'Last execution of this task succeeded'
};

export default function({ status, message, inline, size }) {
  if (status === undefined) return null;
  const svgClassNames = classNames({
    'w-6': size !== 'small',
    'h-6': size !== 'small',
    'w-4': size === 'small',
    'h-4': size === 'small',
    'fill-current': true,
    [statusColorMap[status]]: true
  });

  return (
    <div
      className={classNames({ inline })}
      title={message || statusTextMap[status]}
    >
      <svg className={svgClassNames} viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="40" stroke="black" strokeWidth="3" />
      </svg>
    </div>
  );
}
<commit_msg>make status grey for interrupted tasks and add tooltip<commit_after>import React from 'react';
import classNames from 'classnames';

const statusColorMap = {
  null: 'text-grey-light',
  error: 'text-red-light',
  queued: 'text-orange-light',
  running: 'text-blue-light',
  success: 'text-green-light',
  interrupted: 'text-grey-light'
};

const statusTextMap = {
  null: 'This task has never been scheduled',
  error: 'Last execution of this task failed',
  queued: 'This task is currently queued',
  running: 'This task is running',
  success: 'Last execution of this task succeeded',
  interrupted: 'Interrupted during last execution'
};

export default function({ status, message, inline, size }) {
  if (status === undefined) return null;
  const svgClassNames = classNames({
    'w-6': size !== 'small',
    'h-6': size !== 'small',
    'w-4': size === 'small',
    'h-4': size === 'small',
    'fill-current': true,
    [statusColorMap[status]]: true
  });

  return (
    <div
      className={classNames({ inline })}
      title={message || statusTextMap[status] || `Unknown status: ${status}`}
    >
      <svg className={svgClassNames} viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="40" stroke="black" strokeWidth="3" />
      </svg>
    </div>
  );
}
<|endoftext|>


<commit_before>(function () {
    function addQueryString(url, params) {
        var queryString = [];

        if (!params)
            return url;
        else {
            for (var i in params)
                queryString.push(i + "=" + encodeURIComponent(params[i]));
        }

        return url + ((url.indexOf("?") != -1) ? "&" : "?") + queryString.join("&");
    }

    var openRepoViewerCmd = {
        exec: function (editor) {
            var width = editor.config['filebrowserChamiloWindowWidth'] || editor.config.filebrowserWindowWidth || '30%';
            var height = editor.config['filebrowserChamiloWindowHeight'] || editor.config.filebrowserWindowHeight || '50%';

            var params = {};
            params.CKEditor = editor.name;
            params.CKEditorFuncNum = editor._.chamiloFn;
            if (!params.langCode)
                params.langCode = editor.langCode;

            var url = addQueryString('Chamilo/Libraries/Resources/Javascript/HtmlEditor/CkeditorExtra/Plugin/recording/html', params);
            openPopup(url, width, height);
        }
    };

    var openDialog = {
        exec: function (editor) {
            var element = editor.getSelection().getSelectedElement();
            if (element.is('img') && element.data('cke-real-element-type') == 'chamilo') {
                var realElement = CKEDITOR.dom.element.createFromHtml(decodeURIComponent(element
                    .getAttribute('data-cke-realelement')), this.document);
                var objectType = realElement.getAttribute('type');

                var context = (objectType == 'video') ? 'Hogent' : 'Chamilo';

                if (!CKEDITOR.dialog.exists(objectType + 'Dialog')) {
                    CKEDITOR.dialog.add(objectType + 'Dialog', web_path + context + '/Core/Repository/ContentObject/' + toTitleCase(objectType)
                        + '/Resources/Javascript/HtmlEditor/Ckeditor/dialog.js');
                }

                editor.openDialog(objectType + 'Dialog');
            }
        }
    };

    function toTitleCase(str) {
        return str.replace(/\w\S*/g, function (txt) {
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
    }

    function concatObject(obj) {
        str = '';
        for (prop in obj) {
            str += prop + " value :" + obj[prop] + "\n";
        }
        return (str);
    }

    function setObject(href, objectId, objectType, objectSecurityCode, data) {
        if (!CKEDITOR.dialog.exists(objectType + 'Dialog')) {
            CKEDITOR.dialog.add(objectType + 'Dialog', href);
        }

        this.openDialog(objectType + 'Dialog', function (dialog) {
            var object = this;

            object.on('setVars', function (event) {
                object.setValueOf('info', 'security_code', objectSecurityCode);
                object.setValueOf('info', 'source', objectId);
                object.setValueOf('info', 'type', objectType);
            });

            object.on('show', function (event) {
                object.fireOnce('setVars');
            });
        });
    }

    function createChamiloFakeElement(editor, realElement, isResizable) {
        return editor.createChamiloFakeParserElement(realElement, 'cke_chamilo_' + realElement.attributes.type,
            'chamilo', isResizable);
    }

    var pluginName = 'recording';

    // Register a plugin named "chamilo".
    CKEDITOR.plugins.add(pluginName, {
        lang: 'nl,en-gb',
        icons: 'recording',
        init: function (editor) {

            editor._.chamiloFn = CKEDITOR.tools.addFunction(setObject, editor);
            editor.on('destroy', function () {
                CKEDITOR.tools.removeFunction(this._.chamiloFn);
            });

            editor.addCommand(pluginName, openRepoViewerCmd);
            editor.addCommand('dialog', openDialog);
            editor.ui.addButton && editor.ui.addButton('Recording', {
                label: editor.lang.recording.label,
                command: pluginName
            });

            // If the "menu" plugin is loaded, register the menu items.
            if (editor.addMenuItems) {
                editor.addMenuItems({
                    recording: {
                        label: editor.lang.recording.properties,
                        command: 'dialog',
                        group: 'recording'
                    }
                });
            }

            editor.on('doubleclick', function (evt) {
                var element = evt.data.element;

                if (element.is('img') && element.data('cke-real-element-type') == 'chamilo') {
                    var realElement = CKEDITOR.dom.element.createFromHtml(decodeURIComponent(element
                        .getAttribute('data-cke-realelement')), this.document);
                    var objectType = realElement.getAttribute('type');
                    if (!CKEDITOR.dialog.exists(objectType + 'Dialog')) {
                        CKEDITOR.dialog.add(objectType + 'Dialog', web_path + 'Chamilo/Core/Repository/ContentObject/' + toTitleCase(objectType)
                            + '/Resources/Javascript/HtmlEditor/Ckeditor/dialog.js');
                    }

                    evt.data.dialog = objectType + 'Dialog';
                }

            }
            );

            // If the "contextmenu" plugin is loaded, register the listeners.
            if (editor.contextMenu) {
                editor.contextMenu.addListener(function (element, selection) {
                    if (element && element.is('img') && !element.isReadOnly()
                        && element.data('cke-real-element-type') == 'chamilo') {
                        return {
                            chamilo: CKEDITOR.TRISTATE_OFF
                        };
                    } else {
                        return null;
                    }
                });
            }
        },

        afterInit: function (editor) {
            var dataProcessor = editor.dataProcessor, dataFilter = dataProcessor && dataProcessor.dataFilter;

            if (dataFilter) {
                dataFilter.addRules({
                    elements: {
                        'resource': function (element) {
                            return createChamiloFakeElement(editor, element, true);
                        }
                    }
                }, 5);
            }
        }
    });
})();
<commit_msg>[JS] cleanup<commit_after>(function () {
    function addQueryString(url, params) {
        var queryString = [];

        if (!params)
            return url;
        else {
            for (var i in params)
                queryString.push(i + "=" + encodeURIComponent(params[i]));
        }

        return url + ((url.indexOf("?") != -1) ? "&" : "?") + queryString.join("&");
    }

    var openRecordingViewerCmd = {
        exec: function (editor) {
            var width = editor.config['filebrowserChamiloWindowWidth'] || editor.config.filebrowserWindowWidth || '30%';
            var height = editor.config['filebrowserChamiloWindowHeight'] || editor.config.filebrowserWindowHeight || '50%';

            var params = {};
            params.CKEditor = editor.name;
            params.CKEditorFuncNum = editor._.chamiloFn;
            if (!params.langCode)
                params.langCode = editor.langCode;

            var url = addQueryString('Chamilo/Libraries/Resources/Javascript/HtmlEditor/CkeditorExtra/Plugin/recording/html', params);
            openPopup(url, width, height);
        }
    };

    function setObject(href, objectId, objectType, objectSecurityCode, data) {
        if (!CKEDITOR.dialog.exists(objectType + 'Dialog')) {
            CKEDITOR.dialog.add(objectType + 'Dialog', href);
        }

        this.openDialog(objectType + 'Dialog', function (dialog) {
            var object = this;

            object.on('setVars', function (event) {
                object.setValueOf('info', 'security_code', objectSecurityCode);
                object.setValueOf('info', 'source', objectId);
                object.setValueOf('info', 'type', objectType);
            });

            object.on('show', function (event) {
                object.fireOnce('setVars');
            });
        });
    }

    function createChamiloFakeElement(editor, realElement, isResizable) {
        return editor.createChamiloFakeParserElement(realElement, 'cke_chamilo_' + realElement.attributes.type,
            'chamilo', isResizable);
    }

    var pluginName = 'recording';

    // Register a plugin named "recording".
    CKEDITOR.plugins.add(pluginName, {
        lang: 'nl,en-gb',
        icons: 'recording',
        init: function (editor) {

            editor._.chamiloFn = CKEDITOR.tools.addFunction(setObject, editor);
            editor.on('destroy', function () {
                CKEDITOR.tools.removeFunction(this._.chamiloFn);
            });

            editor.addCommand(pluginName, openRecordingViewerCmd);
            editor.ui.addButton && editor.ui.addButton('Recording', {
                label: editor.lang.recording.label,
                command: pluginName
            });

            // If the "menu" plugin is loaded, register the menu items.
            if (editor.addMenuItems) {
                editor.addMenuItems({
                    recording: {
                        label: editor.lang.recording.properties,
                        command: 'dialog',
                        group: 'recording'
                    }
                });
            }

            // If the "contextmenu" plugin is loaded, register the listeners.
            if (editor.contextMenu) {
                editor.contextMenu.addListener(function (element, selection) {
                    if (element && element.is('img') && !element.isReadOnly()
                        && element.data('cke-real-element-type') == 'chamilo') {
                        return {
                            chamilo: CKEDITOR.TRISTATE_OFF
                        };
                    } else {
                        return null;
                    }
                });
            }
        },

        afterInit: function (editor) {
            var dataProcessor = editor.dataProcessor, dataFilter = dataProcessor && dataProcessor.dataFilter;

            if (dataFilter) {
                dataFilter.addRules({
                    elements: {
                        'resource': function (element) {
                            return createChamiloFakeElement(editor, element, true);
                        }
                    }
                }, 5);
            }
        }
    });
})();
<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'react-redux'
import classnames from 'classnames'

import { ROUTES } from 'routes'
import NavLink from './NavLink'

import './navbar.scss'

class NavBar extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      menuOpen: false,
    }
  }

  componentWillReceiveProps() {
    this.setState({ menuOpen: false })
  }

  render() {
    const { isAuthenticated } = this.props
    const { menuOpen } = this.state

    return (

          <NavLink exact to={ROUTES.Home} className="brand">
            FlaskReact.SPA
          </NavLink>

            Menu  ☰

            <NavLink to={ROUTES.Articles} />
            <NavLink to={ROUTES.Series} />
            <NavLink to={ROUTES.Styles} />
            <NavLink to={ROUTES.Contact} />

            {isAuthenticated
              ? this.renderAuthenticatedMenu()
              : this.renderUnauthenticatedMenu()
            }

    )
  }

  toggleResponsiveMenu = () => {
    this.setState({ menuOpen: !this.state.menuOpen })
  }

  renderAuthenticatedMenu() {
    return (

        <NavLink to={ROUTES.Profile} />
        <NavLink to={ROUTES.Logout} />

    )
  }

  renderUnauthenticatedMenu() {
    return (

        <NavLink to={ROUTES.SignUp} />
        <NavLink to={ROUTES.Login} />

    )
  }
}

export default connect(
  (state) => ({
    isAuthenticated: state.auth.isAuthenticated,
    routing: state.routing, // required for <NavLink> components to work correctly
  }),
)(NavBar)
<commit_msg>use withRouter for navbar<commit_after>import React from 'react'
import { compose } from 'redux'
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import classnames from 'classnames'

import { ROUTES } from 'routes'
import NavLink from './NavLink'

import './navbar.scss'

class NavBar extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      menuOpen: false,
    }
  }

  componentWillReceiveProps() {
    this.setState({ menuOpen: false })
  }

  render() {
    const { isAuthenticated } = this.props
    const { menuOpen } = this.state

    return (

          <NavLink exact to={ROUTES.Home} className="brand">
            FlaskReact.SPA
          </NavLink>

            Menu  ☰

            <NavLink to={ROUTES.Articles} />
            <NavLink to={ROUTES.Series} />
            <NavLink to={ROUTES.Styles} />
            <NavLink to={ROUTES.Contact} />

            {isAuthenticated
              ? this.renderAuthenticatedMenu()
              : this.renderUnauthenticatedMenu()
            }

    )
  }

  toggleResponsiveMenu = () => {
    this.setState({ menuOpen: !this.state.menuOpen })
  }

  renderAuthenticatedMenu() {
    return (

        <NavLink to={ROUTES.Profile} />
        <NavLink to={ROUTES.Logout} />

    )
  }

  renderUnauthenticatedMenu() {
    return (

        <NavLink to={ROUTES.SignUp} />
        <NavLink to={ROUTES.Login} />

    )
  }
}

const withConnect = connect(
  (state) => ({ isAuthenticated: state.auth.isAuthenticated }),
)

export default compose(
  withRouter,  // required for NavLinks to determine whether they're active or not
  withConnect,
)(NavBar)
<|endoftext|>