<commit_before>angular.module('app', ['ui.router', 'ngMaterial', 'ngCookies'])
    .config(function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.when('', 'settings');
        $stateProvider
            .state('auth', {
                url: '/login',
                templateUrl: 'views/login.html',
                controller: 'AuthController'
            })
            .state('logged', {
                templateUrl: '/views/main.html',
                controller: 'MainController'
            })
            .state('logged.settings', {
                url: '/settings',
                views: {
                    'mainView': {
                        templateUrl: 'views/settings.html',
                        controller: 'SettingsController'
                    },
                    'titleView': {
                        template: 'Settings'
                    }
                }
            })
            .state('logged.timetable', {
                url: '/timetable',
                views: {
                    'mainView': {
                        templateUrl: 'views/timetable.html',
                        controller: 'TimetableController'
                    },
                    'titleView': {
                        template: 'Timetable'
                    }
                }
            });
    })
    .service('auth', function ($cookies) {
        this.loggedIn = function () {
            return $cookies.loggedIn;
        }
    })
    .service('settings', function () {
        var saved = {
            classDuration: 90
        };
        this.save = function (data) {
            saved = data;
        };
        this.get = function () {
            return saved;
        };
    })
    .factory('addToGCalendar', function ($http) {
        return function (groupName, cb) {
            $http.get('https://accounts.google.com/o/oauth2/auth?' +
            'scope=email%20profile&' +
            'state=%2Fprofile&' +
            'redirect_uri=https%3A%2F%2Fuscheduler.herokuapp.com%2Foauthcallback&' +
            'response_type=token&' +
            'client_id=571482470120-gulh6a8qqf0kfgf1rqqeula5mgk8v698.apps.googleusercontent.com')
                .success(function (data) {
                    cb(true);
                })
                .error(function (data) {
                    cb(false, data);
                });
        }
    })
    .controller('AuthController', function ($scope, $http, $cookies, $state) {
        $scope.signIn = function () {
            console.log('Sending sign in request');
           // $http.post('/api/auth/', $scope.user).then(function (result) {
                $cookies.loggedIn = true;
                $cookies.email = $scope.email;
                if (true || result.status === 200) {
                    console.log('Logged in');
                    $state.go('logged.settings');
                } else {
                    console.log('/api/auth no result === success');
                }
            //}, function () {
            //    console.log('/api/auth err connection');
            //})
        };

        $scope.signUp = function () {
            console.log('Sending sign up request');
            //$http.post('/api/user/', $scope.user).then(function (result) {
                $cookies.loggedIn = true;
                $cookies.email = $scope.email;
                if (true ||result.status === 200) {
                    console.log('Registered');
                    $scope.signIn();
                } else {
                    console.log('/api/user no result success');
                }
            //}, function () {
            //    console.log('/api/user err connection');
            //})
        }
    })
    .controller('MainController', function ($scope, $state, $cookies) {
        $scope.logOut = function () {
            delete $cookies.loggedIn;
            delete $cookies.email;
            delete $cookies.password;
            $state.go('auth');
        }
    })
    .controller('SettingsController', function ($scope, $state, settings, addToGCalendar) {
        $scope.user = settings.get();
        $scope.user.university = "NTUU KPI";

        $scope.saveSettings = function () {
            $state.go('logged.timetable');
        };

        $scope.addToGCalendar = function () {
            addToGCalendar($scope.user.group, function (result, data) {
                console.log('Result of adding to gcal: ' + result);
                alert('Result of adding to gcal: ' + result + ', data: '+ data);
            });
        };
    })
    .controller('TimetableController', function ($scope, $mdDialog) {
        $scope.days = [
            'Monday',
            'Tuesday',
            'Wednesday',
            'Thursday',
            'Friday'
        ];
        var oneDay = [
            {
                name: "Mathematics",
                audience: "103",
                teacher_name: "Mukha I. P.",
                type: "lection",
                start_time: "8:30",
                end_time: "10:15",
                color: "#4e6cef"
            },
            {
                name: "Physics",
                audience: "103",
                teacher_name: "Mukha I. P.",
                type: "lection",
                start_time: "10:30",
                end_time: "12:10",
                color: "#4e6cef"
            }
        ];

        $scope.classes = [
            [
                {
                    name: "Mathematics",
                    audience: "103",
                    teacher_name: "Mukha I. P.",
                    type: "lection",
                    start_time: "8:30",
                    end_time: "10:15",
                    color: "#4e6cef"
                },
                {
                    name: "Physics",
                    audience: "103",
                    teacher_name: "Rokoviy I. P.",
                    type: "lection",
                    start_time: "10:25",
                    end_time: "12:20",
                    color: "#4e6cef"
                },
                {
                    name: "English",
                    audience: "103",
                    teacher_name: "Pasichniy I. P.",
                    type: "lection",
                    start_time: "12:20",
                    end_time: "14:15",
                    color: "#4e6cef"
                }
            ], //mon
            [
                {
                    name: "Software Engineering",
                    audience: "103",
                    teacher_name: "Buzovskiy Q. P.",
                    type: "lection",
                    start_time: "10:30",
                    end_time: "12:10",
                    color: "#4e6cef"
                }
            ], //tue
            [
                {
                    name: "Computer Engineering",
                    audience: "103",
                    teacher_name: "Ivanov I. P.",
                    type: "lection",
                    start_time: "8:30",
                    end_time: "10:15",
                    color: "#4e6cef"
                },
                {
                    name: "Theory of algorithms",
                    audience: "103",
                    teacher_name: "Molchanovskiy I. O.",
                    type: "lection",
                    start_time: "10:25",
                    end_time: "12:20",
                    color: "#4e6cef"
                },
                {
                    name: "Computer science",
                    audience: "103",
                    teacher_name: "Mukha I. P.",
                    type: "lection",
                    start_time: "12:20",
                    end_time: "14:15",
                    color: "#4e6cef"
                }
            ], // wed
            [
                {
                    name: "Algorithms and DS",
                    audience: "103",
                    teacher_name: "Boldak  A. O.",
                    type: "lection",
                    start_time: "8:30",
                    end_time: "10:15",
                    color: "#4e6cef"
                },
                {
                    name: "Electrical Engineering",
                    audience: "103",
                    teacher_name: "Korochkin O. V",
                    type: "lection",
                    start_time: "10:25",
                    end_time: "12:20",
                    color: "#4e6cef"
                }
            ], // thir
            [
                {
                    name: "Computer modelling",
                    audience: "103",
                    teacher_name: "Saverchenko V.G.",
                    type: "lection",
                    start_time: "8:30",
                    end_time: "10:15",
                    color: "#4e6cef"
                },
                {
                    name: "Computer systems",
                    audience: "103",
                    teacher_name: "Lutrkiy G. M.",
                    type: "lection",
                    start_time: "10:25",
                    end_time: "12:20",
                    color: "#4e6cef"
                },
                {
                    name: "OOP",
                    audience: "103",
                    teacher_name: "Nevdaschenko M. V.",
                    type: "lection",
                    start_time: "12:20",
                    end_time: "14:15",
                    color: "#4e6cef"
                }
            ]
        ];
    })
    .run(function($rootScope, $state, $stateParams, auth) {
        $rootScope.$on('$stateChangeStart', function (event, toState, toStateParams) {
            // track the state the user wants to go to; authorization service needs this
            $rootScope.toState = toState;
            $rootScope.toStateParams = toStateParams;
            // if the principal is resolved, do an authorization check immediately. otherwise,
            // it'll be done when the state it resolved.
            if (toState.name === 'auth') {
                return;
            }
            if (!auth.loggedIn()) {
                event.preventDefault();
                console.log('you\'re not logged in');
                $state.go('auth');
            } else {
                console.log('logged in');
            }
        });
    });
