<commit_before>var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");

var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

// CONTACTS API ROUTES BELOW

// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
  console.log("ERROR: " + reason);
  res.status(code || 500).json({"error": message});
}

/*  "/test"
 *    GET: tests this server is operational
 */

app.get("/test", function(req, res) {
  //handleError(res, err.message, "Failed to get generic item.");
  res.status(200).json(
      {
        "result": "success",
        "message": "GET /test endpoint is working"
      }
    );
});<commit_msg>Add missing server start code; small adjustments<commit_after>'use strict';

const
  express = require("express"),
  path = require("path"),
  bodyParser = require("body-parser");

var app = express();
app.set('port', process.env.PORT || 5000);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
  console.log("ERROR: " + reason);
  res.status(code || 500).json({"error": message});
}

/*  "/test"
 *    GET: tests this server is operational
 */

app.get("/test", function(req, res) {
  //handleError(res, err.message, "Failed to get generic item.");
  res.status(200).json(
      {
        "result": "success",
        "message": "GET /test endpoint is working"
      }
    );
});

// Start server
app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

module.exports = app;<|endoftext|>


<commit_before>angular.module('ot.service.event', [

])
    .service('otEventService', function ($interpolate) {

        var variableRegex = /\$\{([:a-zA-Z_]+)\}/g;
        var self = {};

        self.renderEvent = function (event) {

            return event.template.replace(
                variableRegex,
                replacementFunction(event)
            );
        };

        function replacementFunction(event) {
            return function (match, expression) {
                if (expression.charAt(0) == ':') {
                    // We want a value
                    var valueKey = expression.substring(1);
                } else {
                    // We want an entity reference
                    var entity = event.entities[expression];
                    if (!entity) {
                        return replacementEntityError(event, expression);
                    }
                    // Link definition
                    var link = {
                        cls: ''
                    };
                    if (expression == 'PROJECT') {
                        link.uri = "#/project/" + entity.id;
                        link.name = entity.name;
                    }
                    // Link rendering
                    return $interpolate('{{name}}')(link);
                }
            };
        }

        return self;

    })
;<commit_msg>#33 GUI: event rendering: values and entities<commit_after>angular.module('ot.service.event', [

])
    .service('otEventService', function ($interpolate) {

        var variableRegex = /\$\{([:a-zA-Z_]+)\}/g;
        var self = {};

        self.renderEvent = function (event) {

            return event.template.replace(
                variableRegex,
                replacementFunction(event)
            );
        };

        function replacementFunction(event) {
            return function (match, expression) {
                if (expression.charAt(0) == ':') {
                    // We want a value
                    var valueKey = expression.substring(1);
                    var value = event.values[valueKey];
                    if (!value) {
                        return replacementValueError(event, valueKey);
                    }
                    // Rendering
                    return $interpolate('{{value}}')({
                        valueKey: valueKey,
                        value: value
                    });
                } else {
                    // We want an entity reference
                    var entity = event.entities[expression];
                    if (!entity) {
                        return replacementEntityError(event, expression);
                    }
                    // Link definition
                    var link = {
                        cls: ''
                    };
                    if (expression == 'PROJECT') {
                        link.uri = "#/project/" + entity.id;
                        link.name = entity.name;
                    }
                    else if (expression == 'BRANCH') {
                        link.uri = "#/branch/" + entity.id;
                        link.name = entity.name;
                    }
                    else if (expression == 'BUILD') {
                        link.uri = "#/build/" + entity.id;
                        link.name = entity.name;
                    }
                    else if (expression == 'PROMOTION_LEVEL') {
                        link.uri = "#/promotionLevel/" + entity.id;
                        link.name = entity.name;
                    }
                    else if (expression == 'VALIDATION_STAMP') {
                        link.uri = "#/validationStamp/" + entity.id;
                        link.name = entity.name;
                    }
                    else if (expression == 'VALIDATION_RUN') {
                        link.uri = "#/validationRun/" + entity.id;
                        link.name = '#' + entity.runOrder;
                    }
                    // Link rendering
                    return $interpolate('{{name}}')(link);
                }
            };
        }

        return self;

    })
;<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
var https = require('https');
var qs = require('qs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_INTERNAL_IP;
        self.port      = process.env.OPENSHIFT_INTERNAL_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_INTERNAL_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/ok'] = function(req, res) {
          res.send('1');
        };

        self.routes['/auth/login'] = function(req, res) {

          var assertion = req.body.assertion;

          var body = qs.stringify({
            assertion: assertion,
            audience: 'http://proxy-dataupco.rhcloud.com'
          });

          var request = https.request({
            host: 'verifier.login.persona.org',
            path: '/verify',
            method: 'POST',
            headers: {
              'content-type': 'application/x-www-form-urlencoded',
              'content-length': body.length
            }
          }, function(bidRes) {
             var data = "";
             bidRes.setEncoding('utf8');
             bidRes.on('data', function (chunk) {
               data += chunk;
             });
             bidRes.on('end', function () {
               var verified = JSON.parse(data);
               if (verified.status == 'okay') {
                 res.json(verified};
               } else {
                 res.writeHead(403);
               }
              resp.write(data);
              resp.end();
            });
          });

          request.write(body);
          request.end();
        };

        self.routes['/auth/logout'] = function(req, res) {
            res.json({'status' : true});
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();
        self.app.configure(function() {
          self.app.use(express.bodyParser());
          self.app.use(express.static(__dirname + '/public'));
        });

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.all(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<commit_msg>add circular type<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
var https = require('https');
var qs = require('qs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_INTERNAL_IP;
        self.port      = process.env.OPENSHIFT_INTERNAL_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_INTERNAL_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/ok'] = function(req, res) {
          res.send('1');
        };

        self.routes['/auth/login'] = function(req, res) {

          var assertion = req.body.assertion;

          var body = qs.stringify({
            assertion: assertion,
            audience: 'http://proxy-dataupco.rhcloud.com'
          });

          var request = https.request({
            host: 'verifier.login.persona.org',
            path: '/verify',
            method: 'POST',
            headers: {
              'content-type': 'application/x-www-form-urlencoded',
              'content-length': body.length
            }
          }, function(bidRes) {
             var data = "";
             bidRes.setEncoding('utf8');
             bidRes.on('data', function(chunk) {
               data += chunk;
             });
             bidRes.on('end', function(){
               var verified = JSON.parse(data);
               if (verified.status == 'okay') {
                 res.json(verified);
               } else {
                 res.writeHead(403);
               }
              resp.write(data);
              resp.end();
            });
          });

          request.write(body);
          request.end();
        };

        self.routes['/auth/logout'] = function(req, res) {
            res.json({'status' : true});
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();
        self.app.configure(function() {
          self.app.use(express.bodyParser());
          self.app.use(express.static(__dirname + '/public'));
        });

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.all(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<|endoftext|>


<commit_before>// Empty JS for your own code to be here<commit_msg>Add legacy devopsdays.js to standard script<commit_after>// Empty JS for your own code to be here

/**
 * jQWidon't v0.1 - Suppress typographic widows
 *   * http://davecardwell.co.uk/javascript/jquery/plugins/jquery-widont/0.1/
 *
 * Dave Cardwell <http://davecardwell.co.uk/>
 *
 * Built on the shoulders of giants:
 *   * John Resig <http://jquery.com/>
 *   * Shaun Inman <http://www.shauninman.com/plete/2006/08/...
 *                                             ...widont-wordpress-plugin.php>
 *
 *
 * Copyright (c) 2006 Dave Cardwell, dual licensed under the MIT and GPL
 * licenses:
 *   * http://www.opensource.org/licenses/mit-license.php
 *   * http://www.gnu.org/licenses/gpl.txt
 */

/**
 * For the latest version of this plugin, and a discussion of its usage and
 * implementation, visit:
 *   * http://davecardwell.co.uk/javascript/jquery/plugins/jquery-widont/
 */

new function() {
    /**
     * The following functions and attributes form the Public interface of the
     * jQWidon't plugin, accessed externally through the $.jqwidont object.
     * See the relevant function definition later in the source for further
     * information.
     *
     * $.jqwidont.auto()
     * $.jqwidont.auto( bool )
     * $.jqwidont.init()
     *
     * $.jqwidont.transform( string )
     */
    var Public = {
        // Given a boolean argument, auto() will turn initialisation at
        // $(document).ready() on or off accordingly.  Without, it simply
        // returns the current status.  init() performs the necessary steps to
        // start the jQWidon't plugin, including suppressing widows in all
        // <h*> elements in the page.
             'auto': function( bool ) {
                         return bool != undefined ? Private.auto = bool
                                                  : Private.auto;
                     },
             'init': function() {
                         return Private.init();
                     },

        // Perform the 'widont' transformation on a given string.
        'transform': function( string ) {
					alert('transforming'+string)
                         return Private.widont( string );
                     }
    };

    // Allow external access to the 'Public' interface through the $.jqwidont
    // object.
    $.jqwidont = Public;

    /**
     * The following functions and attributes form the internal methods and
     * state of the jQWidon't plugin.  See the relevant function definition
     * later in the source for further information.
     *
     * Private.auto
     * Private.init()
     *
     * Private.widont( string )
     *
     * Private.regexp
     */
    var Private = {
        // When auto is true (default), the init() function will be called at
        // $(document).ready().  init() itself performs the necessary steps to
        // start the jQWidon't plugin.
            'auto': true,
            'init': init,

        // Add a non-breaking space between the last two words of a given
        // string.
          'widont': widont,

        // Regular expression for use later in the plugin.
          'regexp': new RegExp(
                        '[\\n\\r\\s]+'            // whitespace/newlines
                      + '('                       // capture...
                      + '[^\\n\\r\\s(?: )]+' // non-whitespace/newlines
                      + '[\\n\\r\\s]*'            // trailing whitespace
                      + ')$'                      // ...to end of the string

                        , 'm' // match across newlines
                    )
    };

    /**
     * Unless disabled before $(document).ready() is triggered, execute the
     * init() function.
     */
    $(document).ready(function() {
        if( Private.auto ) init();
   });

    /**
     * Perform the necessary initialisation to use the jQWidon't plugin.
     */
    function init() {
        // Use the plugin on all <h*> elements in the page..
        $( 'h1,h2,h3,h4,h5,h6' ).widont();
    };

    /**
     * Use the jQWidon't plugin on the given elements.
     */
    $.fn.widont = function() {
        return $(this).each(function() {
            var obj = $(this);
			var a= Private.widont( obj.html() );
          	$(this).html(a);
	//  don't show in firebug???

        });
    };

    /**
     * This function takes a string and uses the Private.regexp function to
     * attempt to replace the whitespace between the final two words with a
     * non-breaking space, so that line-wrapping cannot occur between them.
     */
    function widont( string ) {
		var a=string.replace( Private.regexp, " $1" );
		//var a=string.replace( Private.regexp, " $1" );
        return a;
    };
}();
$(document).ready(function() {
	  $('span.pullquote').each(function(index) {
		var $parentParagraph = $(this).parent('p');
		$parentParagraph.css('position', 'relative');
		$(this).clone().addClass('pulledquote').prependTo($parentParagraph);
	});
});$(document).ready(function() {
    $("h1:contains('&'), h2:contains('&'), h3:contains('&'), h4:contains('&')", document.body)
        .contents()
        .each(
            function() {
                if( this.nodeType == 3 ) {
                    $(this)
                        .replaceWith( this
                            .nodeValue
                            .replace( /&/g, "&" )
                        );
                }
            }
        );
});
<|endoftext|>


<commit_before>import Ember from "ember";

// This helper is internal to liquid-with.
export default function withApplyHelper(options){
  var view = options.data.view,
      parent = view.get('liquidWithParent'),
      withArgs = parent.get('originalArgs').slice();

  withArgs[0] = 'lwith-view.boundContext';
  options = Ember.copy(options);
  options.data.keywords['lwith-view'] = view;
  options.fn = parent.get('innerTemplate');
  options.hash = parent.get('originalHash');
  options.hashTypes = parent.get('originalHashTypes');
  withArgs.push(options);
  return Ember.Handlebars.helpers.with.apply(this, withArgs);
}
<commit_msg>keywords hash is not always present<commit_after>import Ember from "ember";

// This helper is internal to liquid-with.
export default function withApplyHelper(options){
  var view = options.data.view,
      parent = view.get('liquidWithParent'),
      withArgs = parent.get('originalArgs').slice();

  withArgs[0] = 'lwith-view.boundContext';
  options = Ember.copy(options);
  if (!options.data.keywords) {
    options.data.keywords = {};
  }
  options.data.keywords['lwith-view'] = view;
  options.fn = parent.get('innerTemplate');
  options.hash = parent.get('originalHash');
  options.hashTypes = parent.get('originalHashTypes');
  withArgs.push(options);
  return Ember.Handlebars.helpers.with.apply(this, withArgs);
}
<|endoftext|>


<commit_before>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*eslint-env node */
import { parse as parseUrl } from 'url';
import path from 'path';
import fs from 'fs';

import Koa from 'koa';
import { isString, indexOf } from 'lodash';
import session from 'koa-generic-session';
import redisStore from 'koa-redis';
import convert from 'koa-convert';
import cors from 'kcors';
import serve from 'koa-static';
import bodyParser from 'koa-bodyparser';
import mount from 'koa-mount';
import knexLogger from 'knex-logger';
import chokidar from 'chokidar';
import ejs from 'ejs';
import { promisify } from 'bluebird';

import React from 'react';
import { renderToString } from 'react-dom/server'
import { createMemoryHistory } from 'history'
import { Provider } from 'react-redux';
import { Router, RouterContext, match, useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux';
import Helmet from 'react-helmet';
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';

import { getRoutes } from './src/routing';
import { AuthHandler, FetchHandler } from './src/utils/loader';
import {initApi} from './src/api/routing'
import initBookshelf from './src/api/db';
import { API_HOST } from './src/config';
import ApiClient from './src/api/client'

import { initState } from './src/store';
import {
  setCurrentUser, setLikes, setFavourites, setUserFollowedTags,
  setUserFollowedSchools, setUserFollowedGeotags
} from './src/actions';

import db_config from './knexfile';

let exec_env = process.env.DB_ENV || 'development';

let app = new Koa();

let knexConfig = db_config[exec_env];
let bookshelf = initBookshelf(knexConfig);
let api = initApi(bookshelf);
let matchPromisified = promisify(match, { multiArgs: true });
let templatePath = path.join(__dirname, '/src/views/index.ejs');
let template = ejs.compile(fs.readFileSync(templatePath, 'utf8'), {filename: templatePath});

if (exec_env === 'development') {
  let webpackDevMiddleware = require('webpack-koa-dev-middleware').default;
  let webpackHotMiddleware = require('webpack-koa-hot-middleware').default;
  let webpack = require('webpack');
  let webpackConfig = require('./webpack.dev.config');
  let compiler = webpack(webpackConfig);

  app.use(convert(webpackDevMiddleware(compiler, {
    log: console.log,
    path: '/__webpack_hmr',
    publicPath: webpackConfig.output.publicPath,
    stats: {
      colors: true
    }
  })));
  app.use(convert(webpackHotMiddleware(compiler)));

  // Taken from https://github.com/glenjamin/ultimate-hot-reloading-example/blob/master/server.js

  // Do "hot-reloading" of express stuff on the server
  // Throw away cached modules and re-require next time
  // Ensure there's no important state in there!
  var watcher = chokidar.watch('./src/api');
  watcher.on('ready', function () {
    watcher.on('all', function () {
      console.log('Clearing /src/api/ cache from server');
      Object.keys(require.cache).forEach(function (id) {
        if (/\/src\/api\//.test(id)) delete require.cache[id];
      });
    });
  });

  // Do "hot-reloading" of react stuff on the server
  // Throw away the cached client modules and let them be re-required next time
  compiler.plugin('done', function () {
    console.log('Clearing /src/ cache from server');
    Object.keys(require.cache).forEach(function (id) {
        if (/\/src\//.test(id)) delete require.cache[id];
      });
  });
}

app.use(async (ctx, next) => {
  const { hostname } = parseUrl(API_HOST);
  if (isString(ctx.req.hostname) && ctx.req.hostname !== hostname) {
    const newUri = `${API_HOST}${ctx.req.originalUrl}`;
    ctx.status = 301;
    ctx.redirect(newUri);
    return;
  }
  await next();
});

app.keys = ['libertysoil'];

app.use(convert(session({
  store: redisStore(
    {
      host: '127.0.0.1',
      port: 6379
    }
  ),
  key: 'connect.sid',
  cookie: {signed: false}
})));

app.use(bodyParser());  // for parsing application/x-www-form-urlencoded

app.use(convert(cors({
  allowHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
})));

if (indexOf(['test', 'travis'], exec_env) !== -1) {
  let warn = console.error; // eslint-disable-line no-console
  console.error = function(warning) { // eslint-disable-line no-console
    if (/(Invalid prop|Failed propType)/.test(warning)) {
      throw new Error(warning);
    }
    warn.apply(console, arguments);
  };
}

app.use(mount('/api/v1', api));

app.use(convert(serve(`${__dirname}/public/`)));

app.use(async function reactMiddleware(ctx, next) {
  const store = initState();

  if (ctx.session && ctx.session.user && isString(ctx.session.user)) {
    try {
      let user = await bookshelf
        .model('User')
        .where({id: ctx.session.user})
        .fetch({
          require: true,
          withRelated: [
            'following',
            'followed_hashtags',
            'followed_schools',
            'followed_geotags',
            'liked_hashtags',
            'liked_geotags',
            'liked_schools'
          ]
        });

      let data = user.toJSON();

      let likes = await bookshelf.knex
        .select('post_id')
        .from('likes')
        .where({user_id: ctx.session.user});

      let favourites = await bookshelf.knex
        .select('post_id')
        .from('favourites')
        .where({user_id: ctx.session.user});

      store.dispatch(setCurrentUser(data));
      store.dispatch(setLikes(data.id, likes.map(like => like.post_id)));
      store.dispatch(setFavourites(data.id, favourites.map(fav => fav.post_id)));
    } catch (e) {
      console.log(`dispatch failed: ${e.stack}`);
    }
  }

  const authHandler = new AuthHandler(store);
  const fetchHandler = new FetchHandler(store, new ApiClient(API_HOST, ctx));
  const Routes = getRoutes(authHandler.handle, fetchHandler.handleSynchronously);

  const makeRoutes = (history) => (
    <Router history={history}>
      {Routes}
    </Router>
  );

  const memoryHistory = useRouterHistory(createMemoryHistory)();
  const history = syncHistoryWithStore(memoryHistory, store, { selectLocationState: state => state.get('routing') });
  let routes = makeRoutes(history);

  try {
    const [ redirectLocation, renderProps ] = await matchPromisified({ routes, location: ctx.url });

    if (redirectLocation) {
      ctx.status = 307;
      ctx.redirect(redirectLocation.pathname + redirectLocation.search);
      return;
    }

    if (renderProps == null) {
      ctx.status = 404;
      ctx.body = 'Not found';
      return;
    }

    if (fetchHandler.redirectTo !== null) {
      ctx.status = fetchHandler.status;
      ctx.redirect(fetchHandler.redirectTo);
      return;
    }

    try {
      let html = renderToString(
        <Provider store={store}>
          <RouterContext {...renderProps}/>
        </Provider>
      );
      let state = JSON.stringify(store.getState().toJS());

      if (fetchHandler.status !== null) {
        ctx.status = fetchHandler.status;
      }

      const metadata = ExecutionEnvironment.canUseDOM ? Helmet.peek() : Helmet.rewind();

      ctx.staus = 200;
      ctx.body = template({state, html, metadata});
    } catch (e) {
      console.error(e.stack);
      ctx.status = 500;
      ctx.body = e.message;
    }
  } catch (e) {
    console.error(e.stack);
    ctx.status = 500;
    ctx.body = e.message;
  }
});

export default app;
<commit_msg>disable index-support for statics<commit_after>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*eslint-env node */
import { parse as parseUrl } from 'url';
import path from 'path';
import fs from 'fs';

import Koa from 'koa';
import { isString, indexOf } from 'lodash';
import session from 'koa-generic-session';
import redisStore from 'koa-redis';
import convert from 'koa-convert';
import cors from 'kcors';
import serve from 'koa-static';
import bodyParser from 'koa-bodyparser';
import mount from 'koa-mount';
import knexLogger from 'knex-logger';
import chokidar from 'chokidar';
import ejs from 'ejs';
import { promisify } from 'bluebird';

import React from 'react';
import { renderToString } from 'react-dom/server'
import { createMemoryHistory } from 'history'
import { Provider } from 'react-redux';
import { Router, RouterContext, match, useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux';
import Helmet from 'react-helmet';
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';

import { getRoutes } from './src/routing';
import { AuthHandler, FetchHandler } from './src/utils/loader';
import {initApi} from './src/api/routing'
import initBookshelf from './src/api/db';
import { API_HOST } from './src/config';
import ApiClient from './src/api/client'

import { initState } from './src/store';
import {
  setCurrentUser, setLikes, setFavourites, setUserFollowedTags,
  setUserFollowedSchools, setUserFollowedGeotags
} from './src/actions';

import db_config from './knexfile';

let exec_env = process.env.DB_ENV || 'development';

let app = new Koa();

let knexConfig = db_config[exec_env];
let bookshelf = initBookshelf(knexConfig);
let api = initApi(bookshelf);
let matchPromisified = promisify(match, { multiArgs: true });
let templatePath = path.join(__dirname, '/src/views/index.ejs');
let template = ejs.compile(fs.readFileSync(templatePath, 'utf8'), {filename: templatePath});

if (exec_env === 'development') {
  let webpackDevMiddleware = require('webpack-koa-dev-middleware').default;
  let webpackHotMiddleware = require('webpack-koa-hot-middleware').default;
  let webpack = require('webpack');
  let webpackConfig = require('./webpack.dev.config');
  let compiler = webpack(webpackConfig);

  app.use(convert(webpackDevMiddleware(compiler, {
    log: console.log,
    path: '/__webpack_hmr',
    publicPath: webpackConfig.output.publicPath,
    stats: {
      colors: true
    }
  })));
  app.use(convert(webpackHotMiddleware(compiler)));

  // Taken from https://github.com/glenjamin/ultimate-hot-reloading-example/blob/master/server.js

  // Do "hot-reloading" of express stuff on the server
  // Throw away cached modules and re-require next time
  // Ensure there's no important state in there!
  var watcher = chokidar.watch('./src/api');
  watcher.on('ready', function () {
    watcher.on('all', function () {
      console.log('Clearing /src/api/ cache from server');
      Object.keys(require.cache).forEach(function (id) {
        if (/\/src\/api\//.test(id)) delete require.cache[id];
      });
    });
  });

  // Do "hot-reloading" of react stuff on the server
  // Throw away the cached client modules and let them be re-required next time
  compiler.plugin('done', function () {
    console.log('Clearing /src/ cache from server');
    Object.keys(require.cache).forEach(function (id) {
        if (/\/src\//.test(id)) delete require.cache[id];
      });
  });
}

app.use(async (ctx, next) => {
  const { hostname } = parseUrl(API_HOST);
  if (isString(ctx.req.hostname) && ctx.req.hostname !== hostname) {
    const newUri = `${API_HOST}${ctx.req.originalUrl}`;
    ctx.status = 301;
    ctx.redirect(newUri);
    return;
  }
  await next();
});

app.keys = ['libertysoil'];

app.use(convert(session({
  store: redisStore(
    {
      host: '127.0.0.1',
      port: 6379
    }
  ),
  key: 'connect.sid',
  cookie: {signed: false}
})));

app.use(bodyParser());  // for parsing application/x-www-form-urlencoded

app.use(convert(cors({
  allowHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
})));

if (indexOf(['test', 'travis'], exec_env) !== -1) {
  let warn = console.error; // eslint-disable-line no-console
  console.error = function(warning) { // eslint-disable-line no-console
    if (/(Invalid prop|Failed propType)/.test(warning)) {
      throw new Error(warning);
    }
    warn.apply(console, arguments);
  };
}

app.use(mount('/api/v1', api));

app.use(convert(serve(`${__dirname}/public/`, { index: false, defer: false })));

app.use(async function reactMiddleware(ctx, next) {
  const store = initState();

  if (ctx.session && ctx.session.user && isString(ctx.session.user)) {
    try {
      let user = await bookshelf
        .model('User')
        .where({id: ctx.session.user})
        .fetch({
          require: true,
          withRelated: [
            'following',
            'followed_hashtags',
            'followed_schools',
            'followed_geotags',
            'liked_hashtags',
            'liked_geotags',
            'liked_schools'
          ]
        });

      let data = user.toJSON();

      let likes = await bookshelf.knex
        .select('post_id')
        .from('likes')
        .where({user_id: ctx.session.user});

      let favourites = await bookshelf.knex
        .select('post_id')
        .from('favourites')
        .where({user_id: ctx.session.user});

      store.dispatch(setCurrentUser(data));
      store.dispatch(setLikes(data.id, likes.map(like => like.post_id)));
      store.dispatch(setFavourites(data.id, favourites.map(fav => fav.post_id)));
    } catch (e) {
      console.log(`dispatch failed: ${e.stack}`);
    }
  }

  const authHandler = new AuthHandler(store);
  const fetchHandler = new FetchHandler(store, new ApiClient(API_HOST, ctx));
  const Routes = getRoutes(authHandler.handle, fetchHandler.handleSynchronously);

  const makeRoutes = (history) => (
    <Router history={history}>
      {Routes}
    </Router>
  );

  const memoryHistory = useRouterHistory(createMemoryHistory)();
  const history = syncHistoryWithStore(memoryHistory, store, { selectLocationState: state => state.get('routing') });
  let routes = makeRoutes(history);

  try {
    const [ redirectLocation, renderProps ] = await matchPromisified({ routes, location: ctx.url });

    if (redirectLocation) {
      ctx.status = 307;
      ctx.redirect(redirectLocation.pathname + redirectLocation.search);
      return;
    }

    if (renderProps == null) {
      ctx.status = 404;
      ctx.body = 'Not found';
      return;
    }

    if (fetchHandler.redirectTo !== null) {
      ctx.status = fetchHandler.status;
      ctx.redirect(fetchHandler.redirectTo);
      return;
    }

    try {
      let html = renderToString(
        <Provider store={store}>
          <RouterContext {...renderProps}/>
        </Provider>
      );
      let state = JSON.stringify(store.getState().toJS());

      if (fetchHandler.status !== null) {
        ctx.status = fetchHandler.status;
      }

      const metadata = ExecutionEnvironment.canUseDOM ? Helmet.peek() : Helmet.rewind();

      ctx.staus = 200;
      ctx.body = template({state, html, metadata});
    } catch (e) {
      console.error(e.stack);
      ctx.status = 500;
      ctx.body = e.message;
    }
  } catch (e) {
    console.error(e.stack);
    ctx.status = 500;
    ctx.body = e.message;
  }
});

export default app;
<|endoftext|>


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

var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    os = require('os'),
    fs = require('fs'),
    crypto = require('crypto'),
    uploadDir = os.tmpDir() + "/uplodr",
    config = require('./config.js');

if (typeof config.customUploadDir !== 'undefined')
  uploadDir = config.customUploadDir;

mkdirIfNotExist(uploadDir);

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // current date/time of session, use UTC to avoid DST
    var date = new Date();
    var dateString = '' + date.getUTCFullYear()
              + twoDigits(date.getUTCMonth()+1)
              + twoDigits(date.getUTCDate())
              + '-'
              + twoDigits(date.getUTCHours())
              + twoDigits(date.getUTCMinutes())
              + twoDigits(date.getUTCSeconds());
    var newUploadDir = uploadDir
                     + '/' + dateString
                     + '-' + randomCharacters(5);
    mkdirIfNotExist(newUploadDir);
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.uploadDir = newUploadDir;
    form.parse(req, function(err, fields, files) {
      // metadata
      var metafile = newUploadDir + '/metadata.txt';
      fs.appendFile(metafile,
        util.inspect({fields: fields, files: files}),
        function(err){
          if (err) throw err;
        }
      );
      console.log('uplodr: new %s', metafile);
      // files.upload, "upload" is the name of the input field
      processUpload(files.upload);
      processUpload(files.upload2);
      processUpload(files.upload3);
      processUpload(files.upload4);
      processUpload(files.upload5);
      // response to browser
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload.\n\n');
      // res.end(util.inspect({fields: fields, files: files}));
      res.end();
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title">
'+
    '<input type="file" name="upload">
'+
    '<input type="file" name="upload2">
'+
    '<input type="file" name="upload3">
'+
    '<input type="file" name="upload4">
'+
    '<input type="file" name="upload5">
'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(80);

function mkdirIfNotExist(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir);
  if (!fs.existsSync(dir)) {
    return false;
  } else {
    return fs.statSync(dir).isDirectory();
  }
}

function twoDigits(num) {
  if (Number(num) < 10) {
    return '0' + Number(num);
  } else {
    return num;
  }
}

function randomCharacters (count, characters) {
  characters = characters
    || "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var result = new Array(count),
      randomByte = crypto.randomBytes(count);
  for (var i = 0; i < count; i++) {
    result[i] = characters[randomByte[i] % characters.length]
  };
  return result.join('');
}

function processUpload(inputName) {
  if (typeof inputName !== 'undefined') {
    if (inputName.size !== 0) {
      if (inputName.name.lastIndexOf('.') > 0) {
        var parts = inputName.name.split('.');
        var extension = parts.pop();
        var newUploadDir = inputName.path.split('/');
        newUploadDir.pop();
        if (String(extension).length > 0) {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join().replace(/,/g,'')
            + '.' + extension;
        } else {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join().replace(/,/g,'');
        }
        fs.rename(inputName.path, safename, function(err){
          if (err) throw err;
        });
      }
      return true;
    }
  }
  return false;
}
<commit_msg>fix newUploadDir<commit_after>#!/usr/bin/env node

var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    os = require('os'),
    fs = require('fs'),
    crypto = require('crypto'),
    uploadDir = os.tmpDir() + "/uplodr",
    config = require('./config.js');

if (typeof config.customUploadDir !== 'undefined')
  uploadDir = config.customUploadDir;

mkdirIfNotExist(uploadDir);

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // current date/time of session, use UTC to avoid DST
    var date = new Date();
    var dateString = '' + date.getUTCFullYear()
              + twoDigits(date.getUTCMonth()+1)
              + twoDigits(date.getUTCDate())
              + '-'
              + twoDigits(date.getUTCHours())
              + twoDigits(date.getUTCMinutes())
              + twoDigits(date.getUTCSeconds());
    var newUploadDir = uploadDir
                     + '/' + dateString
                     + '-' + randomCharacters(5);
    mkdirIfNotExist(newUploadDir);
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.uploadDir = newUploadDir;
    form.parse(req, function(err, fields, files) {
      // metadata
      var metafile = newUploadDir + '/metadata.txt';
      fs.appendFile(metafile,
        util.inspect({fields: fields, files: files}),
        function(err){
          if (err) throw err;
        }
      );
      console.log('uplodr: new %s', metafile);
      // files.upload, "upload" is the name of the input field
      processUpload(files.upload);
      processUpload(files.upload2);
      processUpload(files.upload3);
      processUpload(files.upload4);
      processUpload(files.upload5);
      // response to browser
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload.\n\n');
      // res.end(util.inspect({fields: fields, files: files}));
      res.end();
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title">
'+
    '<input type="file" name="upload">
'+
    '<input type="file" name="upload2">
'+
    '<input type="file" name="upload3">
'+
    '<input type="file" name="upload4">
'+
    '<input type="file" name="upload5">
'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(80);

function mkdirIfNotExist(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir);
  if (!fs.existsSync(dir)) {
    return false;
  } else {
    return fs.statSync(dir).isDirectory();
  }
}

function twoDigits(num) {
  if (Number(num) < 10) {
    return '0' + Number(num);
  } else {
    return num;
  }
}

function randomCharacters (count, characters) {
  characters = characters
    || "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var result = new Array(count),
      randomByte = crypto.randomBytes(count);
  for (var i = 0; i < count; i++) {
    result[i] = characters[randomByte[i] % characters.length]
  };
  return result.join('');
}

function processUpload(inputName) {
  if (typeof inputName !== 'undefined') {
    if (inputName.size !== 0) {
      if (inputName.name.lastIndexOf('.') > 0) {
        var parts = inputName.name.split('.');
        var extension = parts.pop();
        var path = inputName.path.split('/');
        path.pop();
        var newUploadDir = '/' + path.join('/');
        console.log('uplodr: newUploadDir %s', newUploadDir);
        if (String(extension).length > 0) {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join().replace(/,/g,'')
            + '.' + extension;
        } else {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join().replace(/,/g,'');
        }
        fs.rename(inputName.path, safename, function(err){
          if (err) throw err;
        });
      }
      return true;
    }
  }
  return false;
}
<|endoftext|>


<commit_before>define([
  'jquery',
  'underscore',
  'backbone',
  'collections/topic',
  'helpers/conf'
], function($, _, Backbone, TopicCollection, ConfHelper) {
  return {

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    hidePopover: function () {
      if (this.currentPopover) {
        $(this.currentPopover).popover ('hide');
        this.currentPopover = 0;
      }
    },

    popover: function (ev) {

      var that = this;
      var link = $(ev.currentTarget).attr ('href');

      if (this.isLoading) {
        return false;
      }

      if (this.currentPopover == ev.currentTarget) {
        if ($(ev.currentTarget).attr ('data-content-url')) {
          location.href = $(ev.currentTarget).attr ('href');
          return true;
        } else {
          return false;
        }
      }

      this.hidePopover ();

      // TODO: expand this
      var position = function (context, source) {
        var position = $(source).position ();
        var main_position = $(that.el).width ();

        if ($(window).width () < 767) {
          return "auto";
        }

        if (position.top < 100)
          return "bottom";

        if (position.left < 300)
          return "auto left";

        return "auto top";
      };

      // external link

      // FIXME: this is shitty code I've ever written
      //        code repeats, hard to read etc.
      //        need to refactor ASAP

      if (link.match (/^http(s)*:\/\//)) {

        // do nothing if content is already loaded
        if ($(ev.currentTarget).attr ('data-loaded')) {
          return false;
        }

        if ((youtube_id = this.parseYoutubeUrl (link)) != false) {
          if (!ConfHelper.getOption ('youtube')) {
            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }
          return false;
        }

        // check if its image
        // FIXME: 80+
        if (link.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?/i)) {

          if (ConfHelper.getOption ('images')) {

            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }

          return false;

        }

        if (!ConfHelper.getOption ('readability')) {
          window.open (link);
          return false;
        }

        // get content from readability if external url is not an image
        $.ajax ('https://readability.com/api/content/v1/parser?url=' +
                escape (link) + '&token=' +
                // token supposed to be secret but who cares
                'd83f7c87d05f46dcff11e87cbe4b278268f30132'
               ).done (function (data) {

                  $(ev.currentTarget).after ('

' +
                                             data.content +
                                             '

');
                  $(ev.currentTarget).attr ('data-loaded', 'true');

               });

        return false;
      }

      if ($(ev.currentTarget).attr ('data-content')) {
        that.currentPopover = ev.currentTarget;
        $(ev.currentTarget).popover ('show');
        return false;
      }

      this.isLoading = true;

      var topicCollection = new TopicCollection ();
      topicCollection.external_url = link;
      topicCollection.order = 0;
      topicCollection.fetch ({
        success: function (entries) {
          $(ev.currentTarget).attr ('data-content',
                   $('
' + entries.at (0).get ('content') + '
').text ());
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          $(ev.currentTarget).attr ('data-content-url', 'true');
          $(ev.currentTarget).attr ('href', "#t/0/" + topicCollection.external_url);

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        },

        error: function () {
          $(ev.currentTarget).attr ('data-content',
            '404 böyle bir başlık/entry yok')
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        }
      });

      return false;

    },

    trigger: function (ev) {

      if (this.currentPopover) {
        this.hidePopover ();
      }

      return false;
    },

    reset: function () {
      this.currentPopover = false;
    }

  };
});
<commit_msg>add FIXME<commit_after>define([
  'jquery',
  'underscore',
  'backbone',
  'collections/topic',
  'helpers/conf'
], function($, _, Backbone, TopicCollection, ConfHelper) {
  return {

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    hidePopover: function () {
      if (this.currentPopover) {
        $(this.currentPopover).popover ('hide');
        this.currentPopover = 0;
      }
    },

    // FIXME: this is a complete mess. needs serious refactoring
    popover: function (ev) {

      var that = this;
      var link = $(ev.currentTarget).attr ('href');

      if (this.isLoading) {
        return false;
      }

      if (this.currentPopover == ev.currentTarget) {
        if ($(ev.currentTarget).attr ('data-content-url')) {
          location.href = $(ev.currentTarget).attr ('href');
          return true;
        } else {
          return false;
        }
      }

      this.hidePopover ();

      // TODO: expand this
      var position = function (context, source) {
        var position = $(source).position ();
        var main_position = $(that.el).width ();

        if ($(window).width () < 767) {
          return "auto";
        }

        if (position.top < 100)
          return "bottom";

        if (position.left < 300)
          return "auto left";

        return "auto top";
      };

      // external link

      // FIXME: this is shitty code I've ever written
      //        code repeats, hard to read etc.
      //        need to refactor ASAP

      if (link.match (/^http(s)*:\/\//)) {

        // do nothing if content is already loaded
        if ($(ev.currentTarget).attr ('data-loaded')) {
          return false;
        }

        if ((youtube_id = this.parseYoutubeUrl (link)) != false) {
          if (!ConfHelper.getOption ('youtube')) {
            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }
          return false;
        }

        // check if its image
        // FIXME: 80+
        if (link.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?/i)) {

          if (ConfHelper.getOption ('images')) {

            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }

          return false;

        }

        if (!ConfHelper.getOption ('readability')) {
          window.open (link);
          return false;
        }

        // get content from readability if external url is not an image
        $.ajax ('https://readability.com/api/content/v1/parser?url=' +
                escape (link) + '&token=' +
                // token supposed to be secret but who cares
                'd83f7c87d05f46dcff11e87cbe4b278268f30132'
               ).done (function (data) {

                  $(ev.currentTarget).after ('

' +
                                             data.content +
                                             '

');
                  $(ev.currentTarget).attr ('data-loaded', 'true');

               });

        return false;
      }

      if ($(ev.currentTarget).attr ('data-content')) {
        that.currentPopover = ev.currentTarget;
        $(ev.currentTarget).popover ('show');
        return false;
      }

      this.isLoading = true;

      var topicCollection = new TopicCollection ();
      topicCollection.external_url = link;
      topicCollection.order = 0;
      topicCollection.fetch ({
        success: function (entries) {
          $(ev.currentTarget).attr ('data-content',
                   $('
' + entries.at (0).get ('content') + '
').text ());
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          $(ev.currentTarget).attr ('data-content-url', 'true');
          $(ev.currentTarget).attr ('href', "#t/0/" + topicCollection.external_url);

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        },

        error: function () {
          $(ev.currentTarget).attr ('data-content',
            '404 böyle bir başlık/entry yok')
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        }
      });

      return false;

    },

    trigger: function (ev) {

      if (this.currentPopover) {
        this.hidePopover ();
      }

      return false;
    },

    reset: function () {
      this.currentPopover = false;
    }

  };
});
<|endoftext|>


<commit_before>var express = require("express"),
    app     = express.createServer();

app.get("/", function(req, res) {
  res.redirect("/test/index.html");
});

app.configure(function(){
  app.use(express.methodOverride());
  app.use(express.bodyParser());
  app.use(express.static(__dirname + '/'));
  app.use(express.errorHandler({
    dumpExceptions: true,
    showStack: true
  }));
  app.use(app.router);
});

app.listen(8080);
<commit_msg>Update the test server to the latest version of express<commit_after>var express = require("express"),
    app     = express();

app.get("/", function(req, res) {
  res.redirect("/test/index.html");
});

app.configure(function(){
  app.use(express.methodOverride());
  app.use(express.bodyParser());
  app.use(express.static(__dirname + '/'));
  app.use(express.errorHandler({
    dumpExceptions: true,
    showStack: true
  }));
  app.use(app.router);
});

app.listen(8080);
<|endoftext|>


<commit_before>define([
  'jquery',
  'underscore',
  'backbone',
  'collections/topic',
  'helpers/conf'
], function($, _, Backbone, TopicCollection, ConfHelper) {
  return {

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    hidePopover: function () {
      if (this.currentPopover) {
        $(this.currentPopover).popover ('hide');
        this.currentPopover = 0;
      }
    },

    // FIXME: this is a complete mess. needs serious refactoring
    popover: function (ev) {

      var that = this;
      var link = $(ev.currentTarget).attr ('href');

      if (this.isLoading) {
        return false;
      }

      if (this.currentPopover == ev.currentTarget) {
        if ($(ev.currentTarget).attr ('data-content-url')) {
          location.href = $(ev.currentTarget).attr ('href');
          return true;
        } else {
          return false;
        }
      }

      this.hidePopover ();

      // TODO: expand this
      var position = function (context, source) {
        var position = $(source).position ();
        var main_position = $(that.el).width ();

        if ($(window).width () < 767) {
          return "auto";
        }

        if (position.top < 100)
          return "bottom";

        if (position.left < 300)
          return "auto left";

        return "auto top";
      };

      // external link

      // FIXME: this is shitty code I've ever written
      //        code repeats, hard to read etc.
      //        need to refactor ASAP

      if (link.match (/^http(s)*:\/\//)) {

        // do nothing if content is already loaded
        if ($(ev.currentTarget).attr ('data-loaded')) {
          return false;
        }

        if ((youtube_id = this.parseYoutubeUrl (link)) != false) {
          if (!ConfHelper.getOption ('youtube')) {
            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }
          return false;
        }

        // check if its image
        // FIXME: 80+
        if (link.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?/i)) {

          if (ConfHelper.getOption ('images')) {

            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }

          return false;

        }

        if (!ConfHelper.getOption ('readability')) {
          window.open (link);
          return false;
        }

        // get content from readability if external url is not an image
        $.ajax ('https://readability.com/api/content/v1/parser?url=' +
                escape (link) + '&token=' +
                // token supposed to be secret but who cares
                'd83f7c87d05f46dcff11e87cbe4b278268f30132'
               ).done (function (data) {

                  $(ev.currentTarget).after ('

' +
                                             data.content +
                                             '

');
                  $(ev.currentTarget).attr ('data-loaded', 'true');

               }).error (function () {
                 window.open (link);
               });

        return false;
      }

      if ($(ev.currentTarget).attr ('data-content')) {
        that.currentPopover = ev.currentTarget;
        $(ev.currentTarget).popover ('show');
        return false;
      }

      this.isLoading = true;

      var topicCollection = new TopicCollection ();
      topicCollection.external_url = link;
      topicCollection.order = 0;
      topicCollection.fetch ({
        success: function (entries) {

          that.isLoading = false;

          if (!ConfHelper.getOption ('popover')) {
            location.href = '#t/0/' + topicCollection.external_url;
            return;
          }

          $(ev.currentTarget).attr ('data-content',
                   $('
' + entries.at (0).get ('content') + '
').text ());
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          $(ev.currentTarget).attr ('data-content-url', 'true');
          $(ev.currentTarget).attr ('href', "#t/0/" + topicCollection.external_url);

          that.currentPopover = ev.currentTarget;
        },

        error: function () {
          $(ev.currentTarget).attr ('data-content',
            '404 böyle bir başlık/entry yok')
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        }
      });

      return false;

    },

    trigger: function (ev) {

      if (this.currentPopover) {
        this.hidePopover ();
      }

      return false;
    },

    reset: function () {
      this.currentPopover = false;
    }

  };
});
<commit_msg>correct youtube option statement<commit_after>define([
  'jquery',
  'underscore',
  'backbone',
  'collections/topic',
  'helpers/conf'
], function($, _, Backbone, TopicCollection, ConfHelper) {
  return {

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    hidePopover: function () {
      if (this.currentPopover) {
        $(this.currentPopover).popover ('hide');
        this.currentPopover = 0;
      }
    },

    // FIXME: this is a complete mess. needs serious refactoring
    popover: function (ev) {

      var that = this;
      var link = $(ev.currentTarget).attr ('href');

      if (this.isLoading) {
        return false;
      }

      if (this.currentPopover == ev.currentTarget) {
        if ($(ev.currentTarget).attr ('data-content-url')) {
          location.href = $(ev.currentTarget).attr ('href');
          return true;
        } else {
          return false;
        }
      }

      this.hidePopover ();

      // TODO: expand this
      var position = function (context, source) {
        var position = $(source).position ();
        var main_position = $(that.el).width ();

        if ($(window).width () < 767) {
          return "auto";
        }

        if (position.top < 100)
          return "bottom";

        if (position.left < 300)
          return "auto left";

        return "auto top";
      };

      // external link

      // FIXME: this is shitty code I've ever written
      //        code repeats, hard to read etc.
      //        need to refactor ASAP

      if (link.match (/^http(s)*:\/\//)) {

        // do nothing if content is already loaded
        if ($(ev.currentTarget).attr ('data-loaded')) {
          return false;
        }

        if ((youtube_id = this.parseYoutubeUrl (link)) != false) {
          if (ConfHelper.getOption ('youtube')) {
            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }
          return false;
        }

        // check if its image
        // FIXME: 80+
        if (link.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?/i)) {

          if (ConfHelper.getOption ('images')) {

            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }

          return false;

        }

        if (!ConfHelper.getOption ('readability')) {
          window.open (link);
          return false;
        }

        // get content from readability if external url is not an image
        $.ajax ('https://readability.com/api/content/v1/parser?url=' +
                escape (link) + '&token=' +
                // token supposed to be secret but who cares
                'd83f7c87d05f46dcff11e87cbe4b278268f30132'
               ).done (function (data) {

                  $(ev.currentTarget).after ('

' +
                                             data.content +
                                             '

');
                  $(ev.currentTarget).attr ('data-loaded', 'true');

               }).error (function () {
                 window.open (link);
               });

        return false;
      }

      if ($(ev.currentTarget).attr ('data-content')) {
        that.currentPopover = ev.currentTarget;
        $(ev.currentTarget).popover ('show');
        return false;
      }

      this.isLoading = true;

      var topicCollection = new TopicCollection ();
      topicCollection.external_url = link;
      topicCollection.order = 0;
      topicCollection.fetch ({
        success: function (entries) {

          that.isLoading = false;

          if (!ConfHelper.getOption ('popover')) {
            location.href = '#t/0/' + topicCollection.external_url;
            return;
          }

          $(ev.currentTarget).attr ('data-content',
                   $('
' + entries.at (0).get ('content') + '
').text ());
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          $(ev.currentTarget).attr ('data-content-url', 'true');
          $(ev.currentTarget).attr ('href', "#t/0/" + topicCollection.external_url);

          that.currentPopover = ev.currentTarget;
        },

        error: function () {
          $(ev.currentTarget).attr ('data-content',
            '404 böyle bir başlık/entry yok')
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        }
      });

      return false;

    },

    trigger: function (ev) {

      if (this.currentPopover) {
        this.hidePopover ();
      }

      return false;
    },

    reset: function () {
      this.currentPopover = false;
    }

  };
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require("path");
//var logger = require('morgan');
var bodyParser = require('body-parser');
//var cookieParser = require('cookie-parser');
var db = require('./db');

var app = express();

/*
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
*/
app.set('template engine', 'pug');
app.use(express.static(__dirname + '/'));
app.use(express.static('materialize'));
app.set('port', (process.env.PORT || 5000));

//LOAD ROUTES
require('./routes')(app);

//BODY PARSER
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post("/", function(req, res){
  console.log(req.body.user)
  console.log(req.body.pass)
  var user = req.body.user;
  var pass = req.body.pass;
  /*var queryString = `INSERT INTO ouwxcpp_db.user(username, email, password, create_time)  						VALUES  ("${user}", "robbie.whitmer@gmail.com", "${pass}", NOW())`;
  db.query(queryString, function(err, rows, fields) {
    if (err) throw err;
  });
*/
  if((typeof user !== 'undefined')){
      var queryString = `SELECT * FROM OUWXC.user WHERE username="${user}"`;
      db.query(queryString, function(err, rows, fields) {
        if (err) throw err;
        if (rows.length > 0){
        	if(pass === rows[0].password){
        		console.log('Correct password!');
      			  res.redirect('/home');
        		console.log('Did we make it here?');
        	}
        	else{
        		console.log('Incorrect Password');
            res.redirect('/');
          }
        }
        else{
        	console.log('Not a user');
          res.redirect('/');
        }
    });
  }
});

//WORKOUT ENTRY FORM PARSER
app.post("/workoutentry", function(req, res){
  console.log(req.body)
  console.log(req.body.healthstatus)
  console.log(req.body.illness)
  console.log(req.body.injury)
  console.log(req.body.time)
  console.log(req.body.distance)
  var rpe = req.body.rpeval;
  var healthstatus = req.body.healthstatus;
  var illness = req.body.illness;
  var injury = req.body.injury;
  var time = req.body.time;
  var distance = req.body.distance;

  var queryString2 = `INSERT INTO OUWXC.athlete_data(athlete, date, sleep, health_status, Illness, Injury, percent_health, cycle_start, RPE, time, distance, notes) VALUES ("WillSmith", NOW(), "10", "${healthstatus}", "${illness}", "${injury}", "100", NOW(), "${rpe}", "${time}", "${distance}", "just dummy data for testing")`;
  db.query(queryString2, function(err, result) {
    console.log(err)
    console.log(result)
  });

  res.redirect('/workoutentry');
});

//ADMIN ADD USER FORM PARSER
app.post("/admin_add_user_form", function(req, res){
  console.log(req.body)
  var newusername = req.body.newusername;
  var newuserpw = req.body.newuserpw;
  var newuserfirst = req.body.newuserfirst;
  var newuserlast = req.body.newuserlast;
  var newuseremail = req.body.newuseremail;

  var queryString3 = `INSERT INTO OUWXC.user(username, email, password, first, last, create_time) VALUES ("${newusername}", "${newuseremail}", "${newuserpw}", "${newuserfirst}", "${newuserlast}", NOW())`;
  db.query(queryString3, function(err, result) {
    console.log(err)
    console.log(result)
  });

  res.redirect('/admin_add_user');
});

//ADMIN REMOVE USER FORM PARSER
app.post("/admin_remove_user_form", function(req, res){
  console.log(req.body.newuserfirstname)
  console.log(req.body.newuserlastname)
  var newuserfirstname = req.body.newuserfirstname;
  var newuserlastname = req.body.newuserlastname;

  var queryString4 = `DELETE FROM OUWXC.user WHERE username="${newuserfirstname}" AND password="${newuserlastname}"`;
  db.query(queryString4, function(err, result) {
    console.log(err)
    console.log(result)
  });

  res.redirect('/admin_add_user');
});

/*var queryString = 'SELECT * FROM Roles;';
db.query(queryString, function(err, rows, fields) {
    if (err) throw err;
    for (var i in rows) {
        console.log('Data: ', rows[i]);
    }
});
*/

// LAUNCH
app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'));
});
<commit_msg>updated server file to incorporate passport<commit_after>var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var db = require('./db');

var routes = require('./routes/index');

// Init Application
var app = express();

// View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('template engine', 'pug');

// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// Set Static Folder
app.use(express.static(__dirname + '/'));
app.use(express.static('public'));

// Express Session
app.use(session({
	secret: 'teamonacob',
	saveUninitialized: true,
	resave: true
}));

// Passport Init
app.use(passport.initialize());
app.use(passport.session());

// Express Validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

// Connect Flash
app.use(flash());

// Global Vars
app.use(function (req, res, next) {
	res.locals.success_msg = req.flash('success_msg');
	res.locals.error_msg = req.flash('error_msg');
	res.locals.error = req.flash('error');
	res.locals.user = req.user || null;
	next();
});

app.use('/', routes);

// Set Port
app.set('port', (process.env.PORT || 5000));

app.listen(app.get('port'), function() {
	console.log('Server started on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>function preload() {
  RESET_SYMBOL = loadImage("assets/appbar.refresh.svg");
}

function setup() {
  COLOR_1 = color("#233237"); // gunmetal
  COLOR_2 = color("#984b43"); // rusty red

  createCanvas(windowWidth, windowHeight);
  noStroke();
  textAlign(CENTER, CENTER);

  score_1 = 0;
  score_2 = 0;
  reset_button_diameter = 0;
  serve_turn = true;

  serve_indicator = createGraphics(1, 1);
  windowResized();
}

function draw() {
  // score_1 background
  fill(COLOR_1);
  (height > width) ? rect(0, 0, width, 0.5 * height) : rect(0, 0, 0.5 * width, height);
  // score_2 background
  fill(COLOR_2);
  (height > width) ? rect(0, 0.5 * height, width, 0.5 * height) : rect(0.5 * width, 0, 0.5 * width, height);

  // serve indicator
  push();
  blendMode(LIGHTEST);
  if (height > width) {
    serve_turn ? image(serve_indicator, 0, 0, width, 0.5 * height) : image(serve_indicator, 0, 0.5 * height);
  } else {
    serve_turn ? image(serve_indicator, 0, 0) : image(serve_indicator, 0.5 * width, 0);
  }
  pop();

  // scores
  fill(255);
  textSize(0.375 * min(width, height));
  if (height > width) {
    text(score_1.toString(), 0.5 * width, 0.25 * height);
    text(score_2.toString(), 0.5 * width, 0.75 * height);
  } else {
    text(score_1.toString(), 0.25 * width, 0.5 * height);
    text(score_2.toString(), 0.75 * width, 0.5 * height);
  }

  // reset button
  push();
  imageMode(CENTER);
  reset_button_diameter = 0.0625 * max(width, height);
  fill(255);
  ellipse(0.5 * width, 0.5 * height, reset_button_diameter);
  image(RESET_SYMBOL, 0.5 * width, 0.5 * height, reset_button_diameter, reset_button_diameter);
  pop();
}

function mousePressed() {
  if (dist(mouseX, mouseY, 0.5 * width, 0.5 * height) < 0.5 * reset_button_diameter) {
    // reset button clicked
    score_1 = 0;
    score_2 = 0;
  } else {
    var score_1_clicked = (height > width) ? (mouseY < 0.5 * height) : (mouseX < 0.5 * width);

    score_1_clicked ? ++score_1 : ++score_2;

    if ((score_1 + score_2) % 2 === 0) {
      serve_turn = !serve_turn;
    }
  }
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);

  serve_indicator = (height > width) ? createGraphics(windowWidth, 0.5 * windowHeight) : createGraphics(0.5 * windowWidth, windowHeight);
  serve_indicator.noStroke();
  serve_indicator.background(255);
  serve_indicator.fill(0);
  serve_indicator.ellipse(0.5 * serve_indicator.width, 0.5 * serve_indicator.height, sqrt(0.5 * width * height));
}
<commit_msg>Implement proper serve indicator logic<commit_after>function preload() {
  RESET_SYMBOL = loadImage("assets/appbar.refresh.svg");
}

function setup() {
  COLOR_1 = color("#233237"); // gunmetal
  COLOR_2 = color("#984b43"); // rusty red

  createCanvas(windowWidth, windowHeight);
  noStroke();
  textAlign(CENTER, CENTER);

  score_1 = 0;
  score_2 = 0;
  reset_button_diameter = 0;
  serve_turn = true;

  serve_indicator = createGraphics(1, 1);
  windowResized();
}

function draw() {
  // score_1 background
  fill(COLOR_1);
  (height > width) ? rect(0, 0, width, 0.5 * height) : rect(0, 0, 0.5 * width, height);
  // score_2 background
  fill(COLOR_2);
  (height > width) ? rect(0, 0.5 * height, width, 0.5 * height) : rect(0.5 * width, 0, 0.5 * width, height);

  // serve indicator
  push();
  blendMode(LIGHTEST);
  var total_score = score_1 + score_2;
  var serve_indicator_pos = serve_turn != ((floor(total_score / 2) % 2) === 0);
  if (height > width) {
    serve_indicator_pos ? image(serve_indicator, 0, 0, width, 0.5 * height) : image(serve_indicator, 0, 0.5 * height);
  } else {
    serve_indicator_pos ? image(serve_indicator, 0, 0) : image(serve_indicator, 0.5 * width, 0);
  }
  pop();

  // scores
  fill(255);
  textSize(0.375 * min(width, height));
  if (height > width) {
    text(score_1.toString(), 0.5 * width, 0.25 * height);
    text(score_2.toString(), 0.5 * width, 0.75 * height);
  } else {
    text(score_1.toString(), 0.25 * width, 0.5 * height);
    text(score_2.toString(), 0.75 * width, 0.5 * height);
  }

  // reset button
  push();
  imageMode(CENTER);
  reset_button_diameter = 0.0625 * max(width, height);
  fill(255);
  ellipse(0.5 * width, 0.5 * height, reset_button_diameter);
  image(RESET_SYMBOL, 0.5 * width, 0.5 * height, reset_button_diameter, reset_button_diameter);
  pop();
}

function mousePressed() {
  if (dist(mouseX, mouseY, 0.5 * width, 0.5 * height) < 0.5 * reset_button_diameter) {
    // reset button clicked
    if (score_1 + score_2 === 0) {
      serve_turn = !serve_turn;
    } else {
      score_1 = 0;
      score_2 = 0;
    }
  } else {
    var score_1_clicked = (height > width) ? (mouseY < 0.5 * height) : (mouseX < 0.5 * width);

    score_1_clicked ? ++score_1 : ++score_2;
  }
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);

  serve_indicator = (height > width) ? createGraphics(windowWidth, 0.5 * windowHeight) : createGraphics(0.5 * windowWidth, windowHeight);
  serve_indicator.noStroke();
  serve_indicator.background(255);
  serve_indicator.fill(0);
  serve_indicator.ellipse(0.5 * serve_indicator.width, 0.5 * serve_indicator.height, sqrt(0.5 * width * height));
}
<|endoftext|>


<commit_before>//= require mithril
//= require underscore
//= require mithril.postgrest
//= require moment
//= require replace-diacritics
//= require Chartjs
//= require api/init
//= require catarse.js/dist/catarse.js
//= require_self

(function(m, c, Chart){
  //Chart.defaults.global.responsive = true;
  Chart.defaults.global.responsive = false;
  //Chart.defaults.global.animation = false;

  var adminRoot = document.getElementById('new-admin'),
      teamRoot = document.getElementById('team-root'),
      projectInsightsRoot = document.getElementById('project-insights-root');

  if(adminRoot){
    m.mount(adminRoot, c.admin.Contributions);
  }

  if(teamRoot){
    m.mount(teamRoot, c.pages.Team);
  }

  if(projectInsightsRoot){
    m.mount(projectInsightsRoot, m.component(c.project.Insights, {root: projectInsightsRoot}));
  }
}(window.m, window.c, window.Chart));

window.toggleMenu = function(){
  var userMenu = document.getElementById("user-menu-dropdown");
  userMenu.classList.toggle('w--open');
};

<commit_msg>fixes chartjs<commit_after>//= require mithril
//= require underscore
//= require mithril.postgrest
//= require moment
//= require replace-diacritics
//= require chartjs
//= require api/init
//= require catarse.js/dist/catarse.js
//= require_self

(function(m, c, Chart){
  //Chart.defaults.global.responsive = true;
  Chart.defaults.global.responsive = false;
  //Chart.defaults.global.animation = false;

  var adminRoot = document.getElementById('new-admin'),
      teamRoot = document.getElementById('team-root'),
      projectInsightsRoot = document.getElementById('project-insights-root');

  if(adminRoot){
    m.mount(adminRoot, c.admin.Contributions);
  }

  if(teamRoot){
    m.mount(teamRoot, c.pages.Team);
  }

  if(projectInsightsRoot){
    m.mount(projectInsightsRoot, m.component(c.project.Insights, {root: projectInsightsRoot}));
  }
}(window.m, window.c, window.Chart));

window.toggleMenu = function(){
  var userMenu = document.getElementById("user-menu-dropdown");
  userMenu.classList.toggle('w--open');
};

<|endoftext|>


<commit_before>const app = require('./app');
const followerCollector = require('./collect-followers');
// listen for requests :)
const listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
  if (process.env.NODE_ENV === 'development') {
    const port = parseInt(process.env.PORT, 10);
    const browserSync = require('browser-sync');
    browserSync({
      files: ['views/**/*.{handlebars}', './static/*.css'],
      online: false,
      open: false,
      port: port + 1,
      proxy: 'localhost:' + port,
      ui: false
    });
  }
});

console.log('Starting follower collection');
if (process.env.NODE_ENV !== 'development') {
  followerCollector.run();
}
<commit_msg>Remove follower-collector from server.js<commit_after>const app = require('./app');
// listen for requests :)
const listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
  if (process.env.NODE_ENV === 'development') {
    const port = parseInt(process.env.PORT, 10);
    const browserSync = require('browser-sync');
    browserSync({
      files: ['views/**/*.{handlebars}', './static/*.css'],
      online: false,
      open: false,
      port: port + 1,
      proxy: 'localhost:' + port,
      ui: false
    });
  }
});
<|endoftext|>


<commit_before>// Better performance
p5.disableFriendlyErrors = true;

let h;
let particles;

function setup() {
	createCanvas(500, 500);
	h = new Hole();
	particles = [];
	for (let i = 0; i < 150; i++){
		particles.push(new Particle(true));
	}
}

function draw() {
	background(50, 150, 150);
	particles.push(new Particle());

	// Iterate backwards over the particles
	for(let i = particles.length-1; i >= 0; i--){
		p = particles[i];
		p.update();
		if (!p.alive){
			particles.splice(i, 1);
			continue;
		}
		p.show();
	}

	h.update();
	h.show();
}

function mousePressed(){
	h.posLocked = !h.posLocked;
}

class Hole{
	constructor(){
		this.pos = createVector(width/2, height/2);
		this.posLocked = true;
		this.gravity = 1000;
		this.r = 40;
	}

	update(){
		if(!this.posLocked){
			this.pos.x = mouseX;
			this.pos.y = mouseY;
		}
	}

	show(){
		fill(0);
		noStroke();
		ellipse(this.pos.x, this.pos.y, 2*this.r);
	}
}

class Particle{
	constructor(firstTime = false){
		// At the start particles have to be at a random spot
		if (firstTime){
			this.pos = createVector(random(0, width),
									random(0, height));
		}

		// Otherwise spawn them outside the screen at a random spot
		else{
			if (random(0,1)<0.5){
				let x = random(-50, width+50);
				if (x>=0 && x<=width){
					if (random(0,1)<0.5){
						this.pos = createVector(x, random(-50, 0));
					}
					else{
						this.pos = createVector(x, height+random(0, 50));
					}
				}

				else{
					this.pos = createVector(x, random(-50, height+50));
				}
			}

			else{
				let y = random(-50, width+50);
				if (y>=0 && y<=height){
					if (random(0,1)<0.5){
						this.pos = createVector(random(-50, 0), y);
					}
					else{
						this.pos = createVector(width+random(0, 50), y);
					}
				}

				else{
					this.pos = createVector(random(-50, width+50), y);
				}
			}
		}

		this.vel = createVector(0, 0);
		this.acc = createVector(0, 0);
		this.alive = true;
		this.r = random(1, 8);
	}

	update(){
		// Reset acceleration
		this.acc.mult(0);
		// Calculate distance between particle and black hole
		let d = this.pos.dist(h.pos);
		// If particle too far of the screen or if in black hole set it dead
		if(this.pos.x <- 50 || this.pos.x > width + 50 ||
		   this.pos.y < -50 || this.pos.y > height + 50||
	   	   d < (h.r - this.r)){
			   this.alive = false;
		   }
		// Calculate force on this object
		let force = h.gravity/(d*d);
		// Set the acceleration towards the hole
		this.acc.x = h.pos.x - this.pos.x;
		this.acc.y = h.pos.y - this.pos.y;
		// Scale it according to the force
		this.acc.normalize();
		this.acc.mult(force);

		this.vel.add(this.acc);
		this.pos.add(this.vel);
	}

	show(){
		noStroke();
		fill(255);
		ellipse(this.pos.x, this.pos.y, this.r)
	}
}
<commit_msg>Changed controlling hole with mouse.<commit_after>// Better performance
p5.disableFriendlyErrors = true;

let h;
let particles;

function setup() {
	createCanvas(500, 500);
	h = new Hole();
	particles = [];
	for (let i = 0; i < 150; i++){
		particles.push(new Particle(true));
	}
}

function draw() {
	background(50, 150, 150);
	particles.push(new Particle());

	// Iterate backwards over the particles
	for(let i = particles.length-1; i >= 0; i--){
		p = particles[i];
		p.update();
		if (!p.alive){
			particles.splice(i, 1);
			continue;
		}
		p.show();
	}

	h.update();
	h.show();
}

function mousePressed(){
	h.posLocked = false;
}

function mouseReleased(){
	h.posLocked = true;
}

class Hole{
	constructor(){
		this.pos = createVector(width/2, height/2);
		this.posLocked = true;
		this.gravity = 1000;
		this.r = 40;
	}

	update(){
		if(!this.posLocked){
			this.pos.x = mouseX;
			this.pos.y = mouseY;
		}
	}

	show(){
		fill(0);
		noStroke();
		ellipse(this.pos.x, this.pos.y, 2*this.r);
	}
}

class Particle{
	constructor(firstTime = false){
		// At the start particles have to be at a random spot
		if (firstTime){
			this.pos = createVector(random(0, width),
									random(0, height));
		}

		// Otherwise spawn them outside the screen at a random spot
		else{
			if (random(0,1)<0.5){
				let x = random(-50, width+50);
				if (x>=0 && x<=width){
					if (random(0,1)<0.5){
						this.pos = createVector(x, random(-50, 0));
					}
					else{
						this.pos = createVector(x, height+random(0, 50));
					}
				}

				else{
					this.pos = createVector(x, random(-50, height+50));
				}
			}

			else{
				let y = random(-50, width+50);
				if (y>=0 && y<=height){
					if (random(0,1)<0.5){
						this.pos = createVector(random(-50, 0), y);
					}
					else{
						this.pos = createVector(width+random(0, 50), y);
					}
				}

				else{
					this.pos = createVector(random(-50, width+50), y);
				}
			}
		}

		this.vel = createVector(0, 0);
		this.acc = createVector(0, 0);
		this.alive = true;
		this.r = random(1, 8);
	}

	update(){
		// Reset acceleration
		this.acc.mult(0);
		// Calculate distance between particle and black hole
		let d = this.pos.dist(h.pos);
		// If particle too far of the screen or if in black hole set it dead
		if(this.pos.x <- 50 || this.pos.x > width + 50 ||
		   this.pos.y < -50 || this.pos.y > height + 50||
	   	   d < (h.r - this.r)){
			   this.alive = false;
		   }
		// Calculate force on this object
		let force = h.gravity/(d*d);
		// Set the acceleration towards the hole
		this.acc.x = h.pos.x - this.pos.x;
		this.acc.y = h.pos.y - this.pos.y;
		// Scale it according to the force
		this.acc.normalize();
		this.acc.mult(force);

		this.vel.add(this.acc);
		this.pos.add(this.vel);
	}

	show(){
		noStroke();
		fill(255);
		ellipse(this.pos.x, this.pos.y, this.r)
	}
}
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// Catch-all for any other responses not handled above
slapp.message(/^(what day is it\?)/i, ['mention', 'direct_message', 'direct_mention', 'ambient'], (msg) => {
  var now = new Date();
  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  var day = days[ now.getDay() ];

  var returnMessage = { text: "It's "+days[ now.getDay()] };

  if(day == "Friday"){
    returnMessage = { text: "IT'S FRIDAAAYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY!!!!!!!!",
                       attachments: [{
                          text: 'DAYBOT SAYS IT\'S FRIDAAAYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY',
                          title: 'FRIDAY!!!',
                          image_url: 'https://lh6.googleusercontent.com/xLudRRMFGY24Lu7qjwQa1mRM-8VSNWE2l2L72XYDKnCDJQkbQfFoYajCsnrcVlJqF-OrNp4SabUE7cQ=w1920-h901',
                          title_link: 'http://www.usmanjj.com/',
                          color: '#7CD197'
                        }]
                    };
  }
  msg.say(returnMessage);

})

// Catch-all for any other responses not handled above
slapp.message(/^(testestest\?)/i, ['mention', 'direct_message', 'direct_mention', 'ambient'], (msg) => {
  var now = new Date();
  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  var day = days[ now.getDay() ];

  var returnMessage = { text: "It's "+days[ now.getDay()] };

    returnMessage = {
                    text: "It's "+days[ now.getDay()] ,
                    attachments: [{
                          text: "It's "+days[ now.getDay()],
                          image_url: 'https://lh6.googleusercontent.com/xLudRRMFGY24Lu7qjwQa1mRM-8VSNWE2l2L72XYDKnCDJQkbQfFoYajCsnrcVlJqF-OrNp4SabUE7cQ=w1920-h901',
                          title_link: 'http://www.usmanjj.com/',
                          color: '#7CD197'
                        }]
                    };

  msg.say(returnMessage);

})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>adding more more more more more stuff<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// Catch-all for any other responses not handled above
slapp.message(/^(what day is it\?)/i, ['mention', 'direct_message', 'direct_mention', 'ambient'], (msg) => {
  var now = new Date();
  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  var day = days[ now.getDay() ];

  var returnMessage = { text: "It's "+days[ now.getDay()] };

  if(day == "Friday"){
    returnMessage = { text: "IT'S FRIDAAAYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY!!!!!!!!",
                       attachments: [{
                          text: 'DAYBOT SAYS IT\'S FRIDAAAYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY',
                          title: 'FRIDAY!!!',
                          image_url: 'https://lh6.googleusercontent.com/xLudRRMFGY24Lu7qjwQa1mRM-8VSNWE2l2L72XYDKnCDJQkbQfFoYajCsnrcVlJqF-OrNp4SabUE7cQ=w1920-h901',
                          title_link: 'http://www.usmanjj.com/',
                          color: '#7CD197'
                        }]
                    };
  }
  msg.say(returnMessage);

})

// Catch-all for any other responses not handled above
slapp.message(/^(testestest\?)/i, ['mention', 'direct_message', 'direct_mention', 'ambient'], (msg) => {
  var now = new Date();
  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  var day = days[ now.getDay() ];

  var returnMessage = { text: "It's "+days[ now.getDay()] };

    returnMessage = {
                    text: "It's "+days[ now.getDay()] ,
                    attachments: [{
                          text: "It's "+days[ now.getDay()],
                          title: 'FRIDAY!!!',
                          image_url: 'https://lh6.googleusercontent.com/xLudRRMFGY24Lu7qjwQa1mRM-8VSNWE2l2L72XYDKnCDJQkbQfFoYajCsnrcVlJqF-OrNp4SabUE7cQ=w1920-h901',
                          title_link: 'http://www.usmanjj.com/',
                          color: '#7CD197'
                        }]
                    };

  msg.say(returnMessage);

})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>