<commit_before>/**
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import("faststatic");
import("dispatch.{Dispatcher,PrefixMatcher,forward}");

import("etherpad.utils.*");
import("etherpad.globals.*");
import("etherpad.admin.plugins");

function onRequest() {
  var staticBase = '/static';

  var opts = {cache: isProduction()};
  var serveCompressed = faststatic.compressedFileServer(opts);

  var disp = new Dispatcher();

  disp.addLocations([
    ['/favicon.ico', faststatic.singleFileServer(staticBase + '/favicon.ico', opts)],
    ['/robots.txt', serveRobotsTxt],
    ['/crossdomain.xml', faststatic.singleFileServer(staticBase + '/crossdomain.xml', opts)],
    [PrefixMatcher('/static/compressed/'), serveCompressed]])

  for (fmt in {'js':0, 'css':0, 'swf':0, 'html':0, 'img':0, 'zip':0}) {
    for (plugin in plugins.loadPlugins().plugins) {
      disp.addLocations([[PrefixMatcher('/static/'+fmt+'/plugins/'+plugin+'/'), faststatic.directoryServer('/plugins/' + plugin + '/static/'+fmt+'/', opts)]]);
    }
    disp.addLocations([[PrefixMatcher('/static/'+fmt+'/'), faststatic.directoryServer(staticBase+'/'+fmt+'/', opts)]]);
  }
  disp.addLocations([[PrefixMatcher('/static/'), faststatic.directoryServer(staticBase, opts)]]);

  return disp.dispatch();
}

function serveRobotsTxt(name) {
  response.neverCache();
  response.setContentType('text/plain');
  response.write('User-agent: *\n');
  if (!isProduction()) {
    response.write('Disallow: /\n');
  }
  response.stop();
  return true;
}
<commit_msg>adding allow robots.txt block to static_control.<commit_after>/**
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import("faststatic");
import("dispatch.{Dispatcher,PrefixMatcher,forward}");

import("etherpad.utils.*");
import("etherpad.globals.*");
import("etherpad.admin.plugins");

function onRequest() {
  var staticBase = '/static';

  var opts = {cache: isProduction()};
  var serveCompressed = faststatic.compressedFileServer(opts);

  var disp = new Dispatcher();

  disp.addLocations([
    ['/favicon.ico', faststatic.singleFileServer(staticBase + '/favicon.ico', opts)],
    ['/robots.txt', serveRobotsTxt],
    ['/crossdomain.xml', faststatic.singleFileServer(staticBase + '/crossdomain.xml', opts)],
    [PrefixMatcher('/static/compressed/'), serveCompressed]])

  for (fmt in {'js':0, 'css':0, 'swf':0, 'html':0, 'img':0, 'zip':0}) {
    for (plugin in plugins.loadPlugins().plugins) {
      disp.addLocations([[PrefixMatcher('/static/'+fmt+'/plugins/'+plugin+'/'), faststatic.directoryServer('/plugins/' + plugin + '/static/'+fmt+'/', opts)]]);
    }
    disp.addLocations([[PrefixMatcher('/static/'+fmt+'/'), faststatic.directoryServer(staticBase+'/'+fmt+'/', opts)]]);
  }
  disp.addLocations([[PrefixMatcher('/static/'), faststatic.directoryServer(staticBase, opts)]]);

  return disp.dispatch();
}

function serveRobotsTxt(name) {
  response.neverCache();
  response.setContentType('text/plain');
  response.write('User-agent: *\n');
  if (isProduction()) {
    response.write('Allow: /\n');
  }
  else {
    response.write('Disallow: /\n');
  }
  response.stop();
  return true;
}
<|endoftext|>


<commit_before>var async = require("async");
var glob = require("glob");

var AppCache = function() {
    this._data = {
        cache: [],
        network: [],
        fallback: []
    };

    this._globbedFiles = {};

    this._dirty = true;
};

AppCache.prototype = {
    cache: function(files) {
        if (typeof files === "string") {
            files = [files];
        }

        this._data.cache = this._data.cache.concat(files);
        this._dirty = true;
    },

    network: function(files) {
        if (typeof files === "string") {
            files = [files];
        }

        this._data.network = this._data.network.concat(files);
        this._dirty = true;
    },

    glob: function(file, callback) {
        if (file.indexOf("http") === 0) {
            callback(null, file);
        } else {
            glob(file, callback);
        }
    },

    getFiles: function(files, callback) {
        async.concat(files, this.glob, callback);
    },

    bump: function() {
        return (this._key = (new Date).getTime() + Math.random());
    },

    buildCache: function(callback) {
        var self = this;

        if (!this._dirty) {
            return callback();
        }

        this.bump();

        async.each(Object.keys(this._data), function(key, callback) {
            self.getFiles(self._data[key], function(err, files) {
                self._globbedFiles[key] = files;
                callback(err);
            });
        }, callback);

        this._dirty = false;
    },

    clone: function() {

    }
};

// Inheritance
// Middleware for Express
module.exports = {
    create: function() {

    }

};
<commit_msg>Add in manifest generation, stream piping, express support.<commit_after>var async = require("async");
var glob = require("glob");

var AppCache = function(options) {
    this._options = options || {};

    this._data = {
        cache: [],
        network: []
    };

    this._globbedFiles = {};

    this._dirty = true;
};

AppCache.prototype = {
    addCache: function(files) {
        if (typeof files === "string") {
            files = [files];
        }

        this._data.cache = this._data.cache.concat(files);
        this._dirty = true;

        return this;
    },

    addNetwork: function(files) {
        if (typeof files === "string") {
            files = [files];
        }

        this._data.network = this._data.network.concat(files);
        this._dirty = true;

        return this;
    },

    reload: function() {
        this._dirty = true;
        this.buildCache();
        return this;
    },

    getString: function(callback) {
        var self = this;

        this._buildCache(function(err) {
            callback(err, self._buildString());
        });
    },

    pipe: function(dest) {
        this.getString(function(err, data) {
            // Better handle piping directly to an HTTP response
            if (dest.setHeader) {
                // Set the correct header for the file
                dest.setHeader("Content-Type", "text/cache-manifest");

                // Set it to expire immediately, to make sure it's never cached
                dest.setHeader("Expires", "0");
            }

            dest.emit(data);
        });

        return dest;
    },

    clone: function() {
        var clone = new AppCache();

        clone._data = {
            cache: this.data.cache.slice(0),
            network: this.data.network.slice(0)
        };

        return clone;
    },

    route: function() {
        var self = this;

        return function(req, res) {
            self.pipe(res);
        };
    },

    _buildString: function() {
        var str = [];

        var addFiles = function(name) {
            this._data[name].forEach(function(file) {
                if (typeof file === "string") {
                    str.push(file);
                } else {
                    str = str.concat(file);
                }
            })
        };

        str.push("# " + this._key);

        if (this._data.cache.length) {
            str.push("CACHE:");
            addFiles("cache");
        }

        if (this._data.network.length) {
            str.push("NETWORK:");
            addFiles("network");
        }

        return str.join("\n");
    },

    _glob: function(file, callback) {
        if (file.indexOf("http") === 0) {
            callback(null, file);
        } else {
            var options = {};

            if (this._options.cwd) {
                options.cwd = this._options.cwd;
            }

            glob(file, options, callback);
        }
    },

    _bump: function() {
        this._key = (new Date).getTime() + Math.random();
    },

    _buildCache: function(callback) {
        var self = this;

        if (!this._dirty) {
            return process.nextTick(callback);
        }

        this._dirty = false;
        this._globbedFiles = {};

        this._bump();

        async.each(Object.keys(this._data), function(key, callback) {
            async.concat(self._data[key], self._glob, function(err, files) {
                self._globbedFiles[key] = files;
                callback(err);
            });
        }, callback);

        return this;
    }
};

module.exports = {
    create: function(options) {
        return new AppCache(options);
    }
};
<|endoftext|>


<commit_before>$('.navbar-header .nav a h4').html('Workflow Instance Report');
$('[href="/admin/workflowinstances"]').parent().addClass('active');

$.ajax({
	url: '/api/workflowinstances/'+resource_id,
	success: function(data) {
		$('.navbar-header .nav a h4').append(' - '+data.workflow.name+'');

		$.ajax({
			url:'/api/workflowinstances/'+resource_id+'/submissions',
			dataType : 'json',
			type: 'GET',

			success  : function(data){
				data = _.each(data, function(item){
					item.created_at = {
						original:item.created_at,
						time:moment(item.created_at).format('LTS'),
						date:moment(item.created_at).format('L'),
						fromNow:moment(item.created_at).fromNow()
					}
					item.updated_at = {
						original:item.updated_at,
						time:moment(item.updated_at).format('LTS'),
						date:moment(item.updated_at).format('L'),
						fromNow:moment(item.updated_at).fromNow()
					}
				})
				new GrapheneDataGrid({

					actions:[{type:"info",name:"d_csv",label:' Download'}],
					autoSize:10,name:"workflow_submissions",schema:[{label:"Name",template:"{{attributes.user.first_name}} {{attributes.user.last_name}}"},{name:"created_at",label:"Created",template:"{{attributes.created_at.fromNow}}"},{name:"updated_at",label:"Last Action",template:"{{attributes.updated_at.fromNow}}"},{label:"State",name:"state"},{label:"Status",name:'status'},{label:"Assigned",template:"{{attributes.assignee.first_name}} {{attributes.assignee.last_name}}"}],data:data,download:false,upload:false,el:document.body.querySelector('#table')}).on('click',function(e){
					document.location = "/workflows/report/"+e.model.attributes.id;
				}.bind(this)).on('d_csv',function(e){
					document.location = "/api/workflowinstances/"+resource_id+"/csv"
				})
			}.bind(this)
		})
}})
<commit_msg>Add Group Name<commit_after>$('.navbar-header .nav a h4').html('Workflow Instance Report');
$('[href="/admin/workflowinstances"]').parent().addClass('active');

$.ajax({
	url: '/api/workflowinstances/'+resource_id,
	success: function(data) {
		$('.navbar-header .nav a h4').append(' - '+data.workflow.name+'');

		$.ajax({
			url:'/api/workflowinstances/'+resource_id+'/submissions',
			dataType : 'json',
			type: 'GET',

			success  : function(data){
				data = _.each(data, function(item){
					item.created_at = {
						original:item.created_at,
						time:moment(item.created_at).format('LTS'),
						date:moment(item.created_at).format('L'),
						fromNow:moment(item.created_at).fromNow()
					}
					item.updated_at = {
						original:item.updated_at,
						time:moment(item.updated_at).format('LTS'),
						date:moment(item.updated_at).format('L'),
						fromNow:moment(item.updated_at).fromNow()
					}
				})
				new GrapheneDataGrid({

					actions:[{type:"info",name:"d_csv",label:' Download'}],
					autoSize:10,name:"workflow_submissions",schema:[{label:"Name",template:"{{attributes.user.first_name}} {{attributes.user.last_name}}"},{name:"created_at",label:"Created",template:"{{attributes.created_at.fromNow}}"},{name:"updated_at",label:"Last Action",template:"{{attributes.updated_at.fromNow}}"},{label:"State",name:"state"},{label:"Status",name:'status'},{label:"Assigned",template:"{{attributes.assignee.name}}{{attributes.assignee.first_name}} {{attributes.assignee.last_name}}"}],data:data,download:false,upload:false,el:document.body.querySelector('#table')}).on('click',function(e){
					document.location = "/workflows/report/"+e.model.attributes.id;
				}.bind(this)).on('d_csv',function(e){
					document.location = "/api/workflowinstances/"+resource_id+"/csv"
				})
			}.bind(this)
		})
}})
<|endoftext|>


<commit_before>define(['moxie.conf', 'jquery', 'app'], function(conf, $, app) {
    var consoleAvailable = 'console' in window;

    function PushNotifications() {
        function onNotificationGCM(e) {
            switch(e.event) {
                case 'registered':
                    if ( e.regid.length > 0 ) {
                        var ajaxOptions = {
                            type: "POST",
                            data: JSON.stringify({'registration_id': e.regid}),
                            contentType: 'application/json',
                            url: conf.urlFor('push_notification_register_gcm')
                        };
                        console.log(ajaxOptions.data);
                        $.ajax(ajaxOptions);
                    }
                    break;

                case 'message':
                    if (e.foreground) {
                        // Manually fire the alert as there will
                        // be no notification in the notification bar
                        if (e.payload && e.payload.message) {
                            navigator.notification.alert(e.payload.message);
                        }
                        if (consoleAvailable) {
                            console.log("Foreground");
                        }
                    }
                    else {
                        if (e.coldstart) {
                            if (consoleAvailable) {
                                console.log("Cold Start");
                            }
                        } else {
                            // No need to fire alert as user will have
                            // notification in the notification bar
                            if (consoleAvailable) {
                                console.log("Background");
                            }
                        }
                    }
                    break;

                case 'error':
                    if (consoleAvailable) {
                        console.log("Error from GCM:" + e.msg);
                    }
                    break;

                default:
                    if (consoleAvailable) {
                        console.log("Unknown event");
                    }
                    break;
            }
        }
        window.onNotificationGCM = onNotificationGCM;

        // iOS
        //
        // handle APNS notifications for iOS
        function onNotificationAPN(e) {
            var pushNotification = window.plugins.pushNotification;
            if (e.alert) {
                navigator.notification.alert(e.alert);
            }
            if (e.badge) {
                pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
            }
        }
        window.onNotificationAPN = onNotificationAPN;

        function tokenHandler(result) {
            if (consoleAvailable) {
                console.log("Device Token: " + result);
            }
            var ajaxOptions = {
                type: "POST",
                data: JSON.stringify({'device_token': result}),
                contentType: 'application/json',
                url: conf.urlFor('push_notification_register_apns')
            };
            $.ajax(ajaxOptions);
        }

        // result contains any message sent from the plugin call
        function successHandler (result) {
            if (consoleAvailable) {
                console.log("PushPlugin - Success: " + result);
            }
        }

        // result contains any error description text returned from the plugin call
        function errorHandler (error) {
            if (consoleAvailable) {
                console.log("PushPlugin - Error: " + error);
            }
        }

        this.registerAndroid = function() {
            var pushNotification = window.plugins.pushNotification;
            pushNotification.register(successHandler, errorHandler, {"senderID": conf.pushNotifications.android.senderID, "ecb": "onNotificationGCM"});
        };

        this.registeriOS = function() {
            try {
                var pushNotification = window.plugins.pushNotification;
                pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});
            } catch (e) {
                alert(e);
            }
        };

    }
    return PushNotifications;
});
<commit_msg>Removed debug logging<commit_after>define(['moxie.conf', 'jquery', 'app'], function(conf, $, app) {
    var consoleAvailable = 'console' in window;

    function PushNotifications() {
        function onNotificationGCM(e) {
            switch(e.event) {
                case 'registered':
                    if ( e.regid.length > 0 ) {
                        var ajaxOptions = {
                            type: "POST",
                            data: JSON.stringify({'registration_id': e.regid}),
                            contentType: 'application/json',
                            url: conf.urlFor('push_notification_register_gcm')
                        };
                        $.ajax(ajaxOptions);
                    }
                    break;

                case 'message':
                    if (e.foreground) {
                        // Manually fire the alert as there will
                        // be no notification in the notification bar
                        if (e.payload && e.payload.message) {
                            navigator.notification.alert(e.payload.message);
                        }
                    }
                    break;
                case 'error':
                    if (consoleAvailable) {
                        console.log("Error from GCM:" + e.msg);
                    }
                    break;
                default:
                    if (consoleAvailable) {
                        console.log("Unknown event");
                    }
                    break;
            }
        }
        window.onNotificationGCM = onNotificationGCM;

        // iOS
        //
        // handle APNS notifications for iOS
        function onNotificationAPN(e) {
            var pushNotification = window.plugins.pushNotification;
            if (e.alert) {
                navigator.notification.alert(e.alert);
            }
            if (e.badge) {
                pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
            }
        }
        window.onNotificationAPN = onNotificationAPN;

        function tokenHandler(result) {
            var ajaxOptions = {
                type: "POST",
                data: JSON.stringify({'device_token': result}),
                contentType: 'application/json',
                url: conf.urlFor('push_notification_register_apns')
            };
            $.ajax(ajaxOptions);
        }

        // result contains any message sent from the plugin call
        function successHandler (result) {
            if (consoleAvailable) {
                console.log("PushPlugin - Success: " + result);
            }
        }

        // result contains any error description text returned from the plugin call
        function errorHandler (error) {
            if (consoleAvailable) {
                console.log("PushPlugin - Error: " + error);
            }
        }

        this.registerAndroid = function() {
            var pushNotification = window.plugins.pushNotification;
            pushNotification.register(successHandler, errorHandler, {"senderID": conf.pushNotifications.android.senderID, "ecb": "onNotificationGCM"});
        };

        this.registeriOS = function() {
            try {
                var pushNotification = window.plugins.pushNotification;
                pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});
            } catch (e) {
                if (consoleAvailable) {
                    console.log("PushPlugin - Error Registering");
                    console.log(e);
                }
            }
        };

    }
    return PushNotifications;
});
<|endoftext|>


<commit_before>var connection = null;
var logger = null;
var League = null;
var games = [];
exports.init = function(conn, log, leagJS) {
  connection = conn;
  logger = log;
  League = leagJS;

  setInterval(() => {
    processEntries();
  }, 24*60*60*1000); // check every 24 hours.
  processEntries();
}

function processEntries() {
    return connection.query("SELECT * FROM mastery WHERE processed = 0 ORDER BY update_time ASC").then((result) => {
      logger.info("Analysing games.");
      if (result.length > 0) {
        // construct promise chain so entries get processed in the correct order
        var chain = result.reduce((previous, item, index) => {
           return previous.then(() => {
            return processEntry(item);
           });
        }, Promise.resolve(true));
        return chain;
      } else {
        logger.debug("No new games detected.");
        return "Nothing to process";
      }
    }).then((res) => {
      logger.info("Finished analysing games.");
      // clear game cache after run. we won't see those games ever again
      games = [];
      return true;
    }).catch((err) => {
      logger.error(err);
      logger.error("Error processing new games.", err);
      return false;
    });
}

function processEntry(masteryEntry) {
  // select last entry with that champion
  logger.info("Processing entry " + masteryEntry.summoner_id + " / "  + masteryEntry.game_id);
   return connection.query("SELECT * FROM mastery WHERE summoner_id = ? and champion_id = ? and update_time < ? ORDER BY update_time DESC LIMIT 1", [masteryEntry.summoner_id, masteryEntry.champion_id, masteryEntry.update_time]).then((result) => {
      if (!result || result.length == 0) {
        logger.debug("First entry for " + masteryEntry.summoner_id + " and " + masteryEntry.champion_id);
        return createFirstEntry(masteryEntry);
      } else {
        logger.debug("At least 1 entry for " + masteryEntry.summoner_id + " and " + masteryEntry.champion_id + " exists.");
        return createEntry(masteryEntry, result[0]);
      }
   }).then(() => {
     logger.debug("Setting processed bit for " + masteryEntry.summoner_id + " and " + masteryEntry.game_id + ".");
     return connection.query("UPDATE mastery SET processed = 1 WHERE summoner_id = ? and game_id = ?", [masteryEntry.summoner_id, masteryEntry.game_id]);
   }).then(() => {
     logger.info ("Finished processing " + masteryEntry.summoner_id + " / "  + masteryEntry.game_id);
   })
}

function getGame(gameId) {
  if (games["" + gameId]) {
    return Promise.resolve(games["" + gameId]);
  } else {
    return League.getMatch(gameId, false).then((game) => {
      games["" + gameId] = game;
      return game;
    })
  }
}

function createFirstEntry(masteryEntry) {
  return getGame(masteryEntry.game_id).then((game) => {
    masteryEntry.timestamp = Math.floor((game.matchCreation + game.matchDuration) / 1000.0);
    masteryEntry.pts_gained = null;
    return insertGains(masteryEntry);
  });
}

function createEntry(masteryEntry, lastEntry) {
  return getGame(masteryEntry.game_id).then((game) => {
    masteryEntry.timestamp = Math.floor((game.matchCreation + game.matchDuration) / 1000.0);
    masteryEntry.pts_gained = masteryEntry.championPoints - lastEntry.championPoints; // difference before after
    return insertGains(masteryEntry);
  });
}

function insertGains(masteryEntry) {
  logger.debug("Inserting mastery entry.", masteryEntry);
  return connection.query("INSERT INTO gains (summoner_id, champion_id, game_id, game_timestamp, pts_gained, mastery_level, pts_next, pts_since, pts_total) VALUES (?, ?, ?, FROM_UNIXTIME(?), ?, ?, ?, ?, ?)", [masteryEntry.summoner_id, masteryEntry.champion_id, masteryEntry.game_id, masteryEntry.timestamp, masteryEntry.pts_gained, masteryEntry.championLevel, masteryEntry.pointsSinceLastLevel, masteryEntry.pointsUntilNextLevel, masteryEntry.championPoints]);
}
<commit_msg>Analysis now runs once per hour<commit_after>var connection = null;
var logger = null;
var League = null;
var games = [];
exports.init = function(conn, log, leagJS) {
  connection = conn;
  logger = log;
  League = leagJS;

  setInterval(() => {
    processEntries();
  }, 60*60*1000); // check every 24 hours.
  processEntries();
}

function processEntries() {
    return connection.query("SELECT * FROM mastery WHERE processed = 0 ORDER BY update_time ASC").then((result) => {
      logger.info("Analysing games.");
      if (result.length > 0) {
        // construct promise chain so entries get processed in the correct order
        var chain = result.reduce((previous, item, index) => {
           return previous.then(() => {
            return processEntry(item);
           });
        }, Promise.resolve(true));
        return chain;
      } else {
        logger.debug("No new games detected.");
        return "Nothing to process";
      }
    }).then((res) => {
      logger.info("Finished analysing games.");
      // clear game cache after run. we won't see those games ever again
      games = [];
      return true;
    }).catch((err) => {
      logger.error(err);
      logger.error("Error processing new games.", err);
      return false;
    });
}

function processEntry(masteryEntry) {
  // select last entry with that champion
  logger.info("Processing entry " + masteryEntry.summoner_id + " / "  + masteryEntry.game_id);
   return connection.query("SELECT * FROM mastery WHERE summoner_id = ? and champion_id = ? and update_time < ? ORDER BY update_time DESC LIMIT 1", [masteryEntry.summoner_id, masteryEntry.champion_id, masteryEntry.update_time]).then((result) => {
      if (!result || result.length == 0) {
        logger.debug("First entry for " + masteryEntry.summoner_id + " and " + masteryEntry.champion_id);
        return createFirstEntry(masteryEntry);
      } else {
        logger.debug("At least 1 entry for " + masteryEntry.summoner_id + " and " + masteryEntry.champion_id + " exists.");
        return createEntry(masteryEntry, result[0]);
      }
   }).then(() => {
     logger.debug("Setting processed bit for " + masteryEntry.summoner_id + " and " + masteryEntry.game_id + ".");
     return connection.query("UPDATE mastery SET processed = 1 WHERE summoner_id = ? and game_id = ?", [masteryEntry.summoner_id, masteryEntry.game_id]);
   }).then(() => {
     logger.info ("Finished processing " + masteryEntry.summoner_id + " / "  + masteryEntry.game_id);
   })
}

function getGame(gameId) {
  if (games["" + gameId]) {
    return Promise.resolve(games["" + gameId]);
  } else {
    return League.getMatch(gameId, false).then((game) => {
      games["" + gameId] = game;
      return game;
    })
  }
}

function createFirstEntry(masteryEntry) {
  return getGame(masteryEntry.game_id).then((game) => {
    masteryEntry.timestamp = Math.floor((game.matchCreation + game.matchDuration) / 1000.0);
    masteryEntry.pts_gained = null;
    return insertGains(masteryEntry);
  });
}

function createEntry(masteryEntry, lastEntry) {
  return getGame(masteryEntry.game_id).then((game) => {
    masteryEntry.timestamp = Math.floor((game.matchCreation + game.matchDuration) / 1000.0);
    masteryEntry.pts_gained = masteryEntry.championPoints - lastEntry.championPoints; // difference before after
    return insertGains(masteryEntry);
  });
}

function insertGains(masteryEntry) {
  logger.debug("Inserting mastery entry.", masteryEntry);
  return connection.query("INSERT INTO gains (summoner_id, champion_id, game_id, game_timestamp, pts_gained, mastery_level, pts_next, pts_since, pts_total) VALUES (?, ?, ?, FROM_UNIXTIME(?), ?, ?, ?, ?, ?)", [masteryEntry.summoner_id, masteryEntry.champion_id, masteryEntry.game_id, masteryEntry.timestamp, masteryEntry.pts_gained, masteryEntry.championLevel, masteryEntry.pointsSinceLastLevel, masteryEntry.pointsUntilNextLevel, masteryEntry.championPoints]);
}
<|endoftext|>


<commit_before>/* global Handlebars */

/*
 * jQuery-handlebars
 * https://github.com/softwarespot/jquery-handlebars
 * Author: softwarespot
 * Licensed under the MIT license
 * Version: 1.2.5
 */
; // jshint ignore:line
(function (window, $, undefined) {

    // Initial idea came from: http://blog.teamtreehouse.com/handlebars-js-part-3-tips-and-tricks

    // Plugin Logic

    $.fn.extend({
        // The parameter data doubles up as options when the action is either 'clear' or 'remove' i.e. options param will be ignored
        handlebars: function handlebars(action, template, dataOrOptions, options) {
            // jQuery object reference for this. Only select the first selector of the jQuery collection
            var $this = $(this).first();

            // Store whether the template is valid or invalid
            var isTemplateString = isString(template);

            // These actions don't require any pre-processing
            if (isString(action)) {
                // If a 'get' action is provided, then get the template(s)
                // The template string if not defined will return all template(s)
                if (_regExp.GET.test(action)) {
                    // The include parameter will be true, if the template is a string and valid anchor
                    return getTemplate($this, template, isTemplateString);
                    // If a 'compiled' action is provided, then return the compiled object literal
                } else if (_regExp.COMPILED.test(action)) {
                    // Shallow copy the compiled store, otherwise returning compiled would provide a reference and allow the
                    // end user to manipulate the internal store. Not a good idea if you ask me!
                    return $.extend({}, _compiled);
                }
            } else {
                // An invalid action was passed. It must be a string with a length greater than zero to be
                // considered valid
                return this;
            }

            // Set our options from the defaults, overriding with the
            // parameter we pass into this function
            options = $.extend({}, $.fn.handlebars.options, options);

            // START: Sanitize the options

            // Check if the option type is a string and valid
            if (isString(options.type) && _regExp.TYPE.test(options.type)) {
                // Set to uppercase
                options.type = options.type.toUpperCase();
            } else {
                // Otherwise default to 'append' i.e. if null or simply invalid
                options.type = _type.APPEND;
            }

            // If the removal type is a string and valid, then set to uppercase
            if (isString(options.remove_type) && _regExp.REMOVE_TYPE.test(options.remove_type)) {
                // Set to uppercase
                options.remove_type = options.remove_type.toUpperCase();
            } else {
                // Otherwise default to 'none' i.e. if null or simply is invalid
                options.remove_type = _remove.NONE;
            }

            // END: Sanitize the options

            // If a 'clear' action is provided, then remove the template from the content element
            if (_regExp.CLEAR.test(action)) {
                // Extend the options again, as the dataOrOptions acts as an alias for options when a removal action is
                // specified
                options = $.extend(options, dataOrOptions);

                // If the options parameter is not the 'same' and a template string exists, the
                // temporarily override
                if (isTemplateString && options.remove_type !== _remove.SAME) {
                    options.remove_type = _remove.SAME;
                } else {
                    // Otherwise use 'all'
                    options.remove_type = _remove.ALL;
                }

                // If the template is not defined, then set as null before removing
                if (!isTemplateString) {
                    template = null;
                }

                return removeTemplate(this, $this, template, options);
            }

            // Assume it's an addition i.e. 'add'

            // The data object literal must contain data
            if (isBoolean(options.validate) && options.validate && $.isEmptyObject(dataOrOptions)) {
                return this;
            }

            // jQuery object reference
            var $selector = null;

            // If a valid string template is passed then check if it's compiled or get the jQuery object instead
            if (isTemplateString) {
                // If compiled already then no need to re-compile
                if ($.isFunction(_compiled[template])) {
                    // Return to continue chaining
                    return setTemplate(this, $this, template, dataOrOptions, options);
                }

                // Not compiled

                // Get the first selection only
                $selector = $(template).first();

                // If the selector doesn't exist for whatever reason, then set to null
                if ($selector.length === 0) {
                    $selector = null;
                }
                // If a valid jQuery selector object
            } else if (template instanceof $ && $.isNumeric(template.length) && template.length > 0) {
                // Get the first selection only
                $selector = template.first();

                // Get the selector name for using with the compiled object literal
                // If the selector property doesn't exist, then this will be set to null
                template = $selector.selector !== undefined ? $selector.selector : null;

                // If compiled already then no need to re-compile
                if ($.isFunction(_compiled[template])) {
                    // Return to continue chaining
                    return setTemplate(this, $this, template, dataOrOptions, options);
                }
            }

            // If an invalid selector, then return this to continue chaining
            if ($selector === null || template === null || $selector.length === 0) {
                return this;
            }

            // Get the HTML of the template only
            var html = $selector.html();

            // Store the compiled template in the compiled store
            _compiled[template] = Handlebars.compile(html);

            // Return to continue chaining
            return setTemplate(this, $this, template, dataOrOptions, options);
        }

    });

    // Constants

    // The data-* attribute to distinguish a jQuery-handlebars template
    var DATA_ATTR = 'data-jquery-handlebars';

    // Regular expressions
    var _regExp = {
        CLEAR: /^(?:CLEAR|EMPTY|REMOVE)$/i,
        COMPILED: /^(?:COMPILED|STORE)$/i,
        GET: /^(?:FIND|GET)$/i,
        REMOVE_TYPE: /^(?:ALL|NONE|SAME)$/i,
        TYPE: /^(?:APPEND|COMPILED|HTML|RAW)$/i
    };

    // Removal constants. Who enjoys magic values?
    var _remove = {
        ALL: 'ALL',
        NONE: 'NONE',
        SAME: 'SAME'
    };

    // Type constants. Who enjoys magic values?
    var _type = {
        APPEND: 'APPEND',
        COMPILED: 'COMPILED',
        HTML: 'HTML',
        RAW: 'RAW'
    };

    // Fields (Private)

    // Store the compiled template(s) using the template string as the identifier i.e. key
    var _compiled = {};

    // Methods (Private)

    // Check if value is a boolean datatype
    function isBoolean(value) {
        return $.type(value) === 'boolean';
    }

    // Check if a value is a string datatype with a length greater than zero when whitespace is stripped
    function isString(value) {
        return $.type(value) === 'string' && value.trim().length > 0;
    }

    // Get the template in the content selector
    // include refers to whether to include the template in the selection
    function getTemplate($this, template, include) {
        // Get the divs with the template data attribute and optional specified template string e.g. #some-template
        var templateFind = (include && template ? '="' + sanitizeQuotes(template) + '"' : '');
        return $this.find('div[' + DATA_ATTR + templateFind + ']');
    }

    // Remove the specified template from the content selector. If a template is not provided
    // then all template(s) that are contained within the content selector will be removed
    function removeTemplate(_this, $this, template, options) {
        // If the option has been passed to remove 'none', then respect this choice or if the template is null but the option is set to 'same'
        if (options.remove_type === _remove.NONE || (template === null && options.remove_type === _remove.SAME)) {
            // Return this to maintain chaining if there is nothing to remove
            return _this;
        }

        // The include parameter will be set to true, when specifically looking for the provided template string
        var filtered = getTemplate($this, template, options.remove_type === _remove.SAME);
        if (filtered.length === 0) {
            // Return this to maintain chaining if there is nothing to remove
            return _this;
        }

        // Remove filtered nodes from the DOM
        filtered.remove();

        // Remove the template from the compiled store, if the option is true
        if (isBoolean(options.delete_compiled) && options.delete_compiled) {
            // Iterate through the filtered collection and remove the template string from the compiled store
            $.each(filtered, function filteredEach(index, element) {
                // Get the data attribute for the template string if it's not null or has already been removed
                // var attribute = $(element).attr(DATA_ATTR);
                var attribute = element.getAttribute(DATA_ATTR); // Returns null or '' on error
                if (!attribute && _compiled[attribute] !== undefined) {
                    // Set to undefined to mimic deletion of the template. Using delete is not really required
                    _compiled[attribute] = undefined;
                }
            });
        }
    }

    // Replace double quotes with single quotes. Workaround for jQuery issue
    function sanitizeQuotes(value) {
        return value.replace(/"/g, '\'');
    }

    // Set the specified template to the content selector
    function setTemplate(_this, $this, template, data, options) {
        // Override deleting from the compiled stored before passing to removeTemplate
        options.delete_compiled = false;

        // Remove template(s)
        removeTemplate(_this, $this, template, options);

        // If set to not refill and template node(s) exist, then return this
        if (isBoolean(options.refill) && !options.refill) {
            // Get the template(s) after potential removal. The parameter include has been set to true, as we are checking
            // if only the same template(s) exists (perhaps an option could/should be created)
            var filtered = getTemplate($this, template, true);
            if (filtered.length > 0) {
                return _this;
            }
        }

        // Store the parsed template with data
        var parsedTemplate = _compiled[template](data);

        // Remove the compiled template from the store if specified
        if (isBoolean(options.store_compiled) && !options.store_compiled) {
            // Set to undefined to mimic deletion of the template. Using delete is not really required
            _compiled[template] = undefined;
        }

        // Append to the content element by checking the type. Default is 'append'
        switch (options.type) {
            case _type.COMPILED:
            case _type.RAW:
                // Return the compiled template
                return parsedTemplate;

            case _type.HTML:
                // Return as HTML data
                return $(parsedTemplate);

            default:
                // Create a div element with the template appended to it
                // This contains a data-* attribute called data-jquery-handlebars for easy association
                // that it's a Handlebars template
                var $div = $('<div/>')
                    .attr(DATA_ATTR, sanitizeQuotes(template))
                    .append(parsedTemplate);

                // Append the div to content element
                $this.append($div);
                break;

        }

        return _this;
    }

    // Defaults

    $.fn.handlebars.options = {
        // Delete the template from the compiled store when a removal action is specified. Accepts true (default) or false
        delete_compiled: true,

        // Store a compiled template. This improves efficiency if using the same template continuously. Accepts true (default) or false
        store_compiled: true,

        // Allow the addition of multiple template(s) inside a content element. Accepts true (default) or false
        refill: true,

        // Remove pre-existing compiled templates from the specified content element when adding/appending a template
        //
        // The following options are:
        //      'none' (default): Don't remove any template(s)
        //      'all': Remove all valid template(s) from the content element
        //      'same': Remove only those template(s) that match the provided template string
        remove_type: _remove.NONE,

        // How to output the compiled template to the specified content element
        //
        // The following options are:
        //      'append' (default): Append to the content element
        //      'html': Return a compiled template as HTML
        //      'compiled'/'raw': Return a compiled template
        type: _type.APPEND,

        // Check whether the data passed to the plugin is empty
        validate: true
    };
})(this, this.jQuery);
<commit_msg>Partially fixed jscs errors<commit_after>/* global Handlebars */

/*
 * jQuery-handlebars
 * https://github.com/softwarespot/jquery-handlebars
 * Author: softwarespot
 * Licensed under the MIT license
 * Version: 1.2.5
 */
; // jshint ignore:line
(function (window, $, undefined) {

    // Initial idea came from: http://blog.teamtreehouse.com/handlebars-js-part-3-tips-and-tricks

    // Plugin Logic

    $.fn.extend({
        // The parameter data doubles up as options when the action is either 'clear' or 'remove' i.e. options param will be ignored
        handlebars: function handlebars(action, template, dataOrOptions, options) {
            // jQuery object reference for this. Only select the first selector of the jQuery collection
            var $this = $(this).first();

            // Store whether the template is valid or invalid
            var isTemplateString = isString(template);

            // These actions don't require any pre-processing
            if (isString(action)) {
                // If a 'get' action is provided, then get the template(s)
                // The template string if not defined will return all template(s)
                if (_regExp.GET.test(action)) {
                    // The include parameter will be true, if the template is a string and valid anchor
                    return getTemplate($this, template, isTemplateString);

                    // If a 'compiled' action is provided, then return the compiled object literal
                } else if (_regExp.COMPILED.test(action)) {
                    // Shallow copy the compiled store, otherwise returning compiled would provide a reference and allow the
                    // end user to manipulate the internal store. Not a good idea if you ask me!
                    return $.extend({}, _compiled);
                }
            } else {
                // An invalid action was passed. It must be a string with a length greater than zero to be
                // considered valid
                return this;
            }

            // Set our options from the defaults, overriding with the
            // parameter we pass into this function
            options = $.extend({}, $.fn.handlebars.options, options);

            // START: Sanitize the options

            // Check if the option type is a string and valid
            if (isString(options.type) && _regExp.TYPE.test(options.type)) {
                // Set to uppercase
                options.type = options.type.toUpperCase();
            } else {
                // Otherwise default to 'append' i.e. if null or simply invalid
                options.type = _type.APPEND;
            }

            // If the removal type is a string and valid, then set to uppercase
            if (isString(options.remove_type) && _regExp.REMOVE_TYPE.test(options.remove_type)) {
                // Set to uppercase
                options.remove_type = options.remove_type.toUpperCase();
            } else {
                // Otherwise default to 'none' i.e. if null or simply is invalid
                options.remove_type = _remove.NONE;
            }

            // END: Sanitize the options

            // If a 'clear' action is provided, then remove the template from the content element
            if (_regExp.CLEAR.test(action)) {
                // Extend the options again, as the dataOrOptions acts as an alias for options when a removal action is
                // specified
                options = $.extend(options, dataOrOptions);

                // If the options parameter is not the 'same' and a template string exists, the
                // temporarily override
                if (isTemplateString && options.remove_type !== _remove.SAME) {
                    options.remove_type = _remove.SAME;
                } else {
                    // Otherwise use 'all'
                    options.remove_type = _remove.ALL;
                }

                // If the template is not defined, then set as null before removing
                if (!isTemplateString) {
                    template = null;
                }

                return removeTemplate(this, $this, template, options);
            }

            // Assume it's an addition i.e. 'add'

            // The data object literal must contain data
            if (isBoolean(options.validate) && options.validate && $.isEmptyObject(dataOrOptions)) {
                return this;
            }

            // jQuery object reference
            var $selector = null;

            // If a valid string template is passed then check if it's compiled or get the jQuery object instead
            if (isTemplateString) {
                // If compiled already then no need to re-compile
                if ($.isFunction(_compiled[template])) {
                    // Return to continue chaining
                    return setTemplate(this, $this, template, dataOrOptions, options);
                }

                // Not compiled

                // Get the first selection only
                $selector = $(template).first();

                // If the selector doesn't exist for whatever reason, then set to null
                if ($selector.length === 0) {
                    $selector = null;
                }

                // If a valid jQuery selector object
            } else if (template instanceof $ && $.isNumeric(template.length) && template.length > 0) {
                // Get the first selection only
                $selector = template.first();

                // Get the selector name for using with the compiled object literal
                // If the selector property doesn't exist, then this will be set to null
                template = $selector.selector !== undefined ? $selector.selector : null;

                // If compiled already then no need to re-compile
                if ($.isFunction(_compiled[template])) {
                    // Return to continue chaining
                    return setTemplate(this, $this, template, dataOrOptions, options);
                }
            }

            // If an invalid selector, then return this to continue chaining
            if ($selector === null || template === null || $selector.length === 0) {
                return this;
            }

            // Get the HTML of the template only
            var html = $selector.html();

            // Store the compiled template in the compiled store
            _compiled[template] = Handlebars.compile(html);

            // Return to continue chaining
            return setTemplate(this, $this, template, dataOrOptions, options);
        }

    });

    // Constants

    // The data-* attribute to distinguish a jQuery-handlebars template
    var DATA_ATTR = 'data-jquery-handlebars';

    // Regular expressions
    var _regExp = {
        CLEAR: /^(?:CLEAR|EMPTY|REMOVE)$/i,
        COMPILED: /^(?:COMPILED|STORE)$/i,
        GET: /^(?:FIND|GET)$/i,
        REMOVE_TYPE: /^(?:ALL|NONE|SAME)$/i,
        TYPE: /^(?:APPEND|COMPILED|HTML|RAW)$/i
    };

    // Removal constants. Who enjoys magic values?
    var _remove = {
        ALL: 'ALL',
        NONE: 'NONE',
        SAME: 'SAME'
    };

    // Type constants. Who enjoys magic values?
    var _type = {
        APPEND: 'APPEND',
        COMPILED: 'COMPILED',
        HTML: 'HTML',
        RAW: 'RAW'
    };

    // Fields (Private)

    // Store the compiled template(s) using the template string as the identifier i.e. key
    var _compiled = {};

    // Methods (Private)

    // Check if value is a boolean datatype
    function isBoolean(value) {
        return $.type(value) === 'boolean';
    }

    // Check if a value is a string datatype with a length greater than zero when whitespace is stripped
    function isString(value) {
        return $.type(value) === 'string' && value.trim().length > 0;
    }

    // Get the template in the content selector
    // include refers to whether to include the template in the selection
    function getTemplate($this, template, include) {
        // Get the divs with the template data attribute and optional specified template string e.g. #some-template
        var templateFind = (include && template ? '="' + sanitizeQuotes(template) + '"' : '');
        return $this.find('div[' + DATA_ATTR + templateFind + ']');
    }

    // Remove the specified template from the content selector. If a template is not provided
    // then all template(s) that are contained within the content selector will be removed
    function removeTemplate(_this, $this, template, options) {
        // If the option has been passed to remove 'none', then respect this choice or if the template is null but the option is set to 'same'
        if (options.remove_type === _remove.NONE || (template === null && options.remove_type === _remove.SAME)) {
            // Return this to maintain chaining if there is nothing to remove
            return _this;
        }

        // The include parameter will be set to true, when specifically looking for the provided template string
        var filtered = getTemplate($this, template, options.remove_type === _remove.SAME);
        if (filtered.length === 0) {
            // Return this to maintain chaining if there is nothing to remove
            return _this;
        }

        // Remove filtered nodes from the DOM
        filtered.remove();

        // Remove the template from the compiled store, if the option is true
        if (isBoolean(options.delete_compiled) && options.delete_compiled) {
            // Iterate through the filtered collection and remove the template string from the compiled store
            $.each(filtered, function filteredEach(index, element) {
                // Get the data attribute for the template string if it's not null or has already been removed
                // var attribute = $(element).attr(DATA_ATTR);
                var attribute = element.getAttribute(DATA_ATTR); // Returns null or '' on error
                if (!attribute && _compiled[attribute] !== undefined) {
                    // Set to undefined to mimic deletion of the template. Using delete is not really required
                    _compiled[attribute] = undefined;
                }
            });
        }
    }

    // Replace double quotes with single quotes. Workaround for jQuery issue
    function sanitizeQuotes(value) {
        return value.replace(/"/g, '\'');
    }

    // Set the specified template to the content selector
    function setTemplate(_this, $this, template, data, options) {
        // Override deleting from the compiled stored before passing to removeTemplate
        options.delete_compiled = false;

        // Remove template(s)
        removeTemplate(_this, $this, template, options);

        // If set to not refill and template node(s) exist, then return this
        if (isBoolean(options.refill) && !options.refill) {
            // Get the template(s) after potential removal. The parameter include has been set to true, as we are checking
            // if only the same template(s) exists (perhaps an option could/should be created)
            var filtered = getTemplate($this, template, true);
            if (filtered.length > 0) {
                return _this;
            }
        }

        // Store the parsed template with data
        var parsedTemplate = _compiled[template](data);

        // Remove the compiled template from the store if specified
        if (isBoolean(options.store_compiled) && !options.store_compiled) {
            // Set to undefined to mimic deletion of the template. Using delete is not really required
            _compiled[template] = undefined;
        }

        // Append to the content element by checking the type. Default is 'append'
        switch (options.type) {
            case _type.COMPILED:
            case _type.RAW:

                // Return the compiled template
                return parsedTemplate;

            case _type.HTML:

                // Return as HTML data
                return $(parsedTemplate);

            default:

                // Create a div element with the template appended to it
                // This contains a data-* attribute called data-jquery-handlebars for easy association
                // that it's a Handlebars template
                var $div = $('<div/>')
                    .attr(DATA_ATTR, sanitizeQuotes(template))
                    .append(parsedTemplate);

                // Append the div to content element
                $this.append($div);
                break;

        }

        return _this;
    }

    // Defaults

    $.fn.handlebars.options = {
        // Delete the template from the compiled store when a removal action is specified. Accepts true (default) or false
        delete_compiled: true,

        // Store a compiled template. This improves efficiency if using the same template continuously. Accepts true (default) or false
        store_compiled: true,

        // Allow the addition of multiple template(s) inside a content element. Accepts true (default) or false
        refill: true,

        // Remove pre-existing compiled templates from the specified content element when adding/appending a template
        //
        // The following options are:
        //      'none' (default): Don't remove any template(s)
        //      'all': Remove all valid template(s) from the content element
        //      'same': Remove only those template(s) that match the provided template string
        remove_type: _remove.NONE,

        // How to output the compiled template to the specified content element
        //
        // The following options are:
        //      'append' (default): Append to the content element
        //      'html': Return a compiled template as HTML
        //      'compiled'/'raw': Return a compiled template
        type: _type.APPEND,

        // Check whether the data passed to the plugin is empty
        validate: true
    };
})(this, this.jQuery);
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var conf = require('../../../config');
var fs = require('fs')
var usersDB = require('../../users/db')

var app;

router.post("/", function(req, res, next) {
  if(app && conf.mode!="development") {
    res.json(app);
    return;
  }
  app = { };
  app.modules = { };
  loadModule(0, function () {
    app.isLoggedIn = (req.session.login!==undefined);
    usersDB.findUserByEmail(req.session.email, function (err, user) {
      if(err) {
        res.json({
          status:false,
          level: "danger",
          msg: err.message
        });
        return;
      }
      app.status = true;
      app.level = "success";
      app.msg = "app успешно загружен.";
      app.user = user;
      res.json(app);
    })

  })
})

function loadModule(i, callback) {
  var data = { };
  var moduleName = conf.modules[i];
  data.moduleName = moduleName;
  var modulePath = '../modules/' + moduleName
  if(!fs.existsSync(modulePath))
  {
    data.status = false;
    data.msg = 'Модуль '+moduleName+' не найден'
    data.level = "warning"
    app.modules[moduleName] = data;
    console.log("Модуль", moduleName, "не найден!");
    if(conf.mode !== "development") {
      return;
    }
  }
  console.log(6)
  if (fs.existsSync(modulePath + '/html')) {
    var htmlFiles = fs.readdirSync(modulePath + '/html')
    data.html = {}
    if (htmlFiles) {
      htmlFiles.forEach(function (file) {
        data.html[file.replace(/\.[^/.]+$/, "")] = fs.readFileSync(modulePath + '/html/' + file, encoding = 'utf8')
      })
    }
  }
  console.log(7)
  if (fs.existsSync(modulePath + '/js')) {
    var jsFiles = fs.readdirSync(modulePath + '/js')
    data.js = {}
    if (jsFiles) {
      jsFiles.forEach(function (file) {
        data.js[file.replace(/\.[^/.]+$/, "")] = fs.readFileSync(modulePath + '/js/' + file, encoding = 'utf8')
      })
    }
  }
  console.log(8)
  data.status = true;
  data.msg = "Модуль " + moduleName + " был импортирован!"
  data.level = "success"
  console.log(9)
  app.modules[moduleName] = data;
    if(i==conf.modules.length-1) {
    callback();
  } else {
    loadModule(i+1, callback);
  }
}

module.exports = router;
<commit_msg>Добавил поле mode в объект app. Убрал лишний отладочный вывод из /modules/app/route/index.js<commit_after>var express = require('express');
var router = express.Router();
var conf = require('../../../config');
var fs = require('fs')
var usersDB = require('../../users/db')

var app;

router.post("/", function(req, res, next) {
  if(app && conf.mode!="development") {
    res.json(app);
    return;
  }
  app = { };
  app.modules = { };
  loadModule(0, function () {
    app.isLoggedIn = (req.session.login!==undefined);
    usersDB.findUserByEmail(req.session.email, function (err, user) {
      if(err) {
        res.json({
          status:false,
          level: "danger",
          msg: err.message
        });
        return;
      }
      app.mode = conf.mode;
      app.status = true;
      app.level = "success";
      app.msg = "app успешно загружен.";
      app.user = user;
      res.json(app);
    })

  })
})

function loadModule(i, callback) {
  var data = { };
  var moduleName = conf.modules[i];
  data.moduleName = moduleName;
  var modulePath = '../modules/' + moduleName
  if(!fs.existsSync(modulePath))
  {
    data.status = false;
    data.msg = 'Модуль '+moduleName+' не найден'
    data.level = "warning"
    app.modules[moduleName] = data;
    console.log("Модуль", moduleName, "не найден!");
    if(conf.mode !== "development") {
      return;
    }
  }
  if (fs.existsSync(modulePath + '/html')) {
    var htmlFiles = fs.readdirSync(modulePath + '/html')
    data.html = {}
    if (htmlFiles) {
      htmlFiles.forEach(function (file) {
        data.html[file.replace(/\.[^/.]+$/, "")] = fs.readFileSync(modulePath + '/html/' + file, encoding = 'utf8')
      })
    }
  }
  if (fs.existsSync(modulePath + '/js')) {
    var jsFiles = fs.readdirSync(modulePath + '/js')
    data.js = {}
    if (jsFiles) {
      jsFiles.forEach(function (file) {
        data.js[file.replace(/\.[^/.]+$/, "")] = fs.readFileSync(modulePath + '/js/' + file, encoding = 'utf8')
      })
    }
  }
  data.status = true;
  data.msg = "Модуль " + moduleName + " был импортирован!"
  data.level = "success"
  app.modules[moduleName] = data;
    if(i==conf.modules.length-1) {
    callback();
  } else {
    loadModule(i+1, callback);
  }
}

module.exports = router;
<|endoftext|>


<commit_before>let colorNames = {
    aliceblue: 0xf0f8ff,
    antiquewhite: 0xfaebd7,
    aqua: 0x00ffff,
    aquamarine: 0x7fffd4,
    azure: 0xf0ffff,
    beige: 0xf5f5dc,
    bisque: 0xffe4c4,
    black: 0x000000,
    blanchedalmond: 0xffebcd,
    blue: 0x0000ff,
    blueviolet: 0x8a2be2,
    brown: 0xa52a2a,
    burlywood: 0xdeb887,
    cadetblue: 0x5f9ea0,
    chartreuse: 0x7fff00,
    chocolate: 0xd2691e,
    coral: 0xff7f50,
    cornflowerblue: 0x6495ed,
    cornsilk: 0xfff8dc,
    crimson: 0xdc143c,
    cyan: 0x00ffff,
    darkblue: 0x00008b,
    darkcyan: 0x008b8b,
    darkgoldenrod: 0xb8860b,
    darkgray: 0xa9a9a9,
    darkgreen: 0x006400,
    darkgrey: 0xa9a9a9,
    darkkhaki: 0xbdb76b,
    darkmagenta: 0x8b008b,
    darkolivegreen: 0x556b2f,
    darkorange: 0xff8c00,
    darkorchid: 0x9932cc,
    darkred: 0x8b0000,
    darksalmon: 0xe9967a,
    darkseagreen: 0x8fbc8f,
    darkslateblue: 0x483d8b,
    darkslategray: 0x2f4f4f,
    darkslategrey: 0x2f4f4f,
    darkturquoise: 0x00ced1,
    darkviolet: 0x9400d3,
    deeppink: 0xff1493,
    deepskyblue: 0x00bfff,
    dimgray: 0x696969,
    dimgrey: 0x696969,
    dodgerblue: 0x1e90ff,
    firebrick: 0xb22222,
    floralwhite: 0xfffaf0,
    forestgreen: 0x228b22,
    fuchsia: 0xff00ff,
    gainsboro: 0xdcdcdc,
    ghostwhite: 0xf8f8ff,
    gold: 0xffd700,
    goldenrod: 0xdaa520,
    gray: 0x808080,
    gray89: 0xe3e3e3,
    gray94: 0xf0f0f0,
    green: 0x008000,
    greenyellow: 0xadff2f,
    grey: 0x808080,
    grey89: 0xe3e3e3,
    grey94: 0xf0f0f0,
    honeydew: 0xf0fff0,
    hotpink: 0xff69b4,
    indianred: 0xcd5c5c,
    indigo: 0x4b0082,
    ivory: 0xfffff0,
    khaki: 0xf0e68c,
    lavender: 0xe6e6fa,
    lavenderblush: 0xfff0f5,
    lawngreen: 0x7cfc00,
    lemonchiffon: 0xfffacd,
    lightblue: 0xadd8e6,
    lightcoral: 0xf08080,
    lightcyan: 0xe0ffff,
    lightgoldenrodyellow: 0xfafad2,
    lightgray: 0xd3d3d3,
    lightgreen: 0x90ee90,
    lightgrey: 0xd3d3d3,
    lightpink: 0xffb6c1,
    lightsalmon: 0xffa07a,
    lightseagreen: 0x20b2aa,
    lightskyblue: 0x87cefa,
    lightslategray: 0x778899,
    lightslategrey: 0x778899,
    lightsteelblue: 0xb0c4de,
    lightyellow: 0xffffe0,
    lime: 0x00ff00,
    limegreen: 0x32cd32,
    linen: 0xfaf0e6,
    magenta: 0xff00ff,
    maroon: 0x800000,
    mediumaquamarine: 0x66cdaa,
    mediumblue: 0x0000cd,
    mediumorchid: 0xba55d3,
    mediumpurple: 0x9370db,
    mediumseagreen: 0x3cb371,
    mediumslateblue: 0x7b68ee,
    mediumspringgreen: 0x00fa9a,
    mediumturquoise: 0x48d1cc,
    mediumvioletred: 0xc71585,
    midnightblue: 0x191970,
    mintcream: 0xf5fffa,
    mistyrose: 0xffe4e1,
    moccasin: 0xffe4b5,
    navajowhite: 0xffdead,
    navy: 0x000080,
    oldlace: 0xfdf5e6,
    olive: 0x808000,
    olivedrab: 0x6b8e23,
    orange: 0xffa500,
    orangered: 0xff4500,
    orchid: 0xda70d6,
    palegoldenrod: 0xeee8aa,
    palegreen: 0x98fb98,
    paleturquoise: 0xafeeee,
    palevioletred: 0xdb7093,
    papayawhip: 0xffefd5,
    peachpuff: 0xffdab9,
    peru: 0xcd853f,
    pink: 0xffc0cb,
    plum: 0xdda0dd,
    powderblue: 0xb0e0e6,
    purple: 0x800080,
    rebeccapurple: 0x663399,
    red: 0xff0000,
    rosybrown: 0xbc8f8f,
    royalblue: 0x4169e1,
    saddlebrown: 0x8b4513,
    salmon: 0xfa8072,
    sandybrown: 0xf4a460,
    seagreen: 0x2e8b57,
    seashell: 0xfff5ee,
    sienna: 0xa0522d,
    silver: 0xc0c0c0,
    skyblue: 0x87ceeb,
    slateblue: 0x6a5acd,
    slategray: 0x708090,
    slategrey: 0x708090,
    snow: 0xfffafa,
    springgreen: 0x00ff7f,
    steelblue: 0x4682b4,
    tan: 0xd2b48c,
    teal: 0x008080,
    thistle: 0xd8bfd8,
    tomato: 0xff6347,
    turquoise: 0x40e0d0,
    violet: 0xee82ee,
    wheat: 0xf5deb3,
    white: 0xffffff,
    whitesmoke: 0xf5f5f5,
    yellow: 0xffff00,
    yellowgreen: 0x9acd32
};

export default colorNames;
<commit_msg>Remove color-names<commit_after><|endoftext|>


<commit_before>/*
 * Route controller.
 */

/*
 * Module dependencies.
 */
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var express = require('express');
var async = require('async');

/**
 * Main route controller class.
 *
 * @param {Application} application Application.
 * @param {Object} settings Application settings object.
 * @class RouteController
 */
var RouteController = module.exports = function(application, settings) {
  this.application = application;
  this.settings = settings;

  var self = this;
  var app = this.application.application;
  var method = settings.method || 'all';

  // Prepare route register params.
  var params = [self.settings.path];

  // Prepare the middleware, if available.
  if ('middleware' in settings) {
    params.push(settings.middleware);
  }

  // Prepare the route handler.
  params.push(function(request, response) {
    self.handle(request, response);
  });

  // Register on express.
  app[method].apply(app, params);
};

/**
 * Handle a request.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object
 */
RouteController.prototype.handle = function(request, response) {
  var self = this;
  var settings = this.settings;

  // @todo: should this parsing be done in a more global middleware?
  if (request.query && request.query.contexts) {
    request.contexts = request.query.contexts;
    delete request.query.contexts;
  }

  this.access(request, response, function(err, allow) {
    if (err) {
      RouteController.error.call(self, request, response, err);
    }

    if (allow) {
      // A route can have either a content or callback property.
      if (settings.content) {
        RouteController.respond.call(self, request, response, settings.content);
      }
      else if (settings.callback) {
        settings.callback(request, response, function(err, content, code) {
          if (err) {
            RouteController.error.call(self, request, response, err);
          }

          if (content) {
            RouteController.respond.call(self, request, response, content, code);
          }
          else {
            // If there's no content, return 404 error.
            RouteController.notFound.call(self, request, response);
          }
        });
      }
    }
    else {
      // Access denied.
      RouteController.forbidden.call(self, request, response);
    }
  });
};

/**
 * Access check.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 * @param {Function} callaback Function called with the access check results.
 */
RouteController.prototype.access = function(request, response, callback) {
  var settings = this.settings;

  // If this is an object, do access check and other mandatory stuff.
  if (settings.access) {
    if (typeof settings.access === 'boolean') {
      // Access check is a string/permission key.
      return callback(null, settings.access);
    }
    else if (typeof settings.access === 'string') {
      return this.application.access(request, settings.access, callback);
    }
    else if (typeof settings.access === 'function') {
      // Access check is a callback.
      return settings.access(request, response, callback);
    }
  }

  // Default to false. Deny access.
  return callback(null, false);
};

/**
 * Respond to a request.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 * @param {Object|String} content Content to send.
 * @param {Number} [code] HTTP status code.
 */
RouteController.respond = function(request, response, content, code) {
  // Default to 200 (success).
  var code = code || 200;
  var payload = {
    status: {
      code: code
    }
  };

  if (content) {
    payload.data = content;
  }

  response.status(code).send(payload);
};

/**
 * Respond to a request with a "server error".
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 */
RouteController.error = function(request, response, error) {
  RouteController.respond.call(this, request, response, {
    title: 'Server error',
    description: "The server couldn't process the request.",
    error: error.toString()
  }, 500);
};

/**
 * Respond to a request with a "page not found" error.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 */
RouteController.notFound = function(request, response) {
  RouteController.respond.call(this, request, response, {
    title: 'Page not found',
    description: "The page you're looking for wasn't found."
  }, 404);
};

/**
 * Respond to a request with a "forbidden" error.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 */
RouteController.forbidden = function(request, response) {
  RouteController.respond.call(this, request, response, {
    title: 'Forbidden',
    description: "You don't have permission to access this page."
  }, 403);
};
<commit_msg>Resolved minor bug.<commit_after>/*
 * Route controller.
 */

/*
 * Module dependencies.
 */
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var express = require('express');
var async = require('async');

/**
 * Main route controller class.
 *
 * @param {Application} application Application.
 * @param {Object} settings Application settings object.
 * @class RouteController
 */
var RouteController = module.exports = function(application, settings) {
  this.application = application;
  this.settings = settings;

  var self = this;
  var app = this.application.application;
  var method = settings.method || 'all';

  // Prepare route register params.
  var params = [self.settings.path];

  // Prepare the middleware, if available.
  if ('middleware' in settings) {
    params.push(settings.middleware);
  }

  // Prepare the route handler.
  params.push(function(request, response) {
    self.handle(request, response);
  });

  // Register on express.
  app[method].apply(app, params);
};

/**
 * Handle a request.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object
 */
RouteController.prototype.handle = function(request, response) {
  var self = this;
  var settings = this.settings;

  // @todo: should this parsing be done in a more global middleware?
  if (request.query && request.query.contexts) {
    request.contexts = request.query.contexts;
    delete request.query.contexts;
  }

  this.access(request, response, function(err, allow) {
    if (err) {
      RouteController.error.call(self, request, response, err);
    }

    if (allow) {
      // A route can have either a content or callback property.
      if (settings.content) {
        RouteController.respond.call(self, request, response, settings.content);
      }
      else if (settings.callback) {
        settings.callback(request, response, function(err, content, code) {
          if (err) {
            RouteController.error.call(self, request, response, err);
          }

          if (content) {
            RouteController.respond.call(self, request, response, content, code);
          }
          else {
            // If there's no content, return 404 error.
            RouteController.notFound.call(self, request, response);
          }
        });
      }
    }
    else {
      // Access denied.
      RouteController.forbidden.call(self, request, response);
    }
  });
};

/**
 * Access check.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 * @param {Function} callaback Function called with the access check results.
 */
RouteController.prototype.access = function(request, response, callback) {
  var settings = this.settings;

  // If this is an object, do access check and other mandatory stuff.
  if (settings.access) {
    if (typeof settings.access === 'boolean') {
      // Access check is a string/permission key.
      return callback(null, settings.access);
    }
    else if (typeof settings.access === 'string') {
      return this.application.access(request, settings.access, callback);
    }
    else if (typeof settings.access === 'function') {
      // Access check is a callback.
      return settings.access(request, response, callback);
    }
  }

  // Default to false. Deny access.
  return callback(null, false);
};

/**
 * Respond to a request.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 * @param {Object|String} content Content to send.
 * @param {Number} [code] HTTP status code.
 */
RouteController.respond = function(request, response, content, code) {
  // Default to 200 (success).
  var code = code || 200;
  var payload = {
    status: {
      code: code
    }
  };

  if (content) {
    payload.data = content;
  }

  // Run response() hook on all extensions.
  this.application.invoke('response', payload, request, response, function() {
    response.status(code).send(payload);
  });

};

/**
 * Respond to a request with a "server error".
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 */
RouteController.error = function(request, response, error) {
  RouteController.respond.call(this, request, response, {
    title: 'Server error',
    description: "The server couldn't process the request.",
    error: error.toString()
  }, 500);
};

/**
 * Respond to a request with a "page not found" error.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 */
RouteController.notFound = function(request, response) {
  RouteController.respond.call(this, request, response, {
    title: 'Page not found',
    description: "The page you're looking for wasn't found."
  }, 404);
};

/**
 * Respond to a request with a "forbidden" error.
 *
 * @param {Request} request Request object.
 * @param {Response} response Response object.
 */
RouteController.forbidden = function(request, response) {
  RouteController.respond.call(this, request, response, {
    title: 'Forbidden',
    description: "You don't have permission to access this page."
  }, 403);
};
<|endoftext|>


<commit_before>$(function() {
	function replaceRadioButtons($buttonDiv, $prototype) {
		//Funktio piilottaa radiobuttonit annetussa divissä ja korvaa ne pseudo-radiobuttoneilla prototyypissä annetun mallin mukaan.
		//Hae yksittäisen nappulan prototyyppi.
		var $button = $prototype.find("button").clone();

		//Poista prototyyppi-divistä kaikki turha
		$prototype.empty();
		$prototype.removeAttr("style");
		$prototype.removeAttr("id");

		//Lisää jokaista radiobuttonin labelia kohti nappula, jonka teksti on sama kuin labelilla
		$buttonDiv.find("label").each(function() {
			var $newButton = $button.clone().text($(this).text());
			var $oldInput = $(this).prev("input:radio");

			//Anna buttoneille eventhandleri, joka tsekkaa oikean radiobuttonin.
			$newButton.on("click", function() {
				$oldInput.attr("checked", "checked");
			});

			$prototype.append($newButton);
		});

		//Piilota vanhat radiobuttonit
		$buttonDiv.children().hide();
		//Liitä uudet radiobuttonit
		$buttonDiv.prepend($prototype);
	}

	//Tarkista, onko lomakkeeseen tullut virheitä edellisestä lähetyksestä
	//(Jos virheitä on tullut, .formerror - luokan diveillä on sisältöä, eli joku niistä on :parent)
	if ($('.formerror:parent').length == 0) {
		//Jos virheitä ei ole tullut tai sivu ladataan ensimmäistä kertaa, tee lomakkeesta modaali, ja piilota se
		$("#subscriptionmodal").modal('hide');
	} else {
		//Jos virheitä on tullut, tee lomakkeesta modaali ja näytä se.
		$("#subscriptionmodal").modal('show');
		//Lisää jokaiselle virheitä sisältävälle fieldsetille luokka 'error' (muuttaa ne punaisiksi)
		$('.formerror:parent').closest('fieldset').addClass('error');
	}

	//Etsi kaikki radiobuttoneja sisältävät divit ja korvaava prototyyppi
	var $radioButtonDivs = $("div.controls:has(input:radio)");
	var $prototype = $("#radiobuttons-prototype");
	//Korvaa kaikki radiobuttonit tyylikkämillä napeilla
	$radioButtonDivs.each(function() {
		replaceRadioButtons($(this), $prototype.clone());
	});

	$("tr.registered").each(function() {
		if ($(this).attr("data-content") != "") {
			$(this).popover({'placement': 'left'});
		}
	});
	$("h2.event").each(function() {
		if ($(this).attr("data-content") != "") {
			$(this).popover({'placement': 'top'});
		}
	});

	$('form').submit(function(){
		//Disabloi ilmoittautumisnappula lomakketta lähettäessä, estää tuplailmoittautumisen vahingossa.
	    $('input[type=submit]', this).attr('disabled', 'disabled');
	});
});<commit_msg>event.js-säätöä<commit_after>$(function() {
	function replaceRadioButtons($buttonDiv, $prototype) {
		//Funktio piilottaa radiobuttonit annetussa divissä ja korvaa ne pseudo-radiobuttoneilla prototyypissä annetun mallin mukaan.
		//Hae yksittäisen nappulan prototyyppi.
		var $button = $prototype.find("button").clone();

		//Poista prototyyppi-divistä kaikki turha
		$prototype.empty();
		$prototype.removeAttr("style");
		$prototype.removeAttr("id");

		//Lisää jokaista radiobuttonin labelia kohti nappula, jonka teksti on sama kuin labelilla
		$buttonDiv.find("label").each(function() {
			var $newButton = $button.clone().text($(this).text());
			var $oldInput = $(this).prev("input:radio");

			//Anna buttoneille eventhandleri, joka tsekkaa oikean radiobuttonin.
			$newButton.on("click", function() {
				$oldInput.attr("checked", "checked");
			});

			$prototype.append($newButton);
		});

		//Piilota vanhat radiobuttonit
		$buttonDiv.children().hide();
		//Liitä uudet radiobuttonit
		$buttonDiv.prepend($prototype);
	}

	//Tarkista, onko lomakkeeseen tullut virheitä edellisestä lähetyksestä
	//(Jos virheitä on tullut, .formerror - luokan diveillä on sisältöä, eli joku niistä on :parent)
	if ($('.formerror:parent').length == 0) {
		//Jos virheitä ei ole tullut tai sivu ladataan ensimmäistä kertaa, tee lomakkeesta modaali, ja piilota se
		$("#subscriptionmodal").modal('hide');
	} else {
		//Jos virheitä on tullut, tee lomakkeesta modaali ja näytä se.
		$("#subscriptionmodal").modal('show');
		//Lisää jokaiselle virheitä sisältävälle fieldsetille luokka 'error' (muuttaa ne punaisiksi)
		$('.formerror:parent').closest('fieldset').addClass('error');
	}

	//Etsi kaikki radiobuttoneja sisältävät divit ja korvaava prototyyppi
	var $radioButtonDivs = $("div.controls:has(input:radio)");
	var $prototype = $("#radiobuttons-prototype");
	//Korvaa kaikki radiobuttonit tyylikkämillä napeilla
	$radioButtonDivs.each(function() {
		replaceRadioButtons($(this), $prototype.clone());
	});

	$("tr.registered").each(function() {
		if ($(this).attr("data-content") != "") {
			$(this).popover({'placement': 'left'});
		}
	});
	$("h2.event").each(function() {
		if ($(this).attr("data-content") != "") {
			$(this).popover({'placement': 'top'});
		}
	});

	$('form').submit(function(){
		//Disabloi ilmoittautumisnappula lomakketta lähettäessä, estää tuplailmoittautumisen vahingossa.
	    $('input[type=submit]', this).attr('disabled', 'disabled');
	});
	$('input#registration_firstName').keyup(function(){
		if ($(this).val() == 'Ilari') {
			window.open("http://www.youtube.com/watch?v=hdqHUms7vUw");
		}
	});
});<|endoftext|>


<commit_before>const cypress = require('cypress');
const { spawn } = require('child_process');

const retro = spawn('../out/retro', ['--test', '--config', '/dev/null', '--assets', '../out/app/dist']);

retro.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

retro.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

retro.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

cypress
  .run()
  .then((results) => {
    console.log(results);
    retro.kill('SIGINT');
  })
  .catch((err) => {
    console.error(err);
    retro.kill('SIGINT');
    process.exit(1);
  });
<commit_msg>Don't fail tests on 302<commit_after>const cypress = require('cypress');
const { spawn } = require('child_process');

const retro = spawn('../out/retro', ['--test', '--config', '/dev/null', '--assets', '../out/app/dist']);

retro.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

retro.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

retro.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

cypress
  .run({ failOnStatusCode: false })
  .then((results) => {
    console.log(results);
    retro.kill('SIGINT');
  })
  .catch((err) => {
    console.error(err);
    retro.kill('SIGINT');
    process.exit(1);
  });
<|endoftext|>


<commit_before>//default core extensions for the default Application Frame modules - copyright by TitanNano / Jovan Gerodetti - http://www.titannano.de

$('wrap')(function(){

"use strict";

// if your required list type isn't here just add it
if($$.NodeList && !$$.NodeList.prototype.forEach) $$.NodeList.prototype.forEach= $$.Array.prototype.forEach;
if($$.TouchList && !$$.TouchList.prototype.forEach) $$.TouchList.prototype.forEach= $$.Array.prototype.forEach;

/* --- last extension --- */
var ArrayLast= function(){
	return this[this.length -1];
};

if($$.Array && !$$.Array.prototype.last) $$.Array.prototype.last= ArrayLast;

});
<commit_msg>improved core-extension<commit_after>//default core extensions for the default Application Frame modules - copyright by TitanNano / Jovan Gerodetti - http://www.titannano.de

var apply= function(){
	"use strict";

// 	if your required list type isn't here just add it
	if($$.NodeList && !$$.NodeList.prototype.forEach) $$.NodeList.prototype.forEach= $$.Array.prototype.forEach;
	if($$.TouchList && !$$.TouchList.prototype.forEach) $$.TouchList.prototype.forEach= $$.Array.prototype.forEach;

/* --- last extension --- */
	var ArrayLast= function(){
		return this[this.length -1];
	};

	if($$.Array && !$$.Array.prototype.last) $$.Array.prototype.last= ArrayLast;

	if($$.TouchList && !$$.TouchList.prototype.indexOf) $$.TouchList.prototype.indexOf= Array.prototype.indexOf;
	if($$.TouchList && !$$.TouchList.prototype.find) $$.TouchList.prototype.find= Array.prototype.find;
};

export default {
	coreExtension : {
		apply : apply
	}
};
<|endoftext|>


<commit_before>/******************************************
 * Form Handlers and page                 *
 * generators for TSSAA WebApp Fat Client *
 *****************************************/

$(document).on("pageinit", function(e, obj) {
    /**
     * Login form handler
     */
    $("#login_page").on("submit", function(e, obj) {

        var formData = $("#login_form").serialize();

        $.ajax( "app_dev.php/login", {
            type: "POST",
            data: formData,
            contentType: 'application/x-www-form-urlencoded',
            success: loginSuccess
        });
        return false;
    });

    /**
     * Get school list ajax handler
     */
    $("#school_list_page_a").on("click", function(e, obj) {
        $.ajax("app_dev.php/get_school_list", {
            type: "GET",
            cache: "true",
            success: generateSchoolList
        });
    });

    /**
     * Add school form ajax handler
     */
    $('#add_school_submit').on('click', function(e, obj) {

        var  formData = $('#add_school_form').serialize();

        $.ajax("app_dev.php/add_school", {
            type: "POST",
            cache: false,
            data: formData,
            success: popDBDialog
        });
        return false;
    });

});

/**
 * Login form ajax callback
 * TODO session management handled here?
 */
function loginSuccess(response) {
    alert("loginSuccess:\n" + response);
    $.mobile.changePage($("#options_page"), {
            transition: "slideup",
            reverse: true,
        });
}

/**
 * DB Dialog ajax success callback
 */
function popDBDialog(response) {
    try {
        var data = $.parseJSON(response);
        alert(data);
    } catch(err) {
        alert(err);
    }

    var response_items = [];

    $.each(data, function(response, obj) {
            response_items.push('
'+response[obj]['name']+':	'+response[obj]['name']+'
');
    });

    $('
',{
			'class': 'response_table',
			html: response_items.join('')
		}).replaceAll("#response");

    $.mobile.changePage("#db_confirm_dialog");
}

/**
 * School List response handler
 * generates ul of schools returned from DB
 */
function generateSchoolList(response) {

    try {
        var school_data = $.parseJSON(response);
    } catch(err) {
        alert(err);
    }

    var schools = [];

    $.each(school_data, function(school) {
                var name = school;
                var phone = school.phone;
                var address = school.address;

                //TODO expanding li for each school with phone, address, etc
                schools.push('
'+name+'
');
            });

    $('ul#school_list').html(schools.join(''));
    $('ul#school_list').listview("refresh");
};
<commit_msg>examine jsonParse'd school_data<commit_after>/******************************************
 * Form Handlers and page                 *
 * generators for TSSAA WebApp Fat Client *
 *****************************************/

$(document).on("pageinit", function(e, obj) {
    /**
     * Login form handler
     */
    $("#login_page").on("submit", function(e, obj) {

        var formData = $("#login_form").serialize();

        $.ajax( "app_dev.php/login", {
            type: "POST",
            data: formData,
            contentType: 'application/x-www-form-urlencoded',
            success: loginSuccess
        });
        return false;
    });

    /**
     * Get school list ajax handler
     */
    $("#school_list_page_a").on("click", function(e, obj) {
        $.ajax("app_dev.php/get_school_list", {
            type: "GET",
            cache: "true",
            success: generateSchoolList
        });
    });

    /**
     * Add school form ajax handler
     */
    $('#add_school_submit').on('click', function(e, obj) {

        var  formData = $('#add_school_form').serialize();

        $.ajax("app_dev.php/add_school", {
            type: "POST",
            cache: false,
            data: formData,
            success: popDBDialog
        });
        return false;
    });

});

/**
 * Login form ajax callback
 * TODO session management handled here?
 */
function loginSuccess(response) {
    alert("loginSuccess:\n" + response);
    $.mobile.changePage($("#options_page"), {
            transition: "slideup",
            reverse: true,
        });
}

/**
 * DB Dialog ajax success callback
 */
function popDBDialog(response) {
    try {
        var data = $.parseJSON(response);
        alert(data);
    } catch(err) {
        alert(err);
    }

    var response_items = [];

    $.each(data, function(key, val) {
            response_items.push('
'+key+':	'+val+'
');
    });

    $('
',{
			'class': 'response_table',
			html: response_items.join('')
		}).replaceAll("#response");

    $.mobile.changePage("#db_confirm_dialog");
}

/**
 * School List response handler
 * generates ul of schools returned from DB
 */
function generateSchoolList(response) {

    try {
        var school_data = $.parseJSON(response);
        alert(school_data);
    } catch(err) {
        alert(err);
    }

    var schools = [];

    $.each(school_data, function(school) {
                var name = school;
                var phone = school.phone;
                var address = school.address;

                schools.push('
'+name+'
');
            });

    $('ul#school_list').html(schools.join(''));
    $('ul#school_list').listview("refresh");
};
<|endoftext|>


<commit_before>self.deprecationWorkflow = self.deprecationWorkflow || {};
self.deprecationWorkflow.config = {
  workflow: [
    { handler: "silence", matchId: "deprecate-router-events" },
    { handler: "silence", matchId: "ember-runtime.deprecate-copy-copyable" },
    { handler: "silence", matchId: "ember-polyfills.deprecate-merge" },
    { handler: "silence", matchId: "ember-data:method-calls-on-destroyed-store" },
    { handler: "silence", matchId: "ember-component.send-action" }
  ]
};
<commit_msg>flush deprecations<commit_after>self.deprecationWorkflow = self.deprecationWorkflow || {};
self.deprecationWorkflow.config = {
  workflow: [
    { handler: "silence", matchId: "deprecate-router-events" },
    { handler: "silence", matchId: "ember-runtime.deprecate-copy-copyable" },
    { handler: "silence", matchId: "ember-polyfills.deprecate-merge" },
    { handler: "silence", matchId: "ember-data:method-calls-on-destroyed-store" },
    { handler: "silence", matchId: "ember-component.send-action" },
    { handler: "silence", matchId: "ember-views.curly-components.jquery-element" },
    { handler: "silence", matchId: "ember-test-helpers.rendering-context.jquery-element" }
  ]
};
<|endoftext|>


<commit_before>//  elmoSlider v0.0.3 by Michal Dolny
//  dependencies: jQuery

$.fn.elmoSlider = function(options) {
    var defaults = {
        content: 'smth',
        n: 'smth',
        x: 'smth',
        anim: 'smth'
    };
    // n - number of slides
    // x - slide width
    // example - 3 slides, each 360px wide
    // state represents margin that will be applied to each slide
    var state = [0],
        i = 0,  // start point
        slider = content;
    for(var j=1; j<n; j++){
        state[j]=-(j*x);
    }
    $(slider).on('click', '.slide-left', function(){
        i--;
        if( i < 0 ){ i = 2 };
        if(anim == 'opacity'){
            $('.active-slide').removeClass('active-slide');
            $('.slide'+(i+1)).addClass('active-slide');
        }else{
            $(slider).find('.slider-content').animate({'margin-left': state[i]}, 'slow');
        };
    });
    $(slider).on('click', '.slide-right', function(){
        i++;
        if( i > 2 ){ i = 0 };
        if(anim == 'opacity'){
            $('.active-slide').removeClass('active-slide');
            $('.slide'+(i+1)).addClass('active-slide');
        }else{
            $(slider).find('.slider-content').animate({'margin-left': state[i]}, 'slow');
        };
    });
};<commit_msg>wrap the plugin<commit_after>//  elmoSlider v0.0.3 by Michal Dolny
//  dependencies: jQuery

(function($){

$.fn.elmoSlider = function(options) {
    var defaults = {
        content: 'smth',
        n: 'smth',
        x: 'smth',
        anim: 'smth'
    };
    // n - number of slides
    // x - slide width
    // example - 3 slides, each 360px wide
    // state represents margin that will be applied to each slide
    var state = [0],
        i = 0,  // start point
        slider = content;
    for(var j=1; j<n; j++){
        state[j]=-(j*x);
    }
    $(slider).on('click', '.slide-left', function(){
        i--;
        if( i < 0 ){ i = 2 };
        if(anim == 'opacity'){
            $('.active-slide').removeClass('active-slide');
            $('.slide'+(i+1)).addClass('active-slide');
        }else{
            $(slider).find('.slider-content').animate({'margin-left': state[i]}, 'slow');
        };
    });
    $(slider).on('click', '.slide-right', function(){
        i++;
        if( i > 2 ){ i = 0 };
        if(anim == 'opacity'){
            $('.active-slide').removeClass('active-slide');
            $('.slide'+(i+1)).addClass('active-slide');
        }else{
            $(slider).find('.slider-content').animate({'margin-left': state[i]}, 'slow');
        };
    });
};

})(jQuery);<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import DownloadIcon from './icon';

class DownloadButton extends Component {
    constructor () {
        super();
    }
    render () {
        return (
            <button
                title="Download"
                style={{
						background: 'none',
						border: 'none',
						cursor: 'pointer',
						height: 40,
						outline: 'none',
						padding: 10,
						position: 'relative',
						left: -10,
						top: 0,
						width: 40,
						verticalAlign: 'bottom',
						float: 'left'
					}}
                onClick={this.props.handler}
            >
				<span
                    dangerouslySetInnerHTML={{ __html: DownloadIcon }}
                />
            </button>
        )
    }
}

export default DownloadButton;
<commit_msg>Minor codestyle whitespace fix<commit_after>import React, { Component, PropTypes } from 'react';
import DownloadIcon from './icon';

class DownloadButton extends Component {
    constructor () {
        super();
    }
    render () {
        return (
            <button
                title="Download"
                style={{
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    height: 40,
                    outline: 'none',
                    padding: 10,
                    position: 'relative',
                    left: -10,
                    top: 0,
                    width: 40,
                    verticalAlign: 'bottom',
                    float: 'left'
                }}
                onClick={this.props.handler}
            >
				<span
                    dangerouslySetInnerHTML={{ __html: DownloadIcon }}
                />
            </button>
        )
    }
}

export default DownloadButton;
<|endoftext|>