<commit_msg>fix oauth to oauth2 in redirect url<commit_after>angular.module('app', ['ui.router', 'ngMaterial', 'ngCookies'])
    .config(function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.when('', 'settings');
        $stateProvider
            .state('auth', {
                url: '/login',
                templateUrl: 'views/login.html',
                controller: 'AuthController'
            })
            .state('logged', {
                templateUrl: '/views/main.html',
                controller: 'MainController'
            })
            .state('logged.settings', {
                url: '/settings',
                views: {
                    'mainView': {
                        templateUrl: 'views/settings.html',
                        controller: 'SettingsController'
                    },
                    'titleView': {
                        template: 'Settings'
                    }
                }
            })
            .state('logged.timetable', {
                url: '/timetable',
                views: {
                    'mainView': {
                        templateUrl: 'views/timetable.html',
                        controller: 'TimetableController'
                    },
                    'titleView': {
                        template: 'Timetable'
                    }
                }
            });
    })
    .service('auth', function ($cookies) {
        this.loggedIn = function () {
            return $cookies.loggedIn;
        }
    })
    .service('settings', function () {
        var saved = {
            classDuration: 90
        };
        this.save = function (data) {
            saved = data;
        };
        this.get = function () {
            return saved;
        };
    })
    .factory('addToGCalendar', function ($http) {
        return function (groupName, cb) {
            $http.get('https://accounts.google.com/o/oauth2/auth?' +
            'scope=email%20profile&' +
            'state=%2Fprofile&' +
            'redirect_uri=https%3A%2F%2Fuscheduler.herokuapp.com%2Foauth2callback&' +
            'response_type=token&' +
            'client_id=571482470120-gulh6a8qqf0kfgf1rqqeula5mgk8v698.apps.googleusercontent.com')
                .success(function (data) {
                    cb(true);
                })
                .error(function (data) {
                    cb(false, data);
                });
        }
    })
    .controller('AuthController', function ($scope, $http, $cookies, $state) {
        $scope.signIn = function () {
            console.log('Sending sign in request');
           // $http.post('/api/auth/', $scope.user).then(function (result) {
                $cookies.loggedIn = true;
                $cookies.email = $scope.email;
                if (true || result.status === 200) {
                    console.log('Logged in');
                    $state.go('logged.settings');
                } else {
                    console.log('/api/auth no result === success');
                }
            //}, function () {
            //    console.log('/api/auth err connection');
            //})
        };

        $scope.signUp = function () {
            console.log('Sending sign up request');
            //$http.post('/api/user/', $scope.user).then(function (result) {
                $cookies.loggedIn = true;
                $cookies.email = $scope.email;
                if (true ||result.status === 200) {
                    console.log('Registered');
                    $scope.signIn();
                } else {
                    console.log('/api/user no result success');
                }
            //}, function () {
            //    console.log('/api/user err connection');
            //})
        }
    })
    .controller('MainController', function ($scope, $state, $cookies) {
        $scope.logOut = function () {
            delete $cookies.loggedIn;
            delete $cookies.email;
            delete $cookies.password;
            $state.go('auth');
        }
    })
    .controller('SettingsController', function ($scope, $state, settings, addToGCalendar) {
        $scope.user = settings.get();
        $scope.user.university = "NTUU KPI";

        $scope.saveSettings = function () {
            $state.go('logged.timetable');
        };

        $scope.addToGCalendar = function () {
            addToGCalendar($scope.user.group, function (result, data) {
                console.log('Result of adding to gcal: ' + result);
                alert('Result of adding to gcal: ' + result + ', data: '+ data);
            });
        };
    })
    .controller('TimetableController', function ($scope, $mdDialog) {
        $scope.days = [
            'Monday',
            'Tuesday',
            'Wednesday',
            'Thursday',
            'Friday'
        ];
        var oneDay = [
            {
                name: "Mathematics",
                audience: "103",
                teacher_name: "Mukha I. P.",
                type: "lection",
                start_time: "8:30",
                end_time: "10:15",
                color: "#4e6cef"
            },
            {
                name: "Physics",
                audience: "103",
                teacher_name: "Mukha I. P.",
                type: "lection",
                start_time: "10:30",
                end_time: "12:10",
                color: "#4e6cef"
            }
        ];

        $scope.classes = [
            [
                {
                    name: "Mathematics",
                    audience: "103",
                    teacher_name: "Mukha I. P.",
                    type: "lection",
                    start_time: "8:30",
                    end_time: "10:15",
                    color: "#4e6cef"
                },
                {
                    name: "Physics",
                    audience: "103",
                    teacher_name: "Rokoviy I. P.",
                    type: "lection",
                    start_time: "10:25",
                    end_time: "12:20",
                    color: "#4e6cef"
                },
                {
                    name: "English",
                    audience: "103",
                    teacher_name: "Pasichniy I. P.",
                    type: "lection",
                    start_time: "12:20",
                    end_time: "14:15",
                    color: "#4e6cef"
                }
            ], //mon
            [
                {
                    name: "Software Engineering",
                    audience: "103",
                    teacher_name: "Buzovskiy Q. P.",
                    type: "lection",
                    start_time: "10:30",
                    end_time: "12:10",
                    color: "#4e6cef"
                }
            ], //tue
            [
                {
                    name: "Computer Engineering",
                    audience: "103",
                    teacher_name: "Ivanov I. P.",
                    type: "lection",
                    start_time: "8:30",
                    end_time: "10:15",
                    color: "#4e6cef"
                },
                {
                    name: "Theory of algorithms",
                    audience: "103",
                    teacher_name: "Molchanovskiy I. O.",
                    type: "lection",
                    start_time: "10:25",
                    end_time: "12:20",
                    color: "#4e6cef"
                },
                {
                    name: "Computer science",
                    audience: "103",
                    teacher_name: "Mukha I. P.",
                    type: "lection",
                    start_time: "12:20",
                    end_time: "14:15",
                    color: "#4e6cef"
                }
            ], // wed
            [
                {
                    name: "Algorithms and DS",
                    audience: "103",
                    teacher_name: "Boldak  A. O.",
                    type: "lection",
                    start_time: "8:30",
                    end_time: "10:15",
                    color: "#4e6cef"
                },
                {
                    name: "Electrical Engineering",
                    audience: "103",
                    teacher_name: "Korochkin O. V",
                    type: "lection",
                    start_time: "10:25",
                    end_time: "12:20",
                    color: "#4e6cef"
                }
            ], // thir
            [
                {
                    name: "Computer modelling",
                    audience: "103",
                    teacher_name: "Saverchenko V.G.",
                    type: "lection",
                    start_time: "8:30",
                    end_time: "10:15",
                    color: "#4e6cef"
                },
                {
                    name: "Computer systems",
                    audience: "103",
                    teacher_name: "Lutrkiy G. M.",
                    type: "lection",
                    start_time: "10:25",
                    end_time: "12:20",
                    color: "#4e6cef"
                },
                {
                    name: "OOP",
                    audience: "103",
                    teacher_name: "Nevdaschenko M. V.",
                    type: "lection",
                    start_time: "12:20",
                    end_time: "14:15",
                    color: "#4e6cef"
                }
            ]
        ];
    })
    .run(function($rootScope, $state, $stateParams, auth) {
        $rootScope.$on('$stateChangeStart', function (event, toState, toStateParams) {
            // track the state the user wants to go to; authorization service needs this
            $rootScope.toState = toState;
            $rootScope.toStateParams = toStateParams;
            // if the principal is resolved, do an authorization check immediately. otherwise,
            // it'll be done when the state it resolved.
            if (toState.name === 'auth') {
                return;
            }
            if (!auth.loggedIn()) {
                event.preventDefault();
                console.log('you\'re not logged in');
                $state.go('auth');
            } else {
                console.log('logged in');
            }
        });
    });
<|endoftext|>


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

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

exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = 12346;
exports.PROXY_PORT = 1234567;

if (process.platform === 'win32') {
  exports.PIPE = '\\\\.\\pipe\\libuv-test';
} else {
  exports.PIPE = exports.tmpDir + '/test.sock';
}

var util = require('util');
for (var i in util) exports[i] = util[i];
//for (var i in exports) global[i] = exports[i];

function protoCtrChain(o) {
  var result = [];
  for (; o; o = o.__proto__) { result.push(o.constructor); }
  return result.join();
}

exports.indirectInstanceOf = function(obj, cls) {
  if (obj instanceof cls) { return true; }
  var clsChain = protoCtrChain(cls.prototype);
  var objChain = protoCtrChain(obj);
  return objChain.slice(-clsChain.length) === clsChain;
};

exports.ddCommand = function(filename, kilobytes) {
  if (process.platform === 'win32') {
    var p = path.resolve(exports.fixturesDir, 'create-file.js');
    return '"' + process.argv[0] + '" "' + p + '" "' +
           filename + '" ' + (kilobytes * 1024);
  } else {
    return 'dd if=/dev/zero of="' + filename + '" bs=1024 count=' + kilobytes;
  }
};

exports.spawnPwd = function(options) {
  var spawn = require('child_process').spawn;

  if (process.platform === 'win32') {
    return spawn('cmd.exe', ['/c', 'cd'], options);
  } else {
    return spawn('pwd', [], options);
  }
};

// Turn this off if the test should not check for global leaks.
exports.globalCheck = true;

process.on('exit', function() {
  if (!exports.globalCheck) return;
  var knownGlobals = [setTimeout,
                      setInterval,
                      setImmediate,
                      clearTimeout,
                      clearInterval,
                      clearImmediate,
                      console,
                      Buffer,
                      process,
                      global];

  if (global.errno) {
    knownGlobals.push(errno);
  }

  if (global.gc) {
    knownGlobals.push(gc);
  }

  if (global.DTRACE_HTTP_SERVER_RESPONSE) {
    knownGlobals.push(DTRACE_HTTP_SERVER_RESPONSE);
    knownGlobals.push(DTRACE_HTTP_SERVER_REQUEST);
    knownGlobals.push(DTRACE_HTTP_CLIENT_RESPONSE);
    knownGlobals.push(DTRACE_HTTP_CLIENT_REQUEST);
    knownGlobals.push(DTRACE_NET_STREAM_END);
    knownGlobals.push(DTRACE_NET_SERVER_CONNECTION);
    knownGlobals.push(DTRACE_NET_SOCKET_READ);
    knownGlobals.push(DTRACE_NET_SOCKET_WRITE);
  }

  if (global.ArrayBuffer) {
    knownGlobals.push(ArrayBuffer);
    knownGlobals.push(Int8Array);
    knownGlobals.push(Uint8Array);
    knownGlobals.push(Uint8ClampedArray);
    knownGlobals.push(Int16Array);
    knownGlobals.push(Uint16Array);
    knownGlobals.push(Int32Array);
    knownGlobals.push(Uint32Array);
    knownGlobals.push(Float32Array);
    knownGlobals.push(Float64Array);
    knownGlobals.push(DataView);
  }

  for (var x in global) {
    var found = false;

    for (var y in knownGlobals) {
      if (global[x] === knownGlobals[y]) {
        found = true;
        break;
      }
    }

    if (!found) {
      console.error('Unknown global: %s', x);
      assert.ok(false, 'Unknown global found');
    }
  }
});

var mustCallChecks = [];

function runCallChecks() {
  var failed = mustCallChecks.filter(function(context) {
    return context.actual !== context.expected;
  });

  failed.forEach(function(context) {
    console.log('Mismatched %s function calls. Expected %d, actual %d.',
                context.name,
                context.expected,
                context.actual);
    console.log(context.stack.split('\n').slice(2).join('\n'));
  });

  if (failed.length) process.exit(1);
}

exports.mustCall = function(fn, expected) {
  if (typeof expected !== 'number') expected = 1;

  var context = {
    expected: expected,
    actual: 0,
    stack: (new Error).stack,
    name: fn.name || '<anonymous>'
  };

  // add the exit listener only once to avoid listener leak warnings
  if (mustCallChecks.length === 0) process.on('exit', runCallChecks);

  mustCallChecks.push(context);

  return function() {
    context.actual++;
    return fn.apply(this, arguments);
  };
};
<commit_msg>[test] Make global detection work with older node versions<commit_after>// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

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

exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = 12346;
exports.PROXY_PORT = 1234567;

if (process.platform === 'win32') {
  exports.PIPE = '\\\\.\\pipe\\libuv-test';
} else {
  exports.PIPE = exports.tmpDir + '/test.sock';
}

var util = require('util');
for (var i in util) exports[i] = util[i];
//for (var i in exports) global[i] = exports[i];

function protoCtrChain(o) {
  var result = [];
  for (; o; o = o.__proto__) { result.push(o.constructor); }
  return result.join();
}

exports.indirectInstanceOf = function(obj, cls) {
  if (obj instanceof cls) { return true; }
  var clsChain = protoCtrChain(cls.prototype);
  var objChain = protoCtrChain(obj);
  return objChain.slice(-clsChain.length) === clsChain;
};

exports.ddCommand = function(filename, kilobytes) {
  if (process.platform === 'win32') {
    var p = path.resolve(exports.fixturesDir, 'create-file.js');
    return '"' + process.argv[0] + '" "' + p + '" "' +
           filename + '" ' + (kilobytes * 1024);
  } else {
    return 'dd if=/dev/zero of="' + filename + '" bs=1024 count=' + kilobytes;
  }
};

exports.spawnPwd = function(options) {
  var spawn = require('child_process').spawn;

  if (process.platform === 'win32') {
    return spawn('cmd.exe', ['/c', 'cd'], options);
  } else {
    return spawn('pwd', [], options);
  }
};

// Turn this off if the test should not check for global leaks.
exports.globalCheck = true;

process.on('exit', function() {
  if (!exports.globalCheck) return;
  var knownGlobals = [setTimeout,
                      setInterval,
                      clearTimeout,
                      clearInterval,
                      console,
                      Buffer,
                      process,
                      global];

  if (global.setImmediate) {
    knownGlobals.push(setImmediate);
    knownGlobals.push(clearImmediate);
  }

  if (global.errno) {
    knownGlobals.push(errno);
  }

  if (global.gc) {
    knownGlobals.push(gc);
  }

  if (global.DTRACE_HTTP_SERVER_RESPONSE) {
    knownGlobals.push(DTRACE_HTTP_SERVER_RESPONSE);
    knownGlobals.push(DTRACE_HTTP_SERVER_REQUEST);
    knownGlobals.push(DTRACE_HTTP_CLIENT_RESPONSE);
    knownGlobals.push(DTRACE_HTTP_CLIENT_REQUEST);
    knownGlobals.push(DTRACE_NET_STREAM_END);
    knownGlobals.push(DTRACE_NET_SERVER_CONNECTION);
    knownGlobals.push(DTRACE_NET_SOCKET_READ);
    knownGlobals.push(DTRACE_NET_SOCKET_WRITE);
  }

  if (global.ArrayBuffer) {
    knownGlobals.push(ArrayBuffer);
    knownGlobals.push(Int8Array);
    knownGlobals.push(Uint8Array);
    knownGlobals.push(Int16Array);
    knownGlobals.push(Uint16Array);
    knownGlobals.push(Int32Array);
    knownGlobals.push(Uint32Array);
    knownGlobals.push(Float32Array);
    knownGlobals.push(Float64Array);
    knownGlobals.push(DataView);

    if (global.Uint8ClampedArray) {
      knownGlobals.push(Uint8ClampedArray);
    }
  }

  for (var x in global) {
    var found = false;

    for (var y in knownGlobals) {
      if (global[x] === knownGlobals[y]) {
        found = true;
        break;
      }
    }

    if (!found) {
      console.error('Unknown global: %s', x);
      assert.ok(false, 'Unknown global found');
    }
  }
});

var mustCallChecks = [];

function runCallChecks() {
  var failed = mustCallChecks.filter(function(context) {
    return context.actual !== context.expected;
  });

  failed.forEach(function(context) {
    console.log('Mismatched %s function calls. Expected %d, actual %d.',
                context.name,
                context.expected,
                context.actual);
    console.log(context.stack.split('\n').slice(2).join('\n'));
  });

  if (failed.length) process.exit(1);
}

exports.mustCall = function(fn, expected) {
  if (typeof expected !== 'number') expected = 1;

  var context = {
    expected: expected,
    actual: 0,
    stack: (new Error).stack,
    name: fn.name || '<anonymous>'
  };

  // add the exit listener only once to avoid listener leak warnings
  if (mustCallChecks.length === 0) process.on('exit', runCallChecks);

  mustCallChecks.push(context);

  return function() {
    context.actual++;
    return fn.apply(this, arguments);
  };
};
<|endoftext|>


<commit_before>(function(){
   var
      socket = io.connect('/'),
      connectData = {
         room : /[^\/]*$/.exec(window.location.pathname)[0],
         id : window.currentUserId
      },
      gameInst;

   var Game = function(playerId){
      this.playerId    = playerId;
      this.iAmActive   = this.playerId === 0;
      this.turnTimeout = null;
      this.elems= {
         "archer0" : $(".archer0")[0],
         "archer1" : $(".archer1")[0],
         "bullet"  : $(".bullet")[0]
      };

      this.init();
   };

   Game.prototype.init = function(){
      var self = this;

      pWorld.initWorld({
         onHit : function(data){
            self.destroyBullet();

            if(data.hit){
               socket.emit("hit", data);
            }
         }
      });

      setInterval(function(){
         pWorld.step();
         if (!pWorld.isSleep("archer0")){
            self.drawArcher("archer0", pWorld.getArcher("archer0"));
         }
         if (!pWorld.isSleep("archer1")){
            self.drawArcher("archer1", pWorld.getArcher("archer1"));
         }
         if (pWorld.bulletExists()){
            self.drawBullet(pWorld.getBullet());
         }
      }, 1000/60);
   };

   Game.prototype.end = function(){
      window.location = "/";
   };

   Game.prototype.onState = function(data){
      var winner = null;
      if(this.playerId == data.currentPlayer){
         this.iAmActive = true;
         pWorld.changeWind(data.wind/10);
         ChangeWind(data.wind);
      }

      if (!data["player1"].hp){
         winner = 1;
      }
      else if (!data["player2"].hp){
         winner = 0;
      }

      if (winner !== null){
         socket.emit("stopGame", {winner : winner});
      }
      else{
         this.nextTurn();
      }
   };

   Game.prototype.fire = function(pId, vec){
      this.iAmActive = false;
      socket.emit("fire", {name: pId, vec: vec});
   };

   Game.prototype.nextTurn = function(){
      clearTimeout(this.turnTimeout);
      socket.emit("nextTurn");
   };

   Game.prototype.drawArcher = function(name, pos){
      this.elems[name].style.top = pos.top + "px";
      this.elems[name].style.left = pos.left + "px";
   };

   Game.prototype.drawBullet = function(pos){
      $(this.elems["bullet"]).addClass("bulletVisible");
      this.elems["bullet"].style.top = pos.top + "px";
      this.elems["bullet"].style.left = pos.left + "px";
   };
   Game.prototype.destroyBullet = function(){
      $(this.elems["bullet"]).removeClass("bulletVisible");
   };

   socket.on('gameStart', function(data){
      gameInst =  new Game(window.currentPlayerPosition);
      gameInst.onState(data);
   });

   socket.on('state', function (data) {
      gameInst.onState(data);
   });

   socket.on('nextTurn', function (data) {
      gameInst.iAmActive = data.id == gameInst.playerId;
   });

   socket.on('fire', function(data){
      pWorld.createBullet("archer" + data.name, data.vec);
   });

   socket.on('gameEnd', function(){
      gameInst.end();
   });

   socket.emit("ready", connectData);

   $(window).unload(function() {
      socket.emit("leave", connectData);
   });

   $("body").keyup(function(e){
      if(e.which == 32 && gameInst.playerId > -1 && !pWorld.bulletExists() && gameInst.iAmActive){
         if (gameInst.playerId == 0){
            gameInst.fire(gameInst.playerId, {x : 25,y : -15});
         }
         else{
            gameInst.fire(gameInst.playerId, {x : -25,y : -15});
         }
      }
   })
}());
<commit_msg>nextTurn или gameEnd<commit_after>(function(){
   var
      socket = io.connect('/'),
      connectData = {
         room : /[^\/]*$/.exec(window.location.pathname)[0],
         id : window.currentUserId
      },
      gameInst;

   var Game = function(playerId){
      this.playerId    = playerId;
      this.iAmActive   = this.playerId === 0;
      this.turnTimeout = null;
      this.elems= {
         "archer0" : $(".archer0")[0],
         "archer1" : $(".archer1")[0],
         "bullet"  : $(".bullet")[0]
      };

      this.init();
   };

   Game.prototype.init = function(){
      var self = this;

      pWorld.initWorld({
         onHit : function(data){
            self.destroyBullet();

            if(data.hit){
               socket.emit("hit", data);
            }
            else{
               gameInst.nextTurn();
            }
         }
      });

      setInterval(function(){
         pWorld.step();
         if (!pWorld.isSleep("archer0")){
            self.drawArcher("archer0", pWorld.getArcher("archer0"));
         }
         if (!pWorld.isSleep("archer1")){
            self.drawArcher("archer1", pWorld.getArcher("archer1"));
         }
         if (pWorld.bulletExists()){
            self.drawBullet(pWorld.getBullet());
         }
      }, 1000/60);
   };

   Game.prototype.end = function(){
      window.location = "/";
   };

   Game.prototype.onState = function(data){
      var winner = null;
      if(this.playerId == data.currentPlayer){
         this.iAmActive = true;
         pWorld.changeWind(data.wind/10);
         ChangeWind(data.wind);
      }

      if (!data["player1"].hp){
         winner = 1;
      }
      else if (!data["player2"].hp){
         winner = 0;
      }

      if (winner !== null){
         socket.emit("stopGame", {winner : winner});
      }
   };

   Game.prototype.fire = function(pId, vec){
      this.iAmActive = false;
      socket.emit("fire", {name: pId, vec: vec});
   };

   Game.prototype.nextTurn = function(){
      clearTimeout(this.turnTimeout);
      socket.emit("nextTurn");
   };

   Game.prototype.drawArcher = function(name, pos){
      this.elems[name].style.top = pos.top + "px";
      this.elems[name].style.left = pos.left + "px";
   };

   Game.prototype.drawBullet = function(pos){
      $(this.elems["bullet"]).addClass("bulletVisible");
      this.elems["bullet"].style.top = pos.top + "px";
      this.elems["bullet"].style.left = pos.left + "px";
   };
   Game.prototype.destroyBullet = function(){
      $(this.elems["bullet"]).removeClass("bulletVisible");
   };

   socket.on('gameStart', function(data){
      gameInst =  new Game(window.currentPlayerPosition);
      gameInst.onState(data);
   });

   socket.on('state', function (data) {
      gameInst.onState(data);
   });

   socket.on('nextTurn', function (data) {
      gameInst.iAmActive = data.id == gameInst.playerId;
   });

   socket.on('fire', function(data){
      pWorld.createBullet("archer" + data.name, data.vec);
   });

   socket.on('gameEnd', function(){
      gameInst.end();
   });

   socket.emit("ready", connectData);

   $(window).unload(function() {
      socket.emit("leave", connectData);
   });

   $("body").keyup(function(e){
      if(e.which == 32 && gameInst.playerId > -1 && !pWorld.bulletExists() && gameInst.iAmActive){
         if (gameInst.playerId == 0){
            gameInst.fire(gameInst.playerId, {x : 25,y : -15});
         }
         else{
            gameInst.fire(gameInst.playerId, {x : -25,y : -15});
         }
      }
   })
}());
<|endoftext|>


<commit_before>

/// --------------
/// Simple Charts Library based on d3.js to create some simple graphs based on a percentage number
/// by @ahoiin, Sebastian Sadowski
/// --------------

	// define class
	function Fancychart(width, height, colors, color_deactivated){

	  // Define Variables
		this.outerWidth = width || 200;
		this.outerHeight = height || 120;
		this.colors = colors || ["#00ACE4", "#00D8A5", "#9b59b6", "#F1B719", "#e74c3c" ];
		this.color_deactivated = color_deactivated || '#e5e5e5';
		this.color_current = Math.random() * colors.length;

		this.duration = 700;
	}

	// horizontal bar, like a progress bar
	Fancychart.prototype.circles = function(el,val,color){

		var that = this;
		var data = [ val, 100-parseInt(val) ],
			margin = {top: 14, right: 10, bottom: 20, left: 10},
			innerWidth = that.outerWidth - margin.left - margin.right,
	    	innerHeight = that.outerHeight - margin.top - margin.bottom,
	    	color = color || that.colors[Math.round(Math.random() * that.colors.length)],
	    	paddingEl = 14,
	    	elementsInRow = 13,
	    	radius = 4,
	    	row = 1,
	    	dataset = [];

		data.forEach(function(d, i) {
			while(d--) {
				var c = (i==0) ? color : that.color_deactivated;
				dataset.push({color:c});
			}
		});

		var svg = d3.select(el).append("svg")
				.attr("width", that.outerWidth)
				.attr("height", that.outerHeight )
			.append("g")
				.attr("transform", "translate(" + (margin.left ) + "," + (margin.top ) + ")");

		var circle = svg.selectAll("circle")
	    	.data(dataset)
	    .enter().append("circle")
		    .style("fill", function(d,i) { return d.color; })
		    .attr("r", 0)
		    .style("opacity", 0)
		    .attr("cx", function(d,i) { row = (i%elementsInRow == 0) ? i/elementsInRow : row; return ((i+1)-row*elementsInRow) * paddingEl;})
		    .attr("cy", function(d,i) { row = (i%elementsInRow == 0) ? i/elementsInRow : row; return row * paddingEl;})

		 // simple animation on load: opaciy
		 circle.transition()
		 	.duration(that.duration)
		 	.delay(function(d,i) { return 15 * i; })
		 		.style("opacity", 1)
		 		.attr("r", radius);

	};

	// horizontal bar, like a progress bar
	Fancychart.prototype.barHorizontal = function(el,val,color){

		var that = this;
		var data = [ 100, parseInt(val)  ],
			margin = {top: 20, right: 0, bottom: 0, left: 10},
			innerWidth = that.outerWidth - margin.left - margin.right,
	    	innerHeight = that.outerHeight - margin.top - margin.bottom,
	    	color = color || that.colors[Math.round(Math.random() * that.colors.length)];
	    	marginInnerEl = 12;

		var x = d3.scale.linear()
		    .range([0, innerWidth])
		  	.domain([0, d3.max(data, function(d) { return d; })]);

		var svg = d3.select(el).append("svg")
			.attr("width", that.outerWidth)
			.attr("height", that.outerHeight )
		.append("g")
			.attr("transform", "translate(" + (margin.left) + "," + ( innerHeight - 5) + ") rotate(0)");

	  	var g = svg.selectAll(".bar")
	    	.data(data)
	    .enter().append("g")
	    	.style("opacity", 0)
	    	.attr("transform", function(d,i) { marginEl=(i==1)?marginInnerEl/4:0; return "translate(" + marginEl + "," + marginEl + ")"; })

	    var rect = g.append("rect")
			.style("fill", function(d,i) { var c = (i==1) ? color : that.color_deactivated;  return c; })
			.attr("width", 0)
			.attr("height", function(d,i) { marginEl=(i==1)?marginInnerEl:0; return  innerHeight/4-  marginEl/2;  })
			.attr("rx", marginInnerEl)// set the x corner curve radius
			.attr("ry", marginInnerEl);

		 // simple animation on load: opaciy
		 g.transition()
		 	.duration(that.duration)
		 	.delay(function(d,i) { return 200 * i; })
		 		.style("opacity", 1)

		 // simple animation on load: movement
		 rect.transition()
		 	.duration(that.duration)
		 	.ease("quad")
		 	.delay(function(d,i) { return 200 * i; })
		 		.attr("width", function(d,i) { marginEl=(i==1)?marginInnerEl:0; return  x(d) -  marginEl;  })

	};

	// vertical bar chart with the option to rotate it 45degree
	Fancychart.prototype.barVertical = function(el,val,color,rotate){

		var that = this;
		var data = [ 100, parseInt(val) ],
			margin = (rotate) ? {top: 20, right: 70, bottom: 20, left: 5} : {top: 20, right: 50, bottom: 1, left: 10},
			innerWidth = that.outerWidth - margin.left - margin.right,
	    	innerHeight = that.outerHeight - margin.top - margin.bottom,
	    	rotate = rotate || false,
	    	color = color || that.colors[Math.round(Math.random() * that.colors.length)];
	    	marginInnerEl = 5;

		var y = d3.scale.linear()
		    .range([innerHeight, 0])
		  	.domain([0, d3.max(data, function(d) { return d; })]);

		var svg = d3.select(el).append("svg")
			.attr("width", that.outerWidth)
			.attr("height", that.outerHeight )
		.append("g")
			.attr("transform", function(d) { var t = rotate ? "translate(" + (margin.left + innerWidth / 2)+ "," + ( 0 ) + ") rotate(45)" : "translate(" + (margin.left + innerWidth / 2 - innerHeight/2) + "," + (margin.top - 10 ) + ")"; return t; });

		var g = svg.selectAll(".bar")
			.data(data)
		.enter().append("g")
			.style("opacity", 0)
			.attr("transform", function(d,i) { marginEl=(i==1)?marginInnerEl:0; return "translate(" + marginEl + "," + marginEl + ")"; })

		var rect = g.append("rect")
			.style("fill", function(d,i) { var c = (i==1) ? color : that.color_deactivated;  return c; })
			.attr("width", function(d,i) { marginEl=(i==1)?marginInnerEl:0; return  innerHeight -  marginEl*2; })
			.attr("y", function(d) { return innerHeight + marginInnerEl/2; })
			.attr("height", function(d,i) { return 0 ; }) ///
			.attr("rx", marginInnerEl) // set the x corner curve radius
			.attr("ry", marginInnerEl);

		 // simple animation on load: opaciy
		 g.transition()
		 	.duration(that.duration)
		 	.delay(function(d,i) { return 200 * i; })
		 		.style("opacity", 1)

		 // simple animation on load: movement
		 rect.transition()
		 	.duration(that.duration)
		 	.ease("quad")
		 	.delay(function(d,i) { return 200 * i; })
		 		.attr("y", function(d) { return y(d); })
		 		.attr("height", function(d,i) { marginEl=(i==0)?marginInnerEl*2:0; return innerHeight - y(d) + marginEl; })

	};

	// donut chart
	Fancychart.prototype.donut = function(el,val,color){

		var that = this;
		var margin = {top: 25, right: 50, bottom: 1, left: 5},
			innerWidth = that.outerWidth - margin.left - margin.right,
	    	innerHeight = that.outerHeight - margin.top - margin.bottom;
			radius = Math.min(innerWidth, innerHeight) / 2,
		  	data = [val,100-val],
		  	color = color || that.colors[Math.round(Math.random() * that.colors.length)];

		var arc = d3.svg.arc()
		    .outerRadius(radius )
		    .innerRadius(radius - 10);

		var pie = d3.layout.pie()
		    .sort(null)
		    .value(function(d) { return d; });

		var svg = d3.select(el).append("svg")
		    .attr("width", that.outerWidth)
		    .attr("height", that.outerHeight)
		.append("g")
		    .attr("transform", "translate(" + (margin.left + innerWidth / 2) + "," + (margin.top + innerHeight / 2) + ")");

		var g = svg.selectAll(".arc")
			.data(pie(data))
		.enter().append("g")
			.style("opacity", 0);

		var path = g.append("path")
		  .attr("d", arc)
		  .style("stroke-width", "3px")
		  .style("stroke", "#fff")
		  .style("fill", function(d,i) { var c = (i==0) ? color : that.color_deactivated;  return c; });

		// simple animation on load: opacity
		g.transition()
		 	.duration(that.duration)
		 	.ease("quad")
		 	.delay(function(d,i) { return 200 * i; })
		 		.style("opacity", 1);

		path.transition()
			.duration(that.duration)
			.ease("quad")
			.attrTween("d", arcTween);

		function arcTween(finish) {
		    var start = {
		        startAngle: 0,
		        endAngle: 0
		    };
		    var i = d3.interpolate(start, finish);
		    return function(d) { return arc(i(d)); };
		}

	};

<commit_msg>consistent use of tabs/space and replace tabs with 2 spaces<commit_after>

/// --------------
/// Simple Charts Library based on d3.js to create some simple graphs based on a percentage number
/// by @ahoiin, Sebastian Sadowski
/// --------------

// define class
function Fancychart(width, height, colors, color_deactivated){

  // Define Variables
  this.outerWidth = width || 200;
  this.outerHeight = height || 120;
  this.colors = colors || ["#00ACE4", "#00D8A5", "#9b59b6", "#F1B719", "#e74c3c" ];
  this.color_deactivated = color_deactivated || '#e5e5e5';
  this.color_current = Math.random() * colors.length;

  this.duration = 700;
}

// horizontal bar, like a progress bar
Fancychart.prototype.circles = function(el,val,color){

  var that = this;
  var data = [ val, 100-parseInt(val) ],
      margin = {top: 14, right: 10, bottom: 20, left: 10},
      innerWidth = that.outerWidth - margin.left - margin.right,
      innerHeight = that.outerHeight - margin.top - margin.bottom,
      color = color || that.colors[Math.round(Math.random() * that.colors.length)],
      paddingEl = 14,
      elementsInRow = 13,
      radius = 4,
      row = 1,
      dataset = [];

  data.forEach(function(d, i) {
    while(d--) {
      var c = (i==0) ? color : that.color_deactivated;
      dataset.push({color:c});
    }
  });

  var svg = d3.select(el).append("svg")
    .attr("width", that.outerWidth)
    .attr("height", that.outerHeight )
    .append("g")
    .attr("transform", "translate(" + (margin.left ) + "," + (margin.top ) + ")");

  var circle = svg.selectAll("circle")
    .data(dataset)
    .enter().append("circle")
    .style("fill", function(d,i) { return d.color; })
    .attr("r", 0)
    .style("opacity", 0)
    .attr("cx", function(d,i) { row = (i%elementsInRow == 0) ? i/elementsInRow : row; return ((i+1)-row*elementsInRow) * paddingEl;})
    .attr("cy", function(d,i) { row = (i%elementsInRow == 0) ? i/elementsInRow : row; return row * paddingEl;})

   // simple animation on load: opaciy
   circle.transition()
    .duration(that.duration)
    .delay(function(d,i) { return 15 * i; })
    .style("opacity", 1)
    .attr("r", radius);
};

// horizontal bar, like a progress bar
Fancychart.prototype.barHorizontal = function(el,val,color){

  var that = this;
  var data = [ 100, parseInt(val) ],
      margin = { top: 20, right: 0, bottom: 0, left: 10 },
      innerWidth = that.outerWidth - margin.left - margin.right,
      innerHeight = that.outerHeight - margin.top - margin.bottom,
      color = color || that.colors[Math.round(Math.random() * that.colors.length)];
      marginInnerEl = 12;

  var x = d3.scale.linear()
    .range([0, innerWidth])
    .domain([0, d3.max(data, function(d) { return d; })]);

  var svg = d3.select(el).append("svg")
    .attr("width", that.outerWidth)
    .attr("height", that.outerHeight )
    .append("g")
    .attr("transform", "translate(" + (margin.left) + "," + ( innerHeight - 5) + ") rotate(0)");

  var g = svg.selectAll(".bar")
    .data(data)
    .enter().append("g")
    .style("opacity", 0)
    .attr("transform", function(d,i) { marginEl=(i==1)?marginInnerEl/4:0; return "translate(" + marginEl + "," + marginEl + ")"; })

  var rect = g.append("rect")
    .style("fill", function(d,i) { var c = (i==1) ? color : that.color_deactivated;  return c; })
    .attr("width", 0)
    .attr("height", function(d,i) { marginEl=(i==1)?marginInnerEl:0; return  innerHeight/4-  marginEl/2;  })
    .attr("rx", marginInnerEl)// set the x corner curve radius
    .attr("ry", marginInnerEl);

  // simple animation on load: opaciy
  g.transition()
    .duration(that.duration)
    .delay(function(d,i) { return 200 * i; })
    .style("opacity", 1)

  // simple animation on load: movement
  rect.transition()
    .duration(that.duration)
    .ease("quad")
    .delay(function(d,i) { return 200 * i; })
    .attr("width", function(d,i) { marginEl=(i==1)?marginInnerEl:0; return  x(d) -  marginEl;  })
};

// vertical bar chart with the option to rotate it 45degree
Fancychart.prototype.barVertical = function(el,val,color,rotate){

  var that = this;
  var data = [ 100, parseInt(val) ],
      margin = (rotate) ? {top: 20, right: 70, bottom: 20, left: 5} : {top: 20, right: 50, bottom: 1, left: 10},
      innerWidth = that.outerWidth - margin.left - margin.right,
      innerHeight = that.outerHeight - margin.top - margin.bottom,
      rotate = rotate || false,
      color = color || that.colors[Math.round(Math.random() * that.colors.length)];
      marginInnerEl = 5;

  var y = d3.scale.linear()
    .range([innerHeight, 0])
    .domain([0, d3.max(data, function(d) { return d; })]);

  var svg = d3.select(el).append("svg")
    .attr("width", that.outerWidth)
    .attr("height", that.outerHeight )
    .append("g")
    .attr("transform", function(d) { var t = rotate ? "translate(" + (margin.left + innerWidth / 2)+ "," + ( 0 ) + ") rotate(45)" : "translate(" + (margin.left + innerWidth / 2 - innerHeight/2) + "," + (margin.top - 10 ) + ")"; return t; });

  var g = svg.selectAll(".bar")
    .data(data)
    .enter().append("g")
    .style("opacity", 0)
    .attr("transform", function(d,i) { marginEl=(i==1)?marginInnerEl:0; return "translate(" + marginEl + "," + marginEl + ")"; })

  var rect = g.append("rect")
    .style("fill", function(d,i) { var c = (i==1) ? color : that.color_deactivated;  return c; })
    .attr("width", function(d,i) { marginEl=(i==1)?marginInnerEl:0; return  innerHeight -  marginEl*2; })
    .attr("y", function(d) { return innerHeight + marginInnerEl/2; })
    .attr("height", function(d,i) { return 0 ; }) ///
    .attr("rx", marginInnerEl) // set the x corner curve radius
    .attr("ry", marginInnerEl);

   // simple animation on load: opaciy
   g.transition()
    .duration(that.duration)
    .delay(function(d,i) { return 200 * i; })
    .style("opacity", 1)

   // simple animation on load: movement
   rect.transition()
    .duration(that.duration)
    .ease("quad")
    .delay(function(d,i) { return 200 * i; })
    .attr("y", function(d) { return y(d); })
    .attr("height", function(d,i) { marginEl=(i==0)?marginInnerEl*2:0; return innerHeight - y(d) + marginEl; })

};

// donut chart
Fancychart.prototype.donut = function(el,val,color){

  var that = this;
  var margin = {top: 25, right: 50, bottom: 1, left: 5},
      innerWidth = that.outerWidth - margin.left - margin.right,
      innerHeight = that.outerHeight - margin.top - margin.bottom;
      radius = Math.min(innerWidth, innerHeight) / 2,
      data = [val,100-val],
      color = color || that.colors[Math.round(Math.random() * that.colors.length)];

  var arc = d3.svg.arc()
    .outerRadius(radius )
    .innerRadius(radius - 10);

  var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d; });

  var svg = d3.select(el).append("svg")
    .attr("width", that.outerWidth)
    .attr("height", that.outerHeight)
    .append("g")
    .attr("transform", "translate(" + (margin.left + innerWidth / 2) + "," + (margin.top + innerHeight / 2) + ")");

  var g = svg.selectAll(".arc")
    .data(pie(data))
    .enter().append("g")
    .style("opacity", 0);

  var path = g.append("path")
    .attr("d", arc)
    .style("stroke-width", "3px")
    .style("stroke", "#fff")
    .style("fill", function(d,i) { var c = (i==0) ? color : that.color_deactivated;  return c; });

  // simple animation on load: opacity
  g.transition()
    .duration(that.duration)
    .ease("quad")
    .delay(function(d,i) { return 200 * i; })
    .style("opacity", 1);

  path.transition()
    .duration(that.duration)
    .ease("quad")
    .attrTween("d", arcTween);

  function arcTween(finish) {
    var start = {
      startAngle: 0,
      endAngle: 0
    };
    var i = d3.interpolate(start, finish);
    return function(d) { return arc(i(d)); };
  }

};<|endoftext|>


<commit_before>var swig = require('../../lib/swig'),
  expect = require('expect.js'),
  _ = require('lodash'),
  Swig = swig.Swig;

var cases = [
  { code: '= 1', result: '1' },
  { code: '= "burritos"', result: 'burritos' },
  { code: '= 1 + 3', result: '4' },
  { code: '+= 4', result: '5' },
  { code: '-= 1', result: '0' },
  { code: '*= 3', result: '3' },
  { code: '/= 2', result: '0.5' },
  // TODO
  // { code: '= bar|default(1)', result: '1' }
];

describe('Tag: set', function () {

  _.each(cases, function (c) {
    var s = '{% set foo ' + c.code + ' %}';
    it(s, function () {
      expect(swig.render(s + '{{ foo }}', { locals: { foo: 1 }})).to.equal(c.result);
    });
  });

});
<commit_msg>coverage: set 100%<commit_after>var swig = require('../../lib/swig'),
  expect = require('expect.js'),
  _ = require('lodash'),
  Swig = swig.Swig;

var cases = [
  { code: '= 1', result: '1' },
  { code: '= "burritos"', result: 'burritos' },
  { code: '= 1 + 3', result: '4' },
  { code: '+= 4', result: '5' },
  { code: '-= 1', result: '0' },
  { code: '*= 3', result: '3' },
  { code: '/= 2', result: '0.5' },
  { code: '= bar|default(1)', result: '1' }
];

describe('Tag: set', function () {

  _.each(cases, function (c) {
    var s = '{% set foo ' + c.code + ' %}';
    it(s, function () {
      expect(swig.render(s + '{{ foo }}', { locals: { foo: 1 }})).to.equal(c.result);
    });
  });

  it('throws on incorrect assignments', function () {
    expect(function () {
      swig.render('{% set = foo %}');
    }).to.throwError(/Unexpected assignment "=" on line 1\./);
    expect(function () {
      swig.render('{% set blah = foo /= foo %}');
    }).to.throwError(/Unexpected assignment "\/=" on line 1\./);
  });
});
<|endoftext|>


<commit_before>var csVideoTestLayer = cc.Layer.extend({
    ctor:function () {
        var winSize;
        var label, menuItem, menu, title;
        this._super();

        winSize = cc.director.getWinSize();

        title = new cc.LabelTTF("Cocostyle Video Test", "Arial", 20);
        title.setPosition(winSize.width / 2, winSize.height - 40);
        title.setColor(cc.color(255, 255, 0, 255));
        this.addChild(title);

        label = new cc.LabelTTF("[ Main Menu ]", "Arial", 15);
        menuItem = new cc.MenuItemLabel(label, function() {
            var scene = new MainTestLayer();
            cc.director.runScene(scene);
        }, this);

        menu = new cc.Menu(menuItem);
        menu.x = 0;
        menu.y = 0;
        menuItem.x = winSize.width - 70;
        menuItem.y = 25;
        this.addChild(menu);

        var video = new csVideo('http://www.w3schools.com/html/mov_bbb.mp4');
        video.setPosition(cc.p(winSize.width / 2, winSize.height));
        video.video.play();
        this.addChild(video);

        video.rotation = 100;
        video.runAction( new cc.Sequence( new cc.ScaleTo(0.5, 3), new cc.ScaleTo(0.5, 0.1), new cc.ScaleTo(0.5, 1), new cc.FadeOut(0.5), new cc.FadeIn(0.5), new cc.CallFunc(function(obj) {
            obj.rotation = 0;
        }, this) ) );

        return true;
    }
});

var csVideoTestScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new csVideoTestLayer();
        this.addChild(layer);
    }
});
<commit_msg>Delete csVideoTest.js<commit_after><|endoftext|>


<commit_before>(function() {
    var app = angular.module('itineraryApp', ['ngAutocomplete']); // initialize app

    app.controller('autocompCtrl', function ($scope) {
        // see http://plnkr.co/edit/il2J8qOI2Dr7Ik1KHRm8?p=preview
        // for good examples
        $scope.result = '';
        $scope.options = {};
        $scope.details = '';
        $scope.watchForm = function () {
            return $scope.form
        };
        $scope.$watch($scope.watchForm, function () {
            $scope.checkForm()
        }, true);

        $scope.checkForm = function() {
            $scope.options = {};
        };
    });
})();
<commit_msg>Use bounding on autocomplete results<commit_after>(function() {
    var app = angular.module('itineraryApp', ['ngAutocomplete']); // initialize app

    app.controller('autocompCtrl', function ($scope, $http) {
        // see http://plnkr.co/edit/il2J8qOI2Dr7Ik1KHRm8?p=preview
        // for good examples
        $scope.options = {};
        var zip = document.cookie;
        $http.get('http://nominatim.openstreetmap.org/search?q=' + zip +'&format=json&polygon=1&addressdetails=1').success(function(data) {
            //console.log("NGNGNGNG")
            //console.log(data);
            var bb = data[0]['boundingbox'];
            console.log(bb);
            var SW = new google.maps.LatLng(bb[1], bb[3]);
            var NE = new google.maps.LatLng(bb[0], bb[2]);
            var bounds = new google.maps.LatLngBounds(SW, NE);
            $scope.options.bounds = bounds;
            console.log('Added bounds to autocomplete');
            console.log(bounds);
        });
        $scope.result = '';
        $scope.details = '';
        $scope.watchForm = function () {
            return $scope.form
        };
        $scope.$watch($scope.watchForm, function () {
            $scope.checkForm()
        }, true);

        $scope.checkForm = function() {
            //$scope.options = {};
        };
    });
})();
<|endoftext|>


<commit_before>$(function() {
  if ($('.greeting-category').size() === 0) {
    return;
  }

  $(window).on('hashchange', function() {
    var hash = location.hash;
    var isTimetable = (hash.indexOf('#timetable/') === 0);
    var isCharacter = (hash.indexOf('#character/') === 0);

    if (!isTimetable && !isCharacter) {
      isTimetable = true;
    }

    $('#timetable').toggle(isTimetable);
    $('#timetable-tab').toggleClass('active', isTimetable);
    $('#character').toggle(isCharacter);
    $('#character-tab').toggleClass('active', isCharacter);

    var target = $('*[name="' + decodeURI(hash.substring(1)) + '"]');
    if (target.size() > 0) {
      $.scrollTo(target);
    }

    return false;
  }).triggerHandler('hashchange');

  var time = Math.floor(+new Date() / 60000) * 60000;

  var update = function() {
    $('.greeting-category').each(function() {
      var category = $(this);
      if (category.hasClass('greeting-category-deleted')) {
        return true; // continue
      }
      category.find('.greeting-group').each(function() {
        var element = $(this);
        var start = new Date(element.data('start-at'));
        var end = new Date(element.data('end-at'));
        if (time < start && !category.hasClass('greeting-category-before-the-start')) {
          $('.greeting-category-before-the-start .greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-info');
        }
        else if (time >= start && time < end && !category.hasClass('greeting-category-in-session')) {
          $('.greeting-category-in-session .greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-primary');
        }
        else if (time > end && !category.hasClass('greeting-category-after-the-end')) {
          $('.greeting-category-after-the-end .greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-success');
        }
      });
    });

    $('.greeting-category').each(function() {
      var element = $(this);
      var greetings = element.find('.greetings');
      if (greetings.children().size() > 0) {
        element.removeClass('greeting-category-empty');
      }
      else {
        element.addClass('greeting-category-empty');
      }
    });
  };

  update();

  setInterval(function() {
    var next = +new Date();
    if (next - time >= 60000) {
      time = Math.floor(next / 60000) * 60000;
      update();
    }
  }, 1000);
});
<commit_msg>ブラウザの戻るを利用した時にスクロール位置を調整しないよう変更<commit_after>$(function() {
  if ($('.greeting-category').size() === 0) {
    return;
  }

  var updateTab = function(hash) {
    var isTimetable = (hash.indexOf('#timetable/') === 0);
    var isCharacter = (hash.indexOf('#character/') === 0);

    if (!isTimetable && !isCharacter) {
      isTimetable = true;
    }

    $('#timetable').toggle(isTimetable);
    $('#timetable-tab').toggleClass('active', isTimetable);
    $('#character').toggle(isCharacter);
    $('#character-tab').toggleClass('active', isCharacter);
  };

  var hashchange = function() {
    updateTab(location.hash);
  };

  $(window).on('hashchange', hashchange).triggerHandler('hashchange');

  $('a[href^="#"]').on('click', function() {
    var hash = $(this).attr('href');

    updateTab(hash);

    $(window).off('hashchange', hashchange);
    location.hash = hash;
    $(window).on('hashchange', hashchange);

    var target = $('*[name="' + decodeURI(hash.substring(1)) + '"]');
    if (target.size() > 0) {
      $.scrollTo(target);
    }
    return false;
  });

  var time = Math.floor(+new Date() / 60000) * 60000;

  var update = function() {
    $('.greeting-category').each(function() {
      var category = $(this);
      if (category.hasClass('greeting-category-deleted')) {
        return true; // continue
      }
      category.find('.greeting-group').each(function() {
        var element = $(this);
        var start = new Date(element.data('start-at'));
        var end = new Date(element.data('end-at'));
        if (time < start && !category.hasClass('greeting-category-before-the-start')) {
          $('.greeting-category-before-the-start .greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-info');
        }
        else if (time >= start && time < end && !category.hasClass('greeting-category-in-session')) {
          $('.greeting-category-in-session .greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-primary');
        }
        else if (time > end && !category.hasClass('greeting-category-after-the-end')) {
          $('.greeting-category-after-the-end .greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-success');
        }
      });
    });

    $('.greeting-category').each(function() {
      var element = $(this);
      var greetings = element.find('.greetings');
      if (greetings.children().size() > 0) {
        element.removeClass('greeting-category-empty');
      }
      else {
        element.addClass('greeting-category-empty');
      }
    });
  };

  update();

  setInterval(function() {
    var next = +new Date();
    if (next - time >= 60000) {
      time = Math.floor(next / 60000) * 60000;
      update();
    }
  }, 1000);
});
<|endoftext|>


<commit_before>$(document).ready(function() {

    // Define Themes
    var themes = {
        "default": "//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
        "cerulean" : "//bootswatch.com/cerulean/bootstrap.min.css",
        "cosmo" : "//bootswatch.com/cosmo/bootstrap.min.css",
        "cyborg" : "//bootswatch.com/cyborg/bootstrap.min.css",
        "darkly" : "//bootswatch.com/darkly/bootstrap.min.css",
        "flatly" : "//bootswatch.com/flatly/bootstrap.min.css",
        "journal" : "//bootswatch.com/journal/bootstrap.min.css",
        "lumen" : "//bootswatch.com/lumen/bootstrap.min.css",
        "paper" : "//bootswatch.com/paper/bootstrap.min.css",
        "readable" : "//bootswatch.com/readable/bootstrap.min.css",
        "sandstone" : "//bootswatch.com/sandstone/bootstrap.min.css",
        "simplex" : "//bootswatch.com/simplex/bootstrap.min.css",
        "slate" : "//bootswatch.com/slate/bootstrap.min.css",
        "spacelab" : "//bootswatch.com/spacelab/bootstrap.min.css",
        "superhero" : "//bootswatch.com/superhero/bootstrap.min.css",
        "united" : "//bootswatch.com/united/bootstrap.min.css",
        "yeti" : "//bootswatch.com/yeti/bootstrap.min.css"
    }

    var userTheme = $.cookie('theme');
    //var userTheme = ($.cookie('theme')) ? $.cookie('theme') : 'default';

    /*
     * Data Tables
     */

    // Setup - add a text input to filtesearch footers
    $('#table-maplist tfoot th.filtersearch').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="filter '+title+'" class="form-control input-sm" />' );
    } );

    // Setup - add a dropdown to dropdownsearch footers
    $('#table-maplist tfoot th.dropdownsearch').each( function () {
        var title = $(this).text();
        $(this).html( '<select class="form-control input-sm"><option value=""></option><option value="yes">' + title + '</option><option value="no">no ' + title + '</option></select>' );
    } );

    var table = $('#table-maplist').DataTable( {
        "ajax": "./resources/data/maps.json",
        "lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
        "pageLength": 50,
        "colReorder": true,
        "stateSave": true,
        "fixedHeader": {
            "header": true,
            "headerOffset": $('#main-nav').height()
        },
        "processing": true,
        "deferRender": true,
        "language": {
            "search": "",
            "lengthMenu": "_MENU_",
            "processing": '
Processing a large file, this might take a second

'
        },
        "buttons": [
            {
                "extend": "csvHtml5",
                "text": ' CSV',
            },
            {
                "extend": "colvis",
                "postfixButtons": [ 'colvisRestore' ],
                "text": ' Columns'
            }
        ],
        "dom": "<'#table-controls'lfB>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        "columns": [
            { "data": "pk3" },
            { "data": function ( row, type, val, meta ) {
                    return (row.bsp) ? Object.keys(row.bsp).join("
") : "";
                }
            },
            { "data": "filesize" },
            { "data": "filesize" },
            { "data": "shasum" },
            { "data": "mapshot" },
            { "data": "title" },
            { "data": "author" },
            { "data": "gametypes[, ]" },
            { "data": function ( row, type, val, meta ) {
                    str = "";
                    $.each(row.gametypes, function( k, v ) {
                        str += '' + v + ' ';
                    });
                    return str;
                }
            },
            { "data": function ( row, type, val, meta ) {
                    if (Object.keys(row.bsp)) {
                        str = "";
                        $.each(row.bsp, function( key, value ) {
                            if (row.bsp[key].entities) {
                                var manyMaps = (Object.keys(row.bsp).length > 1);
                                if (manyMaps) {
                                    str += key + "
";
                                }
                                $.each(row.bsp[key].entities, function( k, v ) {
                                    str += '' + k + ' ';
                                });
                                if (manyMaps) {
                                    str += "

";
                                }
                            }
                        });
                        return str;
                    } else { return ""; }
                }
            },
            { "data": "map[, ]" },
            { "data": "radar[, ]" },
            { "data": "waypoints[, ]" },
            { "data": "license" },
            { "data": "date" }
        ],
        "columnDefs": [
            {   // pk3
                "targets": 0,
                "render": function ( data, type, full, meta ) {
                    var pk3 = data;
                    if (type === 'display' && data.length > 40) {
                        data = ''+data.substr( 0, 38 )+'...';
                    }
                    return '' + data + '';
                }
            },
            {   // bsp
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    if (data != false && data.length > 0) {
            			if (data.length > 40 && data.indexOf('
') == -1) {
                            data = ''+data.substr( 0, 38 )+'...';
        		    	}
        		    }
                    return data;
                }
            },
            {   // filesize
                "targets": 2,
                "orderData": 3,
                "render": function ( data, type, full, meta ) {
                    return(bytesToSize(data));
                }
            },
            {   // filesize (bytes)
                "targets": 3,
                "visible": false,
                "searchable": false
            },
            {   // shasum
                "targets": 4,
                "visible": false,
            },
            {   // mapshot file
                "targets": 5,
                "render": function ( data, type, full, meta ) {
                    var string = "";
                    if (data.length > 0) {
                        data.forEach(function(value, index, array) {
                            string += '';
                        });
                    }
                    return string;
                }
            },
            {   // title
                "targets": 6,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? data : "";
                }
            },
            {   // author
                "targets": 7,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? data : "";
                }
            },
            {   // gametypes (strings)
                "targets": 8,
                "visible": false
            },
            {   // gametypes
                "targets": 9,
                "type": "html"
            },
            {   // entities
                "targets": 10,
                "type": "html"
            },
            {   // map file
                "targets": 11,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {   // radar file
                "targets": 12,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                },
                "visible": false
            },
            {   // waypoints file
                "targets": 13,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                },
                "visible": false
            },
            {   // license file
                "targets": 14,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                },
                "visible": false
            },
            {
                // date
                "targets": 15,
                "render": function ( data, type, full, meta ) {
                    d = new Date(0);
                    d.setUTCSeconds(data);
                    return d.toISOString().slice(0,10);
                }
            }
        ],
        "initComplete": function( settings, json ) {
            // clear filters on page load
            $("tfoot input").val('').trigger('change');
            $("tfoot select").val('').trigger('change');
            // Hacky way to put the controls in the navbar
            $("#table-controls .btn").addClass("btn-sm");
            $("#table-maplist_length").addClass("pull-right");
            $("#table-maplist_filter").addClass("pull-right");
            $("#table-controls").detach().appendTo('#nav-table-controls');
            $("#table-controls .dt-buttons").addClass("pull-right");
            $("#table-controls").show();
            if (userTheme) {
                setTheme(userTheme);
            }
            //$('[data-toggle="tooltip"]').tooltip();
        },
        "drawCallback": function( settings ) {
            $("#table-controls").show();
            initPopovers();
        }
    } );

    // To be shown by initComplete
    $("#table-controls").hide();

    // Reorder callback
    table.on( 'column-reorder', function ( e, settings, details ) {
        initPopovers();
    });

    // Popover image previews
    function initPopovers() {
        $('a[rel=popover]').popover({
            html: true,
            trigger: 'hover',
            content: function () {
                return '';
            }
        });
    }

    // Apply filtersearch and dropdownsearch
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );

        $( 'select', this.footer() ).on( 'change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );

    } );

    /*
     * Charts
     */

    var chartsDrawn = false;
    var allCharts = [];

    function drawCharts(data) {
        $("#charts").show();

        // Pie
        allCharts[0] = c3.generate(data.mapinfos);
        allCharts[1] = c3.generate(data.mapshots);
        allCharts[2] = c3.generate(data.maps);
        allCharts[3] = c3.generate(data.radars);
        allCharts[4] = c3.generate(data.waypoints);
        allCharts[5] = c3.generate(data.licenses);

        // Bar Chart
        var filesizes = {
            tooltip: {
                format: {
                    title: function (x) { return; },
                    name: function (name, ratio, id, index) { return "map count"; },
                    value: function (value, ratio, id, index) { return value; }
                }
            }
        };

        $.extend(filesizes, data.filesizes);
        allCharts[6] = c3.generate(filesizes);

        // Line
        allCharts[7] = c3.generate(data.mapsbyyear);

        // Donut
        allCharts[8] = c3.generate(data.gametypes);
        allCharts[9] = c3.generate(data.shacount);

        // Stacked Area
        allCharts[10] = c3.generate(data.filesbyyear);

        // Donut
        allCharts[11] = c3.generate(data.entityappearance);

        // Donut
        allCharts[12] = c3.generate(data.entitycount);

        $("#loading-charts").hide();
    }

    function hideCharts() {
/*        allCharts.forEach(function(value, index, array) {
            value.hide();
        });
*/
    }

    function showCharts() {
        $("#loading-charts").hide();
        $("#charts").show();
        /*allCharts.forEach(function(value, index, array) {
            value.show();
        });*/
    }

    // Need to hide datatables when changing tabs for fixedHeader
    var visible = true;
    var tableContainer = $(table.table().container());

    // Bootstrap tab shown event
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

        var currentTab = $(".nav li.active a").attr("href");

        switch(currentTab) {

            case "#maplist":

                visible = false;

                 break;

            case "#statistics":

                $("#charts").hide();
                $("#loading-charts").show();

                if (!chartsDrawn) {
                    $.get('./resources/data/charts.json', function(data) {
                        drawCharts(data);
                        chartsDrawn = true;
                    });
                } else {
                    showCharts();
                }

            case "#about":

            default:

                visible = false

        }

        table.fixedHeader.adjust();

        // decide whether to show the table or not
        if (visible) { // hide table
            $("#nav-table-controls").hide();
            tableContainer.css('display', 'none');
        } else { // show table
            $("#nav-table-controls").show();
            tableContainer.css('display', 'block');
            hideCharts();
        }

    });

    /*
     * Theme Switcher
     */

    function themeSwitcher() {

        // Setup menu

        var themeMenu = '

' +
        '' +
            'Theme ' +
            '' +
        '' +
        '

' +
    '

';

        $('.navbar-right').append(themeMenu);

        $.each(themes, function(index, value) {
            var title = index.charAt(0).toUpperCase() + index.substr(1);
            $('#theme-switcher').append('
' + title + '
');
        });

        $('#theme-switcher li a').click(function() {
            var theme = $(this).attr('data-theme');
            setTheme(theme);
        });

    }

    function setTheme(theme) {
        var themeurl = themes[theme];
        $.cookie('theme', theme)
        $('#theme-switcher li').removeClass('active');
        $('#theme').attr('href', themeurl);
        $('#theme-custom').attr('href', './static/css/themes/' + theme + '/custom.css');
        $('#theme-switcher li a[data-theme=' + theme + ']').parent().addClass('active');
        $('#theme-switcher-wrapper span').text('Theme: ' + theme);
//        table.fixedHeader.adjust();
    }

    new Konami(function() { themeSwitcher(); } );

} );

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

<commit_msg>reset button<commit_after>$(document).ready(function() {

    // Define Themes
    var themes = {
        "default": "//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
        "cerulean" : "//bootswatch.com/cerulean/bootstrap.min.css",
        "cosmo" : "//bootswatch.com/cosmo/bootstrap.min.css",
        "cyborg" : "//bootswatch.com/cyborg/bootstrap.min.css",
        "darkly" : "//bootswatch.com/darkly/bootstrap.min.css",
        "flatly" : "//bootswatch.com/flatly/bootstrap.min.css",
        "journal" : "//bootswatch.com/journal/bootstrap.min.css",
        "lumen" : "//bootswatch.com/lumen/bootstrap.min.css",
        "paper" : "//bootswatch.com/paper/bootstrap.min.css",
        "readable" : "//bootswatch.com/readable/bootstrap.min.css",
        "sandstone" : "//bootswatch.com/sandstone/bootstrap.min.css",
        "simplex" : "//bootswatch.com/simplex/bootstrap.min.css",
        "slate" : "//bootswatch.com/slate/bootstrap.min.css",
        "spacelab" : "//bootswatch.com/spacelab/bootstrap.min.css",
        "superhero" : "//bootswatch.com/superhero/bootstrap.min.css",
        "united" : "//bootswatch.com/united/bootstrap.min.css",
        "yeti" : "//bootswatch.com/yeti/bootstrap.min.css"
    }

    var userTheme = $.cookie('theme');
    //var userTheme = ($.cookie('theme')) ? $.cookie('theme') : 'default';

    /*
     * Data Tables
     */

    // Setup - add a text input to filtesearch footers
    $('#table-maplist tfoot th.filtersearch').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="filter '+title+'" class="form-control input-sm" />' );
    } );

    // Setup - add a dropdown to dropdownsearch footers
    $('#table-maplist tfoot th.dropdownsearch').each( function () {
        var title = $(this).text();
        $(this).html( '<select class="form-control input-sm"><option value=""></option><option value="yes">' + title + '</option><option value="no">no ' + title + '</option></select>' );
    } );

    var table = $('#table-maplist').DataTable( {
        "ajax": "./resources/data/maps.json",
        "lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
        "pageLength": 50,
        "colReorder": true,
        "stateSave": true,
        "fixedHeader": {
            "header": true,
            "headerOffset": $('#main-nav').height()
        },
        "processing": true,
        "deferRender": true,
        "language": {
            "search": "",
            "lengthMenu": "_MENU_",
            "processing": '
Processing a large file, this might take a second

'
        },
        "buttons": [
            {
                "extend": "csvHtml5",
                "text": ' CSV',
            },
            {
                "extend": "colvis",
                "postfixButtons": [ 'colvisRestore' ],
                "text": ' Columns'
            },
            {
                "text": ' Reset',
                "action": function ( e, dt, node, config ) {
                    dt.state.clear();
                    window.location.reload();
                }
            }
        ],
        "dom": "<'#table-controls'lfB>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        "columns": [
            { "data": "pk3" },
            { "data": function ( row, type, val, meta ) {
                    return (row.bsp) ? Object.keys(row.bsp).join("
") : "";
                }
            },
            { "data": "filesize" },
            { "data": "filesize" },
            { "data": "shasum" },
            { "data": "mapshot" },
            { "data": "title" },
            { "data": "author" },
            { "data": "gametypes[, ]" },
            { "data": function ( row, type, val, meta ) {
                    str = "";
                    $.each(row.gametypes, function( k, v ) {
                        str += '' + v + ' ';
                    });
                    return str;
                }
            },
            { "data": function ( row, type, val, meta ) {
                    if (Object.keys(row.bsp)) {
                        str = "";
                        $.each(row.bsp, function( key, value ) {
                            if (row.bsp[key].entities) {
                                var manyMaps = (Object.keys(row.bsp).length > 1);
                                if (manyMaps) {
                                    str += key + "
";
                                }
                                $.each(row.bsp[key].entities, function( k, v ) {
                                    str += '' + k + ' ';
                                });
                                if (manyMaps) {
                                    str += "

";
                                }
                            }
                        });
                        return str;
                    } else { return ""; }
                }
            },
            { "data": "map[, ]" },
            { "data": "radar[, ]" },
            { "data": "waypoints[, ]" },
            { "data": "license" },
            { "data": "date" }
        ],
        "columnDefs": [
            {   // pk3
                "targets": 0,
                "render": function ( data, type, full, meta ) {
                    var pk3 = data;
                    if (type === 'display' && data.length > 40) {
                        data = ''+data.substr( 0, 38 )+'...';
                    }
                    return '' + data + '';
                }
            },
            {   // bsp
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    if (data != false && data.length > 0) {
            			if (data.length > 40 && data.indexOf('
') == -1) {
                            data = ''+data.substr( 0, 38 )+'...';
        		    	}
        		    }
                    return data;
                }
            },
            {   // filesize
                "targets": 2,
                "orderData": 3,
                "render": function ( data, type, full, meta ) {
                    return(bytesToSize(data));
                }
            },
            {   // filesize (bytes)
                "targets": 3,
                "visible": false,
                "searchable": false
            },
            {   // shasum
                "targets": 4,
                "visible": false,
            },
            {   // mapshot file
                "targets": 5,
                "render": function ( data, type, full, meta ) {
                    var string = "";
                    if (data.length > 0) {
                        data.forEach(function(value, index, array) {
                            string += '';
                        });
                    }
                    return string;
                }
            },
            {   // title
                "targets": 6,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? data : "";
                }
            },
            {   // author
                "targets": 7,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? data : "";
                }
            },
            {   // gametypes (strings)
                "targets": 8,
                "visible": false
            },
            {   // gametypes
                "targets": 9,
                "type": "html"
            },
            {   // entities
                "targets": 10,
                "type": "html"
            },
            {   // map file
                "targets": 11,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {   // radar file
                "targets": 12,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                },
                "visible": false
            },
            {   // waypoints file
                "targets": 13,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                },
                "visible": false
            },
            {   // license file
                "targets": 14,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                },
                "visible": false
            },
            {
                // date
                "targets": 15,
                "render": function ( data, type, full, meta ) {
                    d = new Date(0);
                    d.setUTCSeconds(data);
                    return d.toISOString().slice(0,10);
                }
            }
        ],
        "initComplete": function( settings, json ) {
            // clear filters on page load
            $("tfoot input").val('').trigger('change');
            $("tfoot select").val('').trigger('change');
            // Hacky way to put the controls in the navbar
            $("#table-controls .btn").addClass("btn-sm");
            $("#table-maplist_length").addClass("pull-right");
            $("#table-maplist_filter").addClass("pull-right");
            $("#table-controls").detach().appendTo('#nav-table-controls');
            $("#table-controls .dt-buttons").addClass("pull-right");
            $("#table-controls").show();
            if (userTheme) {
                setTheme(userTheme);
            }
            //$('[data-toggle="tooltip"]').tooltip();
        },
        "drawCallback": function( settings ) {
            $("#table-controls").show();
            initPopovers();
        }
    } );

    // To be shown by initComplete
    $("#table-controls").hide();

    // Reorder callback
    table.on( 'column-reorder', function ( e, settings, details ) {
        initPopovers();
    });

    // Popover image previews
    function initPopovers() {
        $('a[rel=popover]').popover({
            html: true,
            trigger: 'hover',
            content: function () {
                return '';
            }
        });
    }

    // Apply filtersearch and dropdownsearch
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );

        $( 'select', this.footer() ).on( 'change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );

    } );

    /*
     * Charts
     */

    var chartsDrawn = false;
    var allCharts = [];

    function drawCharts(data) {
        $("#charts").show();

        // Pie
        allCharts[0] = c3.generate(data.mapinfos);
        allCharts[1] = c3.generate(data.mapshots);
        allCharts[2] = c3.generate(data.maps);
        allCharts[3] = c3.generate(data.radars);
        allCharts[4] = c3.generate(data.waypoints);
        allCharts[5] = c3.generate(data.licenses);

        // Bar Chart
        var filesizes = {
            tooltip: {
                format: {
                    title: function (x) { return; },
                    name: function (name, ratio, id, index) { return "map count"; },
                    value: function (value, ratio, id, index) { return value; }
                }
            }
        };

        $.extend(filesizes, data.filesizes);
        allCharts[6] = c3.generate(filesizes);

        // Line
        allCharts[7] = c3.generate(data.mapsbyyear);

        // Donut
        allCharts[8] = c3.generate(data.gametypes);
        allCharts[9] = c3.generate(data.shacount);

        // Stacked Area
        allCharts[10] = c3.generate(data.filesbyyear);

        // Donut
        allCharts[11] = c3.generate(data.entityappearance);

        // Donut
        allCharts[12] = c3.generate(data.entitycount);

        $("#loading-charts").hide();
    }

    function hideCharts() {
/*        allCharts.forEach(function(value, index, array) {
            value.hide();
        });
*/
    }

    function showCharts() {
        $("#loading-charts").hide();
        $("#charts").show();
        /*allCharts.forEach(function(value, index, array) {
            value.show();
        });*/
    }

    // Need to hide datatables when changing tabs for fixedHeader
    var visible = true;
    var tableContainer = $(table.table().container());

    // Bootstrap tab shown event
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

        var currentTab = $(".nav li.active a").attr("href");

        switch(currentTab) {

            case "#maplist":

                visible = false;

                 break;

            case "#statistics":

                $("#charts").hide();
                $("#loading-charts").show();

                if (!chartsDrawn) {
                    $.get('./resources/data/charts.json', function(data) {
                        drawCharts(data);
                        chartsDrawn = true;
                    });
                } else {
                    showCharts();
                }

            case "#about":

            default:

                visible = false

        }

        table.fixedHeader.adjust();

        // decide whether to show the table or not
        if (visible) { // hide table
            $("#nav-table-controls").hide();
            tableContainer.css('display', 'none');
        } else { // show table
            $("#nav-table-controls").show();
            tableContainer.css('display', 'block');
            hideCharts();
        }

    });

    /*
     * Theme Switcher
     */

    function themeSwitcher() {

        // Setup menu

        var themeMenu = '

' +
        '' +
            'Theme ' +
            '' +
        '' +
        '

' +
    '

';

        $('.navbar-right').append(themeMenu);

        $.each(themes, function(index, value) {
            var title = index.charAt(0).toUpperCase() + index.substr(1);
            $('#theme-switcher').append('
' + title + '
');
        });

        $('#theme-switcher li a').click(function() {
            var theme = $(this).attr('data-theme');
            setTheme(theme);
        });

    }

    function setTheme(theme) {
        var themeurl = themes[theme];
        $.cookie('theme', theme)
        $('#theme-switcher li').removeClass('active');
        $('#theme').attr('href', themeurl);
        $('#theme-custom').attr('href', './static/css/themes/' + theme + '/custom.css');
        $('#theme-switcher li a[data-theme=' + theme + ']').parent().addClass('active');
        $('#theme-switcher-wrapper span').text('Theme: ' + theme);
//        table.fixedHeader.adjust();
    }

    new Konami(function() { themeSwitcher(); } );

} );

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

<|endoftext|>


<commit_before>import { test } from 'ava'

import { execSync } from 'child_process'
import sinon from 'sinon'

import { log } from '../'

const docker = !!process.env.WECHATY_DOCKER

!docker && test('Docker test skipped', function(t) {
    t.pass('not in docker, skip docker tests')
})

docker && test('Docker smoking test', function(t) {
  const n = execSync('ps | grep Xvfb | wc -l')
  t.is(n, 1, 'should has Xvfb started')
})
<commit_msg>fix docker xvfb ps<commit_after>import { test } from 'ava'

import { execSync } from 'child_process'
import sinon from 'sinon'

import { log } from '../'

const docker = !!process.env.WECHATY_DOCKER

!docker && test('Docker test skipped', function(t) {
  t.pass('not in docker, skip docker tests')
})

docker && test('Docker smoking test', function(t) {
  const n = execSync('ps a | grep Xvfb | grep -v grep | wc -l').toString().replace(/\n/, '', 'g')
  t.is(parseInt(n), 1, 'should has Xvfb started')
})
<|endoftext|>


<commit_before>$(document).ready(function() {
  add_inline_editing();
  $('#issue-form').bind('submit', function(e){
    var next_status_id = $('#issue_status_id').val();
    if ((next_status_id != current_status_id) &&
        ($.inArray(parseInt(next_status_id), window.issue_workflow_list) != -1) &&
        $('#has_resources').val() == '0') {
      alert('You need to add estimation before moving to this status.');
      $('#estimation').focus();
      e.preventDefault();
      $(e.target).removeAttr('data-submitted');
      return false;
    }
  });
  window.current_status_id = $('#issue_status_id').val();
});

function add_inline_editing() {
  $('.resource_estimation_editable').each(function(element) {
    var $editable_element = $(this);
    var id = $editable_element.data('resource-id');
    $editable_element.editable('/issue_resources/' + id, {
        onblur : 'submit',
        method : 'PUT',
        ajaxoptions : {type : 'PUT'},
        name : 'issue_resource[estimation]',
        tooltip   : "Click to edit...",
        'event' : 'editable'
    });
    $('#cell-' + id).live('click', function() {
      $editable_element.trigger('editable');
      $('input', $editable_element).trigger('focus').trigger('select');

    })
  });
}
<commit_msg>set submit button as disabled when saving resources<commit_after>$(document).ready(function() {
  add_inline_editing();
  $('#issue-form').bind('submit', function(e){
    var next_status_id = $('#issue_status_id').val();
    if ((next_status_id != current_status_id) &&
        ($.inArray(parseInt(next_status_id), window.issue_workflow_list) != -1) &&
        $('#has_resources').val() == '0') {
      alert('You need to add estimation before moving to this status.');
      $('#estimation').focus();
      e.preventDefault();
      $(e.target).removeAttr('data-submitted');
      return false;
    }
  });

  $('#new_issue_resource').bind('submit', function() {
    $('input.button', $(this)).attr('disabled', true);
    return true;
  });

  window.current_status_id = $('#issue_status_id').val();
});

function add_inline_editing() {
  $('.resource_estimation_editable').each(function(element) {
    var $editable_element = $(this);
    var id = $editable_element.data('resource-id');
    $editable_element.editable('/issue_resources/' + id, {
        onblur : 'submit',
        method : 'PUT',
        ajaxoptions : {type : 'PUT'},
        name : 'issue_resource[estimation]',
        tooltip   : "Click to edit...",
        'event' : 'editable'
    });
    $('#cell-' + id).live('click', function() {
      $editable_element.trigger('editable');
      $('input', $editable_element).trigger('focus').trigger('select');

    })
  });
}
<|endoftext|>