<commit_before>var path = require('path');
var fs = require('fs');

var falafel = require('falafel');
var glob = require('glob');
var madge = require('madge');
var readLastLines = require('read-last-lines');
var eslint = require('eslint');
var trueCasePath = require('true-case-path');

var constants = require('./util/constants');
var srcGlob = path.join(constants.pathToSrc, '**/*.js');
var libGlob = path.join(constants.pathToLib, '**/*.js');
var testGlob = path.join(constants.pathToJasmineTests, '**/*.js');
var bundleTestGlob = path.join(constants.pathToJasmineBundleTests, '**/*.js');

var EXIT_CODE = 0;

// main
assertJasmineSuites();
assertSrcContents();
assertFileNames();
assertTrailingNewLine();
assertCircularDeps();
assertES5();

// check for for focus and exclude jasmine blocks
function assertJasmineSuites() {
    var BLACK_LIST = ['fdescribe', 'fit', 'xdescribe', 'xit'];
    var logs = [];

    glob(combineGlobs([testGlob, bundleTestGlob]), function(err, files) {
        files.forEach(function(file) {
            var code = fs.readFileSync(file, 'utf-8');

            falafel(code, {locations: true}, function(node) {
                if(node.type === 'Identifier' && BLACK_LIST.indexOf(node.name) !== -1) {
                    logs.push([
                        path.basename(file),
                        '[line ' + node.loc.start.line + '] :',
                        'contains either a *fdescribe*, *fit*,',
                        '*xdescribe* or *xit* block.'
                    ].join(' '));
                }
            });

        });

        log('no jasmine suites focus/exclude blocks', logs);
    });
}

/*
 * tests about the contents of source (and lib) files:
 * - check for header comment
 * - check that we don't have any features that break in IE
 * - check that we don't use getComputedStyle unexpectedly
 * - check that require statements use lowercase (to match assertFileNames)
 *   or match the case of the source file
 */
function assertSrcContents() {
    var licenseSrc = constants.licenseSrc;
    var licenseStr = licenseSrc.substring(2, licenseSrc.length - 2);
    var logs = [];

    // These are forbidden in IE *only in SVG* but since
    // that's 99% of what we do here, we'll forbid them entirely
    // until there's some HTML use case where we need them.
    // (not sure what we'd do then, but we'd think of something!)
    var IE_SVG_BLACK_LIST = ['innerHTML', 'parentElement', 'children'];

    // Forbidden in IE in any context
    var IE_BLACK_LIST = ['classList'];

    // require'd built-in modules
    var BUILTINS = ['events'];

    var getComputedStyleCnt = 0;

    glob(combineGlobs([srcGlob, libGlob]), function(err, files) {
        files.forEach(function(file) {
            var code = fs.readFileSync(file, 'utf-8');

            // parse through code string while keeping track of comments
            var comments = [];
            falafel(code, {onComment: comments, locations: true}, function(node) {
                // look for .classList
                if(node.type === 'MemberExpression') {
                    var source = node.source();
                    var parts = source.split('.');
                    var lastPart = parts[parts.length - 1];

                    if(source === 'Math.sign') {
                        logs.push(file + ' : contains Math.sign (IE failure)');
                    }
                    else if(source === 'window.getComputedStyle') {
                        getComputedStyleCnt++;
                    }
                    else if(IE_BLACK_LIST.indexOf(lastPart) !== -1) {
                        logs.push(file + ' : contains .' + lastPart + ' (IE failure)');
                    }
                    else if(IE_SVG_BLACK_LIST.indexOf(lastPart) !== -1) {
                        logs.push(file + ' : contains .' + lastPart + ' (IE failure in SVG)');
                    }
                }
                else if(node.type === 'Identifier' && node.source() === 'getComputedStyle') {
                    if(node.parent.source() !== 'window.getComputedStyle') {
                        logs.push(file + ' : getComputedStyle must be called as a `window` property.');
                    }
                }
                else if(node.type === 'CallExpression' && node.callee.name === 'require') {
                    var pathNode = node.arguments[0];
                    var pathStr = pathNode.value;
                    if(pathNode.type !== 'Literal') {
                        logs.push(file + ' : You may only `require` literals.');
                    }
                    else if(BUILTINS.indexOf(pathStr) === -1) {
                        // node version 8.9.0+ can use require.resolve(request, {paths: [...]})
                        // and avoid this explicit conversion to the current location
                        if(pathStr.charAt(0) === '.') {
                            pathStr = path.relative(__dirname, path.join(path.dirname(file), pathStr));
                        }
                        var fullPath = require.resolve(pathStr);
                        var casedPath = trueCasePath(fullPath);

                        if(fullPath !== trueCasePath(fullPath)) {
                            logs.push(file + ' : `require` path is not case-correct:\n' +
                                fullPath + ' -> ' + casedPath);
                        }
                    }
                }
            });

            var header = comments[0];

            if(!header || header.loc.start.line > 1) {
                logs.push(file + ' : has no header information.');
                return;
            }

            if(header.value !== licenseStr) {
                logs.push(file + ' : has incorrect header information.');
            }
        });

        /*
         * window.getComputedStyle calls are restricted, so we want to be
         * explicit about it whenever we add or remove these calls. This is
         * the reason d3.selection.style is forbidden as a getter.
         *
         * The rule is:
         * - You MAY NOT call getComputedStyle during rendering a plot, EXCEPT
         *   in calculating autosize for the plot (which only makes sense if
         *   the plot is displayed). Other uses of getComputedStyle while
         *   rendering will fail, at least in Chrome, if the plot div is not
         *   attached to the DOM.
         *
         * - You MAY call getComputedStyle during interactions (hover etc)
         *   because at that point it's known that the plot is displayed.
         *
         * - You must use the explicit `window.getComputedStyle` rather than
         *   the implicit global scope `getComputedStyle` for jsdom compat.
         *
         * - If you use conforms to these rules, you may update
         *   KNOWN_GET_COMPUTED_STYLE_CALLS to count the new use.
         */
        var KNOWN_GET_COMPUTED_STYLE_CALLS = 5;
        if(getComputedStyleCnt !== KNOWN_GET_COMPUTED_STYLE_CALLS) {
            logs.push('Expected ' + KNOWN_GET_COMPUTED_STYLE_CALLS +
                ' window.getComputedStyle calls, found ' + getComputedStyleCnt +
                '. See ' + __filename + ' for details how to proceed.');
        }

        log('correct headers and contents in lib/ and src/', logs);
    });
}

// check that all file names are in lower case
function assertFileNames() {
    var pattern = combineGlobs([
        path.join(constants.pathToRoot, '*.*'),
        path.join(constants.pathToSrc, '**/*.*'),
        path.join(constants.pathToLib, '**/*.*'),
        path.join(constants.pathToDist, '**/*.*'),
        path.join(constants.pathToRoot, 'test', '**/*.*'),
        path.join(constants.pathToRoot, 'tasks', '**/*.*'),
        path.join(constants.pathToRoot, 'devtools', '**/*.*')
    ]);

    var logs = [];

    glob(pattern, function(err, files) {
        files.forEach(function(file) {
            var base = path.basename(file);

            if(
                base === 'README.md' ||
                base === 'CONTRIBUTING.md' ||
                base === 'CHANGELOG.md' ||
                base === 'SECURITY.md' ||
                file.indexOf('mathjax') !== -1
            ) return;

            if(base !== base.toLowerCase()) {
                logs.push([
                    file, ':',
                    'has a file name containing some',
                    'non-lower-case characters'
                ].join(' '));
            }
        });

        log('lower case only file names', logs);
    });
}

// check that all files have a trailing new line character
function assertTrailingNewLine() {
    var pattern = combineGlobs([
        path.join(constants.pathToSrc, '**/*.glsl'),
        path.join(constants.pathToRoot, 'test', 'image', 'mocks', '*')
    ]);

    var regexNewLine = /\r?\n$/;
    var regexEmptyNewLine = /^\r?\n$/;
    var promises = [];
    var logs = [];

    glob(pattern, function(err, files) {
        files.forEach(function(file) {
            var promise = readLastLines.read(file, 1);

            promises.push(promise);

            promise.then(function(lines) {
                if(!regexNewLine.test(lines)) {
                    logs.push([
                        file, ':',
                        'does not have a trailing new line character'
                    ].join(' '));
                } else if(regexEmptyNewLine.test(lines)) {
                    logs.push([
                        file, ':',
                        'has more than one trailing new line'
                    ].join(' '));
                }
            });
        });

        Promise.all(promises).then(function() {
            log('trailing new line character', logs);
        });
    });
}

// check circular dependencies
function assertCircularDeps() {
    madge(constants.pathToSrc).then(function(res) {
        var circularDeps = res.circular();
        var logs = [];

        if(circularDeps.length) {
            console.log(circularDeps.join('\n'));
            logs.push('some circular dependencies were found in src/');
        }

        log('circular dependencies: ' + circularDeps.length, logs);
    });
}

// Ensure no ES6 has snuck through into the build:
function assertES5() {
    var CLIEngine = eslint.CLIEngine;

    var cli = new CLIEngine({
        useEslintrc: false,
        ignore: false,
        parserOptions: {
            ecmaVersion: 5
        }
    });

    var files = constants.partialBundlePaths.map(function(f) { return f.dist; });
    files.unshift(constants.pathToPlotlyDist);

    var report = cli.executeOnFiles(files);
    var formatter = cli.getFormatter();

    var errors = [];
    if(report.errorCount > 0) {
        console.log(formatter(report.results));

        // It doesn't work well to pass formatted logs into this,
        // so instead pass the empty string in a way that causes
        // the test to fail
        errors.push('');
    }

    log('es5-only syntax', errors);
}

function combineGlobs(arr) {
    return '{' + arr.join(',') + '}';
}

function log(name, logs) {
    if(logs.length) {
        console.error('test-syntax error [' + name + ']');
        console.error(logs.join('\n'));
        EXIT_CODE = 1;
    } else {
        console.log('ok ' + name);
    }
}

process.on('exit', function() {
    if(EXIT_CODE) {
        throw new Error('test syntax failed.');
    }
});
<commit_msg>test for non-es5 tokens in build/plotly.js<commit_after>var path = require('path');
var fs = require('fs');

var falafel = require('falafel');
var glob = require('glob');
var madge = require('madge');
var readLastLines = require('read-last-lines');
var eslint = require('eslint');
var trueCasePath = require('true-case-path');

var constants = require('./util/constants');
var srcGlob = path.join(constants.pathToSrc, '**/*.js');
var libGlob = path.join(constants.pathToLib, '**/*.js');
var testGlob = path.join(constants.pathToJasmineTests, '**/*.js');
var bundleTestGlob = path.join(constants.pathToJasmineBundleTests, '**/*.js');

var EXIT_CODE = 0;

// main
assertJasmineSuites();
assertSrcContents();
assertFileNames();
assertTrailingNewLine();
assertCircularDeps();
assertES5();

// check for for focus and exclude jasmine blocks
function assertJasmineSuites() {
    var BLACK_LIST = ['fdescribe', 'fit', 'xdescribe', 'xit'];
    var logs = [];

    glob(combineGlobs([testGlob, bundleTestGlob]), function(err, files) {
        files.forEach(function(file) {
            var code = fs.readFileSync(file, 'utf-8');

            falafel(code, {locations: true}, function(node) {
                if(node.type === 'Identifier' && BLACK_LIST.indexOf(node.name) !== -1) {
                    logs.push([
                        path.basename(file),
                        '[line ' + node.loc.start.line + '] :',
                        'contains either a *fdescribe*, *fit*,',
                        '*xdescribe* or *xit* block.'
                    ].join(' '));
                }
            });

        });

        log('no jasmine suites focus/exclude blocks', logs);
    });
}

/*
 * tests about the contents of source (and lib) files:
 * - check for header comment
 * - check that we don't have any features that break in IE
 * - check that we don't use getComputedStyle unexpectedly
 * - check that require statements use lowercase (to match assertFileNames)
 *   or match the case of the source file
 */
function assertSrcContents() {
    var licenseSrc = constants.licenseSrc;
    var licenseStr = licenseSrc.substring(2, licenseSrc.length - 2);
    var logs = [];

    // These are forbidden in IE *only in SVG* but since
    // that's 99% of what we do here, we'll forbid them entirely
    // until there's some HTML use case where we need them.
    // (not sure what we'd do then, but we'd think of something!)
    var IE_SVG_BLACK_LIST = ['innerHTML', 'parentElement', 'children'];

    // Forbidden in IE in any context
    var IE_BLACK_LIST = ['classList'];

    // require'd built-in modules
    var BUILTINS = ['events'];

    var getComputedStyleCnt = 0;

    glob(combineGlobs([srcGlob, libGlob]), function(err, files) {
        files.forEach(function(file) {
            var code = fs.readFileSync(file, 'utf-8');

            // parse through code string while keeping track of comments
            var comments = [];
            falafel(code, {onComment: comments, locations: true}, function(node) {
                // look for .classList
                if(node.type === 'MemberExpression') {
                    var source = node.source();
                    var parts = source.split('.');
                    var lastPart = parts[parts.length - 1];

                    if(source === 'Math.sign') {
                        logs.push(file + ' : contains Math.sign (IE failure)');
                    }
                    else if(source === 'window.getComputedStyle') {
                        getComputedStyleCnt++;
                    }
                    else if(IE_BLACK_LIST.indexOf(lastPart) !== -1) {
                        logs.push(file + ' : contains .' + lastPart + ' (IE failure)');
                    }
                    else if(IE_SVG_BLACK_LIST.indexOf(lastPart) !== -1) {
                        logs.push(file + ' : contains .' + lastPart + ' (IE failure in SVG)');
                    }
                }
                else if(node.type === 'Identifier' && node.source() === 'getComputedStyle') {
                    if(node.parent.source() !== 'window.getComputedStyle') {
                        logs.push(file + ' : getComputedStyle must be called as a `window` property.');
                    }
                }
                else if(node.type === 'CallExpression' && node.callee.name === 'require') {
                    var pathNode = node.arguments[0];
                    var pathStr = pathNode.value;
                    if(pathNode.type !== 'Literal') {
                        logs.push(file + ' : You may only `require` literals.');
                    }
                    else if(BUILTINS.indexOf(pathStr) === -1) {
                        // node version 8.9.0+ can use require.resolve(request, {paths: [...]})
                        // and avoid this explicit conversion to the current location
                        if(pathStr.charAt(0) === '.') {
                            pathStr = path.relative(__dirname, path.join(path.dirname(file), pathStr));
                        }
                        var fullPath = require.resolve(pathStr);
                        var casedPath = trueCasePath(fullPath);

                        if(fullPath !== trueCasePath(fullPath)) {
                            logs.push(file + ' : `require` path is not case-correct:\n' +
                                fullPath + ' -> ' + casedPath);
                        }
                    }
                }
            });

            var header = comments[0];

            if(!header || header.loc.start.line > 1) {
                logs.push(file + ' : has no header information.');
                return;
            }

            if(header.value !== licenseStr) {
                logs.push(file + ' : has incorrect header information.');
            }
        });

        /*
         * window.getComputedStyle calls are restricted, so we want to be
         * explicit about it whenever we add or remove these calls. This is
         * the reason d3.selection.style is forbidden as a getter.
         *
         * The rule is:
         * - You MAY NOT call getComputedStyle during rendering a plot, EXCEPT
         *   in calculating autosize for the plot (which only makes sense if
         *   the plot is displayed). Other uses of getComputedStyle while
         *   rendering will fail, at least in Chrome, if the plot div is not
         *   attached to the DOM.
         *
         * - You MAY call getComputedStyle during interactions (hover etc)
         *   because at that point it's known that the plot is displayed.
         *
         * - You must use the explicit `window.getComputedStyle` rather than
         *   the implicit global scope `getComputedStyle` for jsdom compat.
         *
         * - If you use conforms to these rules, you may update
         *   KNOWN_GET_COMPUTED_STYLE_CALLS to count the new use.
         */
        var KNOWN_GET_COMPUTED_STYLE_CALLS = 5;
        if(getComputedStyleCnt !== KNOWN_GET_COMPUTED_STYLE_CALLS) {
            logs.push('Expected ' + KNOWN_GET_COMPUTED_STYLE_CALLS +
                ' window.getComputedStyle calls, found ' + getComputedStyleCnt +
                '. See ' + __filename + ' for details how to proceed.');
        }

        log('correct headers and contents in lib/ and src/', logs);
    });
}

// check that all file names are in lower case
function assertFileNames() {
    var pattern = combineGlobs([
        path.join(constants.pathToRoot, '*.*'),
        path.join(constants.pathToSrc, '**/*.*'),
        path.join(constants.pathToLib, '**/*.*'),
        path.join(constants.pathToDist, '**/*.*'),
        path.join(constants.pathToRoot, 'test', '**/*.*'),
        path.join(constants.pathToRoot, 'tasks', '**/*.*'),
        path.join(constants.pathToRoot, 'devtools', '**/*.*')
    ]);

    var logs = [];

    glob(pattern, function(err, files) {
        files.forEach(function(file) {
            var base = path.basename(file);

            if(
                base === 'README.md' ||
                base === 'CONTRIBUTING.md' ||
                base === 'CHANGELOG.md' ||
                base === 'SECURITY.md' ||
                file.indexOf('mathjax') !== -1
            ) return;

            if(base !== base.toLowerCase()) {
                logs.push([
                    file, ':',
                    'has a file name containing some',
                    'non-lower-case characters'
                ].join(' '));
            }
        });

        log('lower case only file names', logs);
    });
}

// check that all files have a trailing new line character
function assertTrailingNewLine() {
    var pattern = combineGlobs([
        path.join(constants.pathToSrc, '**/*.glsl'),
        path.join(constants.pathToRoot, 'test', 'image', 'mocks', '*')
    ]);

    var regexNewLine = /\r?\n$/;
    var regexEmptyNewLine = /^\r?\n$/;
    var promises = [];
    var logs = [];

    glob(pattern, function(err, files) {
        files.forEach(function(file) {
            var promise = readLastLines.read(file, 1);

            promises.push(promise);

            promise.then(function(lines) {
                if(!regexNewLine.test(lines)) {
                    logs.push([
                        file, ':',
                        'does not have a trailing new line character'
                    ].join(' '));
                } else if(regexEmptyNewLine.test(lines)) {
                    logs.push([
                        file, ':',
                        'has more than one trailing new line'
                    ].join(' '));
                }
            });
        });

        Promise.all(promises).then(function() {
            log('trailing new line character', logs);
        });
    });
}

// check circular dependencies
function assertCircularDeps() {
    madge(constants.pathToSrc).then(function(res) {
        var circularDeps = res.circular();
        var logs = [];

        if(circularDeps.length) {
            console.log(circularDeps.join('\n'));
            logs.push('some circular dependencies were found in src/');
        }

        log('circular dependencies: ' + circularDeps.length, logs);
    });
}

// Ensure no ES6 has snuck through into the build:
function assertES5() {
    var CLIEngine = eslint.CLIEngine;

    var cli = new CLIEngine({
        useEslintrc: false,
        ignore: false,
        parserOptions: {
            ecmaVersion: 5
        }
    });

    var files = constants.partialBundlePaths.map(function(f) { return f.dist; });
    files.unshift(constants.pathToPlotlyBuild, constants.pathToPlotlyDist);

    var report = cli.executeOnFiles(files);
    var formatter = cli.getFormatter();

    var errors = [];
    if(report.errorCount > 0) {
        console.log(formatter(report.results));

        // It doesn't work well to pass formatted logs into this,
        // so instead pass the empty string in a way that causes
        // the test to fail
        errors.push('');
    }

    log('es5-only syntax', errors);
}

function combineGlobs(arr) {
    return '{' + arr.join(',') + '}';
}

function log(name, logs) {
    if(logs.length) {
        console.error('test-syntax error [' + name + ']');
        console.error(logs.join('\n'));
        EXIT_CODE = 1;
    } else {
        console.log('ok ' + name);
    }
}

process.on('exit', function() {
    if(EXIT_CODE) {
        throw new Error('test syntax failed.');
    }
});
<|endoftext|>


<commit_before>/**
 * Created by sebastianplattner on 28.08.16.
 */

myApp.controller("GameController", ["$scope", "$http", "$attrs", "$window", function($scope, $http, $attrs, $window) {

  $scope.selectedTeam = 0;
  $scope.onlyHeimspiele = 0;

  $scope.gameDetailed = {};
  $scope.teamDetailed = {};

  $scope.filterHeimspiele = function(game) {

    if ($scope.onlyHeimspiele == 0) {
      return true;
    }

    if ($scope.onlyHeimspiele == 1 && game.heimspiel == 1) {
      return false;
    }

    return true;

  }

  /**
   * Get all Games for a Team
   *
   * @param teamID
   */
  $scope.getGames = function(teamID) {
    $http.get("index.php/api/game/getGames/" + teamID)
      .then(function(response) {
        $scope.games = response.data;

        /*
        $scope.games.forEach(function(entry) {
          $http.get("index.php/api/game/getGameDetailed/" + entry.extid)
            .then(function(response) {
              entry.detailed = response.data
            });
        })*/
      });
  };

  /**
   * Get all Teams
   */
  $scope.getTeams = function() {
    $http.get("index.php/api/game/getTeams/")
      .then(function(response) {
        $scope.teams = response.data;

      });
  };

  /**
   * Call getGames on a change of team
   */
  $scope.changeTeam = function() {

    $scope.getGames($scope.selectedTeam);
  }

  /**
   * Get GameDetailed
   */
  $scope.getGameDetailed = function(gameID) {
    $scope.gameDetailed = {};
    $http.get("index.php/api/game/getGameDetailed/" + gameID)
      .then(function(response) {
        $scope.gameDetailed = response.data;

      });
  };

  /**
   * Get GameDetailed
   */
  $scope.getAddressesByTeam = function(gameId, home) {
    $scope.teamDetailed = {};

    // Away
    if (home == 0) {
      $http.get("index.php/api/game/getGameDetailed/" + gameId)
        .then(function(response) {

          $http.get("index.php/api/game/getAddressesByTeam/" + response.data.TeamHomeID)
            .then(function(response) {
              $scope.teamDetailed = response.data[0];
            });

        });
    } // End Away Case

    // Home
    if (home == 1) {
      $http.get("index.php/api/game/getGameDetailed/" + gameId)
        .then(function(response) {

          $http.get("index.php/api/game/getAddressesByTeam/" + response.data.TeamAwayID)
            .then(function(response) {
              $scope.teamDetailed = response.data[0];
            });

        });
    } // End Home Case

  };

  $scope.getTeams();
  $scope.getGames(0);

}]);
<commit_msg>Fix game Filter<commit_after>/**
 * Created by sebastianplattner on 28.08.16.
 */

myApp.controller("GameController", ["$scope", "$http", "$attrs", "$window", function($scope, $http, $attrs, $window) {

  $scope.selectedTeam = 0;
  $scope.onlyHeimspiele = 0;

  $scope.gameDetailed = {};
  $scope.teamDetailed = {};

  $scope.filterHeimspiele = function(game) {

    if ($scope.onlyHeimspiele == 0) {
      return false;
    }

    if ($scope.onlyHeimspiele == 1 && game.heimspiel == 1) {
      return true;
    }

    return false;

  }

  /**
   * Get all Games for a Team
   *
   * @param teamID
   */
  $scope.getGames = function(teamID) {
    $http.get("index.php/api/game/getGames/" + teamID)
      .then(function(response) {
        $scope.games = response.data;

        /*
        $scope.games.forEach(function(entry) {
          $http.get("index.php/api/game/getGameDetailed/" + entry.extid)
            .then(function(response) {
              entry.detailed = response.data
            });
        })*/
      });
  };

  /**
   * Get all Teams
   */
  $scope.getTeams = function() {
    $http.get("index.php/api/game/getTeams/")
      .then(function(response) {
        $scope.teams = response.data;

      });
  };

  /**
   * Call getGames on a change of team
   */
  $scope.changeTeam = function() {

    $scope.getGames($scope.selectedTeam);
  }

  /**
   * Get GameDetailed
   */
  $scope.getGameDetailed = function(gameID) {
    $scope.gameDetailed = {};
    $http.get("index.php/api/game/getGameDetailed/" + gameID)
      .then(function(response) {
        $scope.gameDetailed = response.data;

      });
  };

  /**
   * Get GameDetailed
   */
  $scope.getAddressesByTeam = function(gameId, home) {
    $scope.teamDetailed = {};

    // Away
    if (home == 0) {
      $http.get("index.php/api/game/getGameDetailed/" + gameId)
        .then(function(response) {

          $http.get("index.php/api/game/getAddressesByTeam/" + response.data.TeamHomeID)
            .then(function(response) {
              $scope.teamDetailed = response.data[0];
            });

        });
    } // End Away Case

    // Home
    if (home == 1) {
      $http.get("index.php/api/game/getGameDetailed/" + gameId)
        .then(function(response) {

          $http.get("index.php/api/game/getAddressesByTeam/" + response.data.TeamAwayID)
            .then(function(response) {
              $scope.teamDetailed = response.data[0];
            });

        });
    } // End Home Case

  };

  $scope.getTeams();
  $scope.getGames(0);

}]);
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import styled from 'emotion/react'
import cx from 'classnames'

import { LOGO_ASPECT_RATIO, getLogoHeight, logoImageUrl } from '../layouts/logo'
import { baseUl, monofont, sansfont, childLink } from '../layouts/emotion-base'

const menuBreakpoint1 = `max-width: 740px`
const menuBreakpoint3 = `max-width: 520px`

const Wrapper = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 72px;
  background: #fff;
`

const Logo = styled.div`
  position: absolute;
  top: 50%;
  left: 28px;
  background-image: url(${logoImageUrl});
  background-size: 100% 100%;
  width: 120px;
  height: ${getLogoHeight(120)}px;
  transform: translateY(-50%);

  @media (${menuBreakpoint1}) {
    width: 80px;
    height: ${getLogoHeight(80)}px;
  }

  @media (${menuBreakpoint3}) {
    left: 5px;
    top: 5px;
    width: 60px;
    height: ${getLogoHeight(60)}px;
    transform: none;
  }
`

const Nav = styled.ul`
  composes: ${baseUl} ${sansfont};
  position: absolute;
  right: 40px;
  top: 51%;
  display: flex;
  font-size: 28px;
  font-weight: 300;
  color: #000;
  transform: translateY(-50%);

  @media (${menuBreakpoint1}) {
    right: 24px;
    font-size: 18px;
  }

  @media (${menuBreakpoint3}) {
    right: auto;
    left: 50%;
    top: 40px;
    transform: translateX(-50%);
    font-size: 16px;
    padding-right: 30px;
  }
`

const NavItem = styled.li`
  composes: ${childLink};
  margin: 0;
  padding: 0;
  cursor: pointer;
  flex-shrink: 0;

  &:not(:first-child) {
    margin-left: 25px;

    @media (${menuBreakpoint3}) {
      margin-left: 10px;
    }
  }

  &.active a {
    border-bottom: 2px solid #000;
  }
`

const Menu = ({ location }) => {
  let navItems = [
    { name: 'Designers', path: '/', activePath: '/designers' },
    { name: 'Exhibitions', path: '/exhibitions' },
    { name: 'Works', path: '/works' },
    { name: 'Art Fairs', path: '/art-fairs' },
    { name: 'Info', path: '/info' },
  ].map(item => {
    const active =
      location.pathname === item.path ||
      location.pathname.includes(item.activePath || item.path)

    return {
      ...item,
      className: cx({ active }),
    }
  })

  const includeLogo = true

  return (
    <Wrapper>
      {includeLogo && (
        <Link to={'/'}>
          <Logo width={120} />
        </Link>
      )}

      <Nav>
        {navItems.map(item => (
          <NavItem key={item.name} className={item.className}>
            <Link to={item.path}>{item.name}</Link>
          </NavItem>
        ))}
      </Nav>
    </Wrapper>
  )
}

Menu.propTypes = {
  location: PropTypes.object,
}

export default Menu
<commit_msg>boost logo size<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import styled from 'emotion/react'
import cx from 'classnames'

import { LOGO_ASPECT_RATIO, getLogoHeight, logoImageUrl } from '../layouts/logo'
import { baseUl, monofont, sansfont, childLink } from '../layouts/emotion-base'

const menuBreakpoint1 = `max-width: 740px`
const menuBreakpoint3 = `max-width: 520px`

const Wrapper = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 72px;
  background: #fff;
`

const Logo = styled.div`
  position: absolute;
  top: 50%;
  left: 28px;
  background-image: url(${logoImageUrl});
  background-size: 100% 100%;
  width: 136px;
  height: ${getLogoHeight(136)}px;
  transform: translateY(-50%);

  @media (${menuBreakpoint1}) {
    width: 120px;
    height: ${getLogoHeight(120)}px;
  }

  @media (${menuBreakpoint3}) {
    left: 5px;
    top: 5px;
    width: 72px;
    height: ${getLogoHeight(72)}px;
    transform: none;
  }
`

const Nav = styled.ul`
  composes: ${baseUl} ${sansfont};
  position: absolute;
  right: 40px;
  top: 46%;
  display: flex;
  font-size: 28px;
  font-weight: 300;
  color: #000;
  transform: translateY(-50%);

  @media (${menuBreakpoint1}) {
    right: 24px;
    font-size: 18px;
  }

  @media (${menuBreakpoint3}) {
    right: auto;
    left: 50%;
    top: 42px;
    transform: translateX(-50%);
    font-size: 16px;
    padding-right: 30px;
  }
`

const NavItem = styled.li`
  composes: ${childLink};
  margin: 0;
  padding: 0;
  cursor: pointer;
  flex-shrink: 0;

  &:not(:first-child) {
    margin-left: 25px;

    @media (${menuBreakpoint1}) {
      margin-left: 15px;
    }

    @media (${menuBreakpoint3}) {
      margin-left: 10px;
    }
  }

  &.active a {
    border-bottom: 2px solid #000;
  }
`

const Menu = ({ location }) => {
  let navItems = [
    { name: 'Designers', path: '/', activePath: '/designers' },
    { name: 'Exhibitions', path: '/exhibitions' },
    { name: 'Works', path: '/works' },
    { name: 'Art Fairs', path: '/art-fairs' },
    { name: 'Info', path: '/info' },
  ].map(item => {
    const active =
      location.pathname === item.path ||
      location.pathname.includes(item.activePath || item.path)

    return {
      ...item,
      className: cx({ active }),
    }
  })

  const includeLogo = true

  return (
    <Wrapper>
      {includeLogo && (
        <Link to={'/'}>
          <Logo />
        </Link>
      )}

      <Nav>
        {navItems.map(item => (
          <NavItem key={item.name} className={item.className}>
            <Link to={item.path}>{item.name}</Link>
          </NavItem>
        ))}
      </Nav>
    </Wrapper>
  )
}

Menu.propTypes = {
  location: PropTypes.object,
}

export default Menu
<|endoftext|>


<commit_before>'use strict';

(function ($) {
    $.fn.simplebox = function(options) {
        var settings = $.extend({
            fadeSpeed: 400,
            darkMode: false,
            postfix: "",
            hqClass: "hq"
        }, options);

        // Helper Variables
        var $body = $("body");
        var $overlay = $('

');
        var $cross = $('

');
        var $image = $("");
        var fadeSpeed = settings.fadeSpeed;
        var lbIsOpen = false;

        // Modifying theme based on preference
        if (settings.darkMode) {
            $overlay.css('background-color', 'black');
            $cross.addClass('cross--dark');
            $('.slb').addClass('slb--invert');
            $image.addClass('slb--invert');
        } else {
            $overlay.css('background-color', 'white');
            $cross.addClass('cross--light');
        }

        // Function for hiding the overlay.
        var hideOverlay = function() {
            $overlay.fadeOut(fadeSpeed);
            $image.removeClass('slb--opened');
            lbIsOpen = false;
            $body.css("overflow", "auto");
        };

        // When X is clicked or user clicks on the overlay div
        // Hide lightbox
        $overlay.click(hideOverlay);
        $cross.click(hideOverlay);

        // Attaching ESC listener
        $(document).keyup(function(e) {
             if (e.keyCode == 27 && lbIsOpen) {
                hideOverlay();
            }
        });

        return this.each(function() {
            $overlay.append($cross);
            var $this = $(this);

            // When the image is clicked
            $this.click(function() {
                lbIsOpen = true;
                $body.css("overflow", "hidden");

                var $this = $(this);
                var imageSRC = $this.attr("src");
                if (~$this.attr("class").indexOf(settings.hqClass)) {
                    let dotIndex = imageSRC.lastIndexOf(".");
                    imageSRC = imageSRC.substring(0, dotIndex) + settings.postfix + imageSRC.substring(dotIndex);
                }
                var imageSRCSET = $this.attr("srcset");
                $image.attr("src", imageSRC);
                $image.attr("srcset", imageSRCSET);
                $image.css("max-height", "80%");
                $image.addClass('pop-in');
                $image.removeClass('pop-out');
                $image.addClass('center');
                $image.addClass('slb--opened');

                $overlay.css('pointer-events', 'initial');

                $overlay.append($image);
                $body.append($overlay);

                // Show all the things!
                $overlay.fadeIn(fadeSpeed);
            });
        });
    };
}(jQuery));
<commit_msg>Changed let to var<commit_after>'use strict';

(function ($) {
    $.fn.simplebox = function(options) {
        var settings = $.extend({
            fadeSpeed: 400,
            darkMode: false,
            postfix: "",
            hqClass: "hq"
        }, options);

        // Helper Variables
        var $body = $("body");
        var $overlay = $('

');
        var $cross = $('

');
        var $image = $("");
        var fadeSpeed = settings.fadeSpeed;
        var lbIsOpen = false;

        // Modifying theme based on preference
        if (settings.darkMode) {
            $overlay.css('background-color', 'black');
            $cross.addClass('cross--dark');
            $('.slb').addClass('slb--invert');
            $image.addClass('slb--invert');
        } else {
            $overlay.css('background-color', 'white');
            $cross.addClass('cross--light');
        }

        // Function for hiding the overlay.
        var hideOverlay = function() {
            $overlay.fadeOut(fadeSpeed);
            $image.removeClass('slb--opened');
            lbIsOpen = false;
            $body.css("overflow", "auto");
        };

        // When X is clicked or user clicks on the overlay div
        // Hide lightbox
        $overlay.click(hideOverlay);
        $cross.click(hideOverlay);

        // Attaching ESC listener
        $(document).keyup(function(e) {
             if (e.keyCode == 27 && lbIsOpen) {
                hideOverlay();
            }
        });

        return this.each(function() {
            $overlay.append($cross);
            var $this = $(this);

            // When the image is clicked
            $this.click(function() {
                lbIsOpen = true;
                $body.css("overflow", "hidden");

                var $this = $(this);
                var imageSRC = $this.attr("src");
                if (~$this.attr("class").indexOf(settings.hqClass)) {
                    var dotIndex = imageSRC.lastIndexOf(".");
                    imageSRC = imageSRC.substring(0, dotIndex) + settings.postfix + imageSRC.substring(dotIndex);
                }
                var imageSRCSET = $this.attr("srcset");
                $image.attr("src", imageSRC);
                $image.attr("srcset", imageSRCSET);
                $image.css("max-height", "80%");
                $image.addClass('pop-in');
                $image.removeClass('pop-out');
                $image.addClass('center');
                $image.addClass('slb--opened');

                $overlay.css('pointer-events', 'initial');

                $overlay.append($image);
                $body.append($overlay);

                // Show all the things!
                $overlay.fadeIn(fadeSpeed);
            });
        });
    };
}(jQuery));
<|endoftext|>


<commit_before>/*global define*/
/*global Markdown*/
define([
    'underscore',
    'jquery',
    'app',
    'backbone',
    'text!apps/notes/form/templates/form.html',
    'checklist',
    'ace',
    'pagedown-extra',
    'backbone.mousetrap',
    'marionette',
    'typeahead',
    'tagsinput'
],
function (_, $, App, Backbone, Template, Checklist, ace) {
    'use strict';

    var View = Backbone.Marionette.ItemView.extend({
        template: _.template(Template),

        ui: {
            title      :  'input[name="title"]',
            content    :  '.wmd-input',
            tags       :  'select[name="tags"]',
            notebookId :  '[name="notebookId"]',
            sCont      :  '.ui-s-content'
        },

        events: {
            'submit #noteForm' : 'save',
            'click #saveBtn'   : 'save',
            'click #cancelBtn' : 'redirect'
        },

        keyboardEvents: {
            'esc': 'redirect'
        },

        initialize: function () {
            App.mousetrap.API.pause();
            this.on('shown', this.pagedownRender);
        },

        onClose: function () {
            App.mousetrap.API.unpause();
        },

        onRender: function() {
            var that = this,
                tagsNames;

            tagsNames = this.options.tags.getNames();

            // Tagsinput configuration
            this.ui.tags.tagsinput({
                freeInput   :  true,
                confirmKeys :  [13, 44, 188],
                tagClass    :  function () {
                    return 'label label-default';
                }
            });

            // Typeahead configs
            this.ui.tags.tagsinput('input')
                .typeahead({
                    name  : 'tagsInput',
                    local : tagsNames,
                })
                .on('typeahead:selected', $.proxy(function (obj, datum) {
                    that.ui.tags.tagsinput('add', datum.value);
                    that.ui.tags.tagsinput('input').typeahead('setQuery', '');
                }, this.ui.tags));

            // Show existing tags
            if (this.model !== undefined) {
                _.each(this.model.get('tags'), function (tag) {
                    this.ui.tags.tagsinput('add', tag);
                }, this);
            }
        },

        save: function (e) {
            e.preventDefault();

            var content = this.editor.getSession().getValue().trim(),
                title   = this.ui.title.val().trim(),
                data;

            // Get values
            data = {
                title      : (title !== '') ? title : 'Unnamed',
                content    : content,
                notebookId : parseInt(this.ui.notebookId.val()),
                tags       : this.ui.tags.tagsinput('items')
            };

            // Tasks
            var checklist = new Checklist().count(data.content);
            data.taskAll = checklist.all;
            data.taskCompleted = checklist.completed;

            // Trigger save
            this.model.trigger('save', data);
        },

        /**
         * Redirect to note
         */
        redirect: function (e) {
            e.preventDefault();
            return this.trigger('redirect');
        },

        /**
         * Pagedown-ace editor
         */
        pagedownRender: function () {
            // var that = this,
            var converter,
                editor,
                wmdBar,
                scroll;

            converter = new Markdown.Converter();
            editor = new Markdown.Editor(converter);

            // ACE
            this.editor = ace.edit('wmd-input');
            this.editor.getSession().setMode('ace/mode/markdown');
            this.editor.setTheme('ace/theme/github');

            // Ace configs
            // this.editor.setOption('spellcheck', true);
            this.editor.renderer.setShowGutter(false);
            this.editor.renderer.setPrintMarginColumn(false);
            this.editor.session.setUseWrapMode(true);
            this.editor.session.setNewLineMode('unix');

            // Auto expand: http://stackoverflow.com/questions/11584061/automatically-adjust-height-to-contents-in-ace-cloud9-editor
            this.editor.setOptions({
                maxLines: Infinity,
                minLines: 40
            });

            // this.editor.setKeyboardHandler('vim'); // vim
            editor.run(this.editor);

            // Hide default buttons
            this.$('.wmd-button-row li').addClass('btn').css('left', 0).find('span').hide();
            this.$('.wmd-button-row').addClass('btn-group');

            // Font-awesome buttons
            this.$('#wmd-italic-button').append($('<i class="fa fa-italic">'));
            this.$('#wmd-bold-button').append($('<i class="fa fa-bold">'));
            this.$('#wmd-link-button').append($('<i class="fa fa-globe">'));
            this.$('#wmd-quote-button').append($('<i class="fa fa-indent">'));
            this.$('#wmd-code-button').append($('<i class="fa fa-code">'));
            this.$('#wmd-image-button').append($('<i class="fa fa-picture-o">'));
            this.$('#wmd-olist-button').append($('<i class="fa fa-list-ol">'));
            this.$('#wmd-ulist-button').append($('<i class="fa fa-list">'));
            this.$('#wmd-heading-button').append($('<i class="fa fa-font">'));
            this.$('#wmd-hr-button').append($('<i class="fa fa-minus">'));
            this.$('#wmd-undo-button').append($('<i class="fa fa-reply">'));
            this.$('#wmd-redo-button').append($('<i class="fa fa-share">'));

            // Focus to input[title]
            this.ui.title.focus();

            // Whenever a change happens inside the ACE editor, update the note
            // this.editor.on('change', function () {
            //     if (that.model !== undefined) {
            //         that.$('.form-horizontal').trigger('submit');
            //     }
            // });

            // Editor bar spy your scrolls
            wmdBar = this.$('#wmd-button-bar');
            this.ui.sCont.on('scroll', function () {
                scroll = $(this).scrollTop();
                if (scroll >= 260) {
                    wmdBar.addClass('wmd-bar-fixed')
                        .css({top: scroll-2 + 'px'});
                } else {
                    wmdBar.removeClass('wmd-bar-fixed');
                }
            });
        },

        serializeData: function () {
            var data = _.extend(this.model.toJSON(), this.options.decrypted);
            data.notebooks = this.options.notebooks.toJSON();
            return data;
        },

        templateHelpers: function() {
            return {
                isActive: function (id, notebookId) {
                    var selected = '';
                    if (notebookId && id === notebookId) {
                        selected = ' selected="selected"';
                    }
                    return selected;
                }
            };
        }

    });

    return View;
});
<commit_msg>close on user hits esc<commit_after>/*global define*/
/*global Markdown*/
define([
    'underscore',
    'jquery',
    'app',
    'backbone',
    'text!apps/notes/form/templates/form.html',
    'checklist',
    'ace',
    'pagedown-extra',
    'marionette',
    'typeahead',
    'tagsinput'
],
function (_, $, App, Backbone, Template, Checklist, ace) {
    'use strict';

    var View = Backbone.Marionette.ItemView.extend({
        template: _.template(Template),

        ui: {
            title      :  'input[name="title"]',
            content    :  '.wmd-input',
            tags       :  'select[name="tags"]',
            notebookId :  '[name="notebookId"]',
            sCont      :  '.ui-s-content'
        },

        events: {
            'click #saveBtn'   : 'save',
            'click #cancelBtn' : 'redirect',
            'keyup input[name=title]'  : 'keyupEvents'
        },

        initialize: function () {
            this.on('shown', this.pagedownRender);
            App.mousetrap.API.pause();
        },

        onClose: function () {
            App.mousetrap.API.unpause();
        },

        keyupEvents: function (e) {
            switch (e.which) {
                // Close form when user hits Esc
                case 27:
                    this.redirect(e);
                    break;
                // Save when user hits Enter
                case 13:
                    this.save(e);
                    break;
                default:
                    break;
            }
        },

        onRender: function() {
            var that = this,
                tagsNames;

            tagsNames = this.options.tags.getNames();

            // Tagsinput configuration
            this.ui.tags.tagsinput({
                freeInput   :  true,
                confirmKeys :  [13, 44, 188],
                tagClass    :  function () {
                    return 'label label-default';
                }
            });

            // Typeahead configs
            this.ui.tags.tagsinput('input')
                .typeahead({
                    name  : 'tagsInput',
                    local : tagsNames,
                })
                .on('typeahead:selected', $.proxy(function (obj, datum) {
                    that.ui.tags.tagsinput('add', datum.value);
                    that.ui.tags.tagsinput('input').typeahead('setQuery', '');
                }, this.ui.tags));

            // Show existing tags
            if (this.model !== undefined) {
                _.each(this.model.get('tags'), function (tag) {
                    this.ui.tags.tagsinput('add', tag);
                }, this);
            }
        },

        save: function (e) {
            e.preventDefault();

            var content = this.editor.getSession().getValue().trim(),
                title   = this.ui.title.val().trim(),
                data;

            // Get values
            data = {
                title      : (title !== '') ? title : 'Unnamed',
                content    : content,
                notebookId : parseInt(this.ui.notebookId.val()),
                tags       : this.ui.tags.tagsinput('items')
            };

            // Tasks
            var checklist = new Checklist().count(data.content);
            data.taskAll = checklist.all;
            data.taskCompleted = checklist.completed;

            // Trigger save
            this.model.trigger('save', data);
        },

        /**
         * Redirect to note
         */
        redirect: function (e) {
            e.preventDefault();
            return this.trigger('redirect');
        },

        /**
         * Pagedown-ace editor
         */
        pagedownRender: function () {
            // var that = this,
            var converter,
                editor,
                wmdBar,
                scroll;

            converter = new Markdown.Converter();
            editor = new Markdown.Editor(converter);

            // ACE
            this.editor = ace.edit('wmd-input');
            this.editor.getSession().setMode('ace/mode/markdown');
            this.editor.setTheme('ace/theme/github');

            // Ace configs
            // this.editor.setOption('spellcheck', true);
            this.editor.renderer.setShowGutter(false);
            this.editor.renderer.setPrintMarginColumn(false);
            this.editor.session.setUseWrapMode(true);
            this.editor.session.setNewLineMode('unix');

            // Auto expand: http://stackoverflow.com/questions/11584061/automatically-adjust-height-to-contents-in-ace-cloud9-editor
            this.editor.setOptions({
                maxLines: Infinity,
                minLines: 40
            });

            // this.editor.setKeyboardHandler('vim'); // vim
            editor.run(this.editor);

            // Hide default buttons
            this.$('.wmd-button-row li').addClass('btn').css('left', 0).find('span').hide();
            this.$('.wmd-button-row').addClass('btn-group');

            // Font-awesome buttons
            this.$('#wmd-italic-button').append($('<i class="fa fa-italic">'));
            this.$('#wmd-bold-button').append($('<i class="fa fa-bold">'));
            this.$('#wmd-link-button').append($('<i class="fa fa-globe">'));
            this.$('#wmd-quote-button').append($('<i class="fa fa-indent">'));
            this.$('#wmd-code-button').append($('<i class="fa fa-code">'));
            this.$('#wmd-image-button').append($('<i class="fa fa-picture-o">'));
            this.$('#wmd-olist-button').append($('<i class="fa fa-list-ol">'));
            this.$('#wmd-ulist-button').append($('<i class="fa fa-list">'));
            this.$('#wmd-heading-button').append($('<i class="fa fa-font">'));
            this.$('#wmd-hr-button').append($('<i class="fa fa-minus">'));
            this.$('#wmd-undo-button').append($('<i class="fa fa-reply">'));
            this.$('#wmd-redo-button').append($('<i class="fa fa-share">'));

            // Focus to input[title]
            this.ui.title.focus();

            // Whenever a change happens inside the ACE editor, update the note
            // this.editor.on('change', function () {
            //     if (that.model !== undefined) {
            //         that.$('.form-horizontal').trigger('submit');
            //     }
            // });

            // Editor bar spy your scrolls
            wmdBar = this.$('#wmd-button-bar');
            this.ui.sCont.on('scroll', function () {
                scroll = $(this).scrollTop();
                if (scroll >= 260) {
                    wmdBar.addClass('wmd-bar-fixed')
                        .css({top: scroll-2 + 'px'});
                } else {
                    wmdBar.removeClass('wmd-bar-fixed');
                }
            });
        },

        serializeData: function () {
            var data = _.extend(this.model.toJSON(), this.options.decrypted);
            data.notebooks = this.options.notebooks.toJSON();
            return data;
        },

        templateHelpers: function() {
            return {
                isActive: function (id, notebookId) {
                    var selected = '';
                    if (notebookId && id === notebookId) {
                        selected = ' selected="selected"';
                    }
                    return selected;
                }
            };
        }

    });

    return View;
});
<|endoftext|>


<commit_before>wwm.lobby = (function (){
	var jqMap;
	var userInfo;
	function setJqMap($con) {
		jqMap = {
			$con: $con,
			$showCreateroom: $con.find('#show-createroom-modal'),
			$searchroomBtn: $con.find('#searchroom-btn'),
			$list: $con.find('#room-list'),
			$logout: $con.find('#logout-btn'),
			$room: $con.find('.room')
		};
	}
	function initModule($con) {
		userInfo = JSON.parse(localStorage.login);
		console.log('lobby', localStorage.login);
		var src = $('#wwm-lobby').text();
		console.log(src);	dust.render(dust.loadSource(dust.compile(src)), {
			name: userInfo.username
		}, function(err, out) {
			console.log(out);
			$con.html(out);
		});
		setJqMap($con);
		getList();
		jqMap.$showCreateroom.click(showCreateroom);
		jqMap.$searchroomBtn.click(onSearchRoom);
		jqMap.$logout.click(logout);
		jqMap.$room.click(enterRoom);
	}
	function showCreateroom() {
		wwm.modal.initModule($('#wwm-createroom'));
	}
	function getList() {
		$.get('/roomlist').done(function(res){
			jqMap.$list.html();
		});
	}
	function changeList(data) {
		var $frag = $(document.createDocumentFragment());
		jqMap.$list.html();
	}
	function onSearchRoom (query) {
		$.get('/search/' + query, function(res) {
			changeList(res);
		});
	}
	function logout() {
		localStorage.removeItem('login');
		location.href = '/logout';
	}
	function enterRoom() {
		wwm.room.initModule(jqMap.$con);
	}
	return {
		initModule: initModule
	};
}());
<commit_msg>change to nickname<commit_after>wwm.lobby = (function (){
	var jqMap;
	var userInfo;
	function setJqMap($con) {
		jqMap = {
			$con: $con,
			$showCreateroom: $con.find('#show-createroom-modal'),
			$searchroomBtn: $con.find('#searchroom-btn'),
			$list: $con.find('#room-list'),
			$logout: $con.find('#logout-btn'),
			$room: $con.find('.room')
		};
	}
	function initModule($con) {
		userInfo = JSON.parse(localStorage.login);
		console.log('lobby', localStorage.login);
		var src = $('#wwm-lobby').text();
		console.log(src);	dust.render(dust.loadSource(dust.compile(src)), {
			name: userInfo.properties.nickname
		}, function(err, out) {
			console.log(out);
			$con.html(out);
		});
		setJqMap($con);
		getList();
		jqMap.$showCreateroom.click(showCreateroom);
		jqMap.$searchroomBtn.click(onSearchRoom);
		jqMap.$logout.click(logout);
		jqMap.$room.click(enterRoom);
	}
	function showCreateroom() {
		wwm.modal.initModule($('#wwm-createroom'));
	}
	function getList() {
		$.get('/roomlist').done(function(res){
			jqMap.$list.html();
		});
	}
	function changeList(data) {
		var $frag = $(document.createDocumentFragment());
		jqMap.$list.html();
	}
	function onSearchRoom (query) {
		$.get('/search/' + query, function(res) {
			changeList(res);
		});
	}
	function logout() {
		localStorage.removeItem('login');
		location.href = '/logout';
	}
	function enterRoom() {
		wwm.room.initModule(jqMap.$con);
	}
	return {
		initModule: initModule
	};
}());
<|endoftext|>


<commit_before>var PDP = (function ( pdp ) {

  'use strict';

  // The Query Object
  // ----------------
  // The `query` object is used to cache filter values and store methods
  // that manipulate filter values.
  var query = {};

  // If debug is set to true, dummy data will be used.
  query.debug = false;

  // Set a default format for the data download.
  query.format = query.debug ? 'json' : 'jsonp?$callback=';

  // Set a default endpoint for AJAX requests.
  query.endpoint = query.debug ? 'static/js/static_data/' : 'https://api.consumerfinance.gov/data/hmda/';

  // Seconds to wait on a response from the API before giving up.
  query.secondsToWait = 300;

  // Whether or not they want codes in their downloaded file.
  query.codes = false;

  // `query`'s `params` stores filter values.
  query.params = {};

  // The `reset` method empties the `params` object.
  // If a preset is passed, some defaults will be set.
  query.reset = function( preset ) {

    // The year is selected independent of the preset, because
    // of this we have to ensure it doesn't get overwritten.
    var years = $('.field.as_of_year select').val() || [2012];

    switch( preset ) {

      // All originated mortgages.
      case 'originations':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          },
          action_taken: {
            values: [1],
            comparator: '='
          }
        };
      break;

      // First-lien, owner-occupied, 1-4 family homes (including manufactured homes).
      case 'common':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          },
          property_type: {
            values: [1,2],
            comparator: '='
          },
          owner_occupancy: {
            values: [1],
            comparator: '='
          },
          lien_status: {
            values: [1],
            comparator: '='
          },
          action_taken: {
            values: [1],
            comparator: '='
          }
        };
      break;

      // Default to an empty state with whatever years they've selected.
      case 'all':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          }
        };
        break;

      // Empty everything.
      case 'clear':
        this.params = {};
        break;

      // Default to an empty state with whatever years they've selected.
      default:
        this.params = {
          as_of_year: {
            values: [2012],
            comparator: '='
          }
        };
        break;

    }

    return this;

  };

  // The `updateAll` method runs through all the filter field values the user has selected
  // and stores them in the `params` object.
  query.updateAll = function( options ) {

    var fields,
        opts = options || {};

    switch( opts.source ) {
      case 'url':
        fields = pdp.app.getUrlValues();
        break;
      // State is stored in a cookie. Removing this functionality for now because
      // it's confusing the UX team. I'd rather work on other stuff than explain
      // to them how this works. Winter is coming.
      // case 'session':
      //   fields = pdp.query.getCookie();
      //   break;
      default:
        fields = pdp.form.getFields();
    }

    this.reset('clear');

    // Iterate over all the filter field values and push them into `query.params`.
    function _processField( field ) {

      if ( field.name && field.values ) {

        // Initalize an empty param object if need be.
        if ( typeof query.params[ field.name ] === 'undefined' ) {
          query.params[ field.name ] = {
            values: [],
            comparator: '='
          };
        }

        // If the value is a string from a text box we don't want to iterate
        // over it because it will be split up the characters.
        if ( field.type === 'text' ) {
          query.params[ field.name ].values = [ field.values ];
        } else {
          _.forEach( field.values, function( val, name ){

            var values = query.params[ field.name ].values;

            // Only push the value if it's not already in there.
            if ( !_.contains( values, val ) ) {
              values.push( val );
            }

          });
        }

        query.params[ field.name ].comparator = field.comparator;

      }

    }

    _.forEach( fields, _processField );

    pdp.observer.emitEvent( 'params:updated' );

  };

  // The `setCookie` method stores the param object in a cookie.
  query.setCookie = function() {

    $.cookie( '_hmda', pdp.form.getFields(), { expires: 1 } );

  };

  // The `getCookie` method retrives the param object from a cookie.
  query.getCookie = function() {

    return $.cookie( '_hmda' );

  };

  // The `generateUrlHash` method builds and returns a URL hash from `query`'s `params`.
  query.generateUrlHash = function() {
    var hash,
        hashParams = [];

    // Loop through params, stringify them and push them into the temp array.
    function buildHashParam( param, name ) {

      if ( !param.values[0] ) {
        return;
      }

      // If it's not a number, add quotes around the params.
      hashParams.push( name + param.comparator + param.values.join(',') );

    }
    _.forEach( query.params, buildHashParam );

    hash = '!/' + hashParams.join('&') + '&section=' + pdp.app.currentSection;
    return hash;

  };

  query.removeSelectParam = function (params) {
    //using a copy of the params means that the select obj
    //is still available on query.params for share url generation
    var paramsCopy = $.extend(true, {}, params);
    try {
      delete paramsCopy.clauses.where.select;
    } catch (e) {
      //nested property doesn't exist
    }
    delete paramsCopy.select;
    return paramsCopy;
  };

  // The `generateApiUrl` method builds and returns a Qu URL from `query`'s `params`.
  query.generateApiUrl = function( format, codes, params ) {

    var url,
        apiCallParams = params || this.params,
        showCodes = codes || this.codes,
        downloadFormat = format || this.format;
    //remove 'select' from params so it won't be added to where clause
    apiCallParams = query.removeSelectParam(apiCallParams);

    // Set a base url to append params to
    url = this.endpoint + 'slice/hmda_lar.' + downloadFormat + '?';

    if ( !showCodes ) {
      apiCallParams = {
        clauses: {
          where: apiCallParams,
          select: ['action_taken_name','agency_abbr','agency_name','applicant_ethnicity_name','applicant_race_name_1','applicant_race_name_2','applicant_race_name_3','applicant_race_name_4','applicant_race_name_5','applicant_sex_name','application_date_indicator','as_of_year','census_tract_number','co_applicant_ethnicity_name','co_applicant_race_name_1','co_applicant_race_name_2','co_applicant_race_name_3','co_applicant_race_name_4','co_applicant_race_name_5','co_applicant_sex_name','county_name','denial_reason_name_1','denial_reason_name_2','denial_reason_name_3','edit_status_name','hoepa_status_name','lien_status_name','loan_purpose_name','loan_type_name','msamd_name','owner_occupancy_name','preapproval_name','property_type_name','purchaser_type_name','respondent_id','sequence_number','state_abbr','state_name','applicant_income_000s','hud_median_family_income','loan_amount_000s','number_of_1_to_4_family_units','number_of_owner_occupied_units','minority_population','population','rate_spread','tract_to_msamd_income']
        }
      };
    }

    // fetch, compile queries
    url += this._buildApiQuery( apiCallParams );

    return url;

  };

  // builds the query string to append to api url
  // arg: params, object. if you only need a 'where' clause, passing in
  // query.params will do just fine
  // if you need to use the 'select' and 'group' clauses, pass an object
  // that has a property 'clauses' with an array of objects that correspond to
  // each clause. example:
  // params = {
  //   clauses: {
  //     select: ['var_one', 'var_two'],
  //     group: ['var_one', 'var_two']
  //   }
  // }
  query._buildApiQuery = function( params ) {
    var url = '', key;

    if ( params.hasOwnProperty('clauses') ) {
      for ( key in params.clauses ) {
        if ( params.clauses.hasOwnProperty( key ) ) {
          url += this._buildClause[key]( params.clauses[key] );
        }
      }
    } else {
      url = this._buildClause.where( params );
    }

    return url;

  };

  // methods correspond to each type of clause that the API takes
  // builds part of api call query string pertaining to clause
  query._buildClause = {

  // Convert each param to a proper [`$where` clause](http://cfpb.github.io/qu/articles/queries.html#where_in_detail).
    where: function( params ) {

      var _params = {},
          queryVals = [],
          where;

      // In order to compensate for enumerated location fields (state_code-1, county_name-1, etc.)
      // we have to go through and consolidate all enumerated params into unified objects.
      _.forEach( params, function( param, paramName ) {

        if ( !param.values || !param.values[0] ) {
          return;
        }

        var consolidatedName;

        if ( paramName.match(/\-\d+$/) ) {
          consolidatedName = paramName.replace(/\-\d+$/, '');

          // Initalize an empty param object if need be.
          if ( typeof _params[ consolidatedName ] === 'undefined' ) {
            _params[ consolidatedName ] = {
              values: [],
              comparator: '='
            };
          }

          _.forEach( param.values, function( value ){
            _params[ consolidatedName ].values.push( value );
          });

        } else {
          _params[ paramName ] = param;
        }

      });

      // We can now get back to business and generate that WERECLAWS
      _.forEach( _params, function( param, paramName ) {

        var paramVals;

        // Strip `-min/max` from the end of the param. This is mainly done for the loan_amount_000s fields.
        paramName = paramName.replace( /\-(min|max)$/, '' );
        paramVals = this._formatComparisonValues( param, paramName );
        queryVals.push( paramVals );

      }.bind( this ));

      // Join all the params with `AND` operators
      where = queryVals.join(' AND ');

      // All params are joined with `AND` operators... except with locations things
      // get weird. If the user selects multiple states and MSAs, records should be
      // shown that match any of the locations. `OR` operators need to be used.
      // The simplest way of dealing with this one-off use case is to replace()
      // after building the query string.
      where = where.replace( /(msamd|state_code)=([\d"]+)\)? (AND) \(?(msamd|state_code)/, function replacer( match ){
        return match.replace( 'AND', 'OR' );
      });

      // Encode for URIs and replace spaces with plus signs.
      return '&$where=' + encodeURI( where ).replace( /%20/g, '+' );

    },

    // select and group clauses are formatted the same way sans name
    select: function( param ) {
      return '&$select=' + this._listVals( param );
    },

    group: function( param ) {
      return '&$group=' + this._listVals( param ) + '&$orderBy=' + this._listVals( _.clone( param ).reverse() );
    },

    // formats single value clauses
    // returns string of comma-delimited values
    _listVals: function( param ) {

      var i = param.length,
          str = '';

      while( i-- ) {
        if ( typeof param[i] !== 'undefined' ) {
          str += param[i];
          // if this is not the last value, add comma
          if ( i > 0 ) {
            str += ',';
          }
        }
      }

      return str;
    },

    // formats api call values that have a comparison operator
    _formatComparisonValues: function( param, paramName ){

      var paramVal,
          paramVals = [];

      // If there's only value for the param, meaning they only selected one item or
      // it's a radio button that only allows once value, add the stringified
      // param to the `queryVals` array.
      if ( param.values.length === 1 ) {

        // Rate spread specialness
        if ( param.values[0] == 'null' ) {
          paramVal = paramName + param.comparator + '""';
        // Strings
        } else if ( isNaN( param.values[0] ) || paramName === 'msamd' || paramName === 'respondent_id' || paramName === 'census_tract_number' ) {
          paramVal = paramName + param.comparator + '"' + param.values[0] + '"';
        // Numbers
        } else {
          paramVal = paramName + param.comparator + param.values[0];
        }

        return paramVal;

      // If there are multiple values for a single parameter, we iterate over them and
      // put an `OR` operator between them. We then then [group them](http://cfpb.github.io/qu/articles/queries.html#boolean_operators)
      // with parens and add the grouping to the `params` array.
      } else {

        _.forEach( param.values, function( val, key ){

          if ( isNaN( val ) || paramName === 'msamd' || paramName === 'respondent_id' || paramName === 'census_tract_number' ) {
            paramVals.push( '"' + val + '"' );
          } else {
            paramVals.push( val );
          }

        });

        return paramName + ' IN (' + paramVals + ')';

      }

    }

  };

  // The `fetch` method requests and returns JSON from Qu matching the
  // user's filter and grouping clauses
  query.fetch = function() {

  };

  // Export the public API.
  pdp.query = query;

  return pdp;

}( PDP || {} ));
<commit_msg>updated location query, now grouped<commit_after>var PDP = (function ( pdp ) {

  'use strict';

  // The Query Object
  // ----------------
  // The `query` object is used to cache filter values and store methods
  // that manipulate filter values.
  var query = {};

  // If debug is set to true, dummy data will be used.
  query.debug = false;

  // Set a default format for the data download.
  query.format = query.debug ? 'json' : 'jsonp?$callback=';

  // Set a default endpoint for AJAX requests.
  query.endpoint = query.debug ? 'static/js/static_data/' : 'https://api.consumerfinance.gov/data/hmda/';

  // Seconds to wait on a response from the API before giving up.
  query.secondsToWait = 300;

  // Whether or not they want codes in their downloaded file.
  query.codes = false;

  // `query`'s `params` stores filter values.
  query.params = {};

  // The `reset` method empties the `params` object.
  // If a preset is passed, some defaults will be set.
  query.reset = function( preset ) {

    // The year is selected independent of the preset, because
    // of this we have to ensure it doesn't get overwritten.
    var years = $('.field.as_of_year select').val() || [2012];

    switch( preset ) {

      // All originated mortgages.
      case 'originations':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          },
          action_taken: {
            values: [1],
            comparator: '='
          }
        };
      break;

      // First-lien, owner-occupied, 1-4 family homes (including manufactured homes).
      case 'common':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          },
          property_type: {
            values: [1,2],
            comparator: '='
          },
          owner_occupancy: {
            values: [1],
            comparator: '='
          },
          lien_status: {
            values: [1],
            comparator: '='
          },
          action_taken: {
            values: [1],
            comparator: '='
          }
        };
      break;

      // Default to an empty state with whatever years they've selected.
      case 'all':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          }
        };
        break;

      // Empty everything.
      case 'clear':
        this.params = {};
        break;

      // Default to an empty state with whatever years they've selected.
      default:
        this.params = {
          as_of_year: {
            values: [2012],
            comparator: '='
          }
        };
        break;

    }

    return this;

  };

  // The `updateAll` method runs through all the filter field values the user has selected
  // and stores them in the `params` object.
  query.updateAll = function( options ) {

    var fields,
        opts = options || {};

    switch( opts.source ) {
      case 'url':
        fields = pdp.app.getUrlValues();
        break;
      // State is stored in a cookie. Removing this functionality for now because
      // it's confusing the UX team. I'd rather work on other stuff than explain
      // to them how this works. Winter is coming.
      // case 'session':
      //   fields = pdp.query.getCookie();
      //   break;
      default:
        fields = pdp.form.getFields();
    }

    this.reset('clear');

    // Iterate over all the filter field values and push them into `query.params`.
    function _processField( field ) {

      if ( field.name && field.values ) {

        // Initalize an empty param object if need be.
        if ( typeof query.params[ field.name ] === 'undefined' ) {
          query.params[ field.name ] = {
            values: [],
            comparator: '='
          };
        }

        // If the value is a string from a text box we don't want to iterate
        // over it because it will be split up the characters.
        if ( field.type === 'text' ) {
          query.params[ field.name ].values = [ field.values ];
        } else {
          _.forEach( field.values, function( val, name ){

            var values = query.params[ field.name ].values;

            // Only push the value if it's not already in there.
            if ( !_.contains( values, val ) ) {
              values.push( val );
            }

          });
        }

        query.params[ field.name ].comparator = field.comparator;

      }

    }

    _.forEach( fields, _processField );

    pdp.observer.emitEvent( 'params:updated' );

  };

  // The `setCookie` method stores the param object in a cookie.
  query.setCookie = function() {

    $.cookie( '_hmda', pdp.form.getFields(), { expires: 1 } );

  };

  // The `getCookie` method retrives the param object from a cookie.
  query.getCookie = function() {

    return $.cookie( '_hmda' );

  };

  // The `generateUrlHash` method builds and returns a URL hash from `query`'s `params`.
  query.generateUrlHash = function() {
    var hash,
        hashParams = [];

    // Loop through params, stringify them and push them into the temp array.
    function buildHashParam( param, name ) {

      if ( !param.values[0] ) {
        return;
      }

      // If it's not a number, add quotes around the params.
      hashParams.push( name + param.comparator + param.values.join(',') );

    }
    _.forEach( query.params, buildHashParam );

    hash = '!/' + hashParams.join('&') + '&section=' + pdp.app.currentSection;
    return hash;

  };

  query.removeSelectParam = function (params) {
    //using a copy of the params means that the select obj
    //is still available on query.params for share url generation
    var paramsCopy = $.extend(true, {}, params);
    try {
      delete paramsCopy.clauses.where.select;
    } catch (e) {
      //nested property doesn't exist
    }
    delete paramsCopy.select;
    return paramsCopy;
  };

  // The `generateApiUrl` method builds and returns a Qu URL from `query`'s `params`.
  query.generateApiUrl = function( format, codes, params ) {

    var url,
        apiCallParams = params || this.params,
        showCodes = codes || this.codes,
        downloadFormat = format || this.format;
    //remove 'select' from params so it won't be added to where clause
    apiCallParams = query.removeSelectParam(apiCallParams);

    // Set a base url to append params to
    url = this.endpoint + 'slice/hmda_lar.' + downloadFormat + '?';

    if ( !showCodes ) {
      apiCallParams = {
        clauses: {
          where: apiCallParams,
          select: ['action_taken_name','agency_abbr','agency_name','applicant_ethnicity_name','applicant_race_name_1','applicant_race_name_2','applicant_race_name_3','applicant_race_name_4','applicant_race_name_5','applicant_sex_name','application_date_indicator','as_of_year','census_tract_number','co_applicant_ethnicity_name','co_applicant_race_name_1','co_applicant_race_name_2','co_applicant_race_name_3','co_applicant_race_name_4','co_applicant_race_name_5','co_applicant_sex_name','county_name','denial_reason_name_1','denial_reason_name_2','denial_reason_name_3','edit_status_name','hoepa_status_name','lien_status_name','loan_purpose_name','loan_type_name','msamd_name','owner_occupancy_name','preapproval_name','property_type_name','purchaser_type_name','respondent_id','sequence_number','state_abbr','state_name','applicant_income_000s','hud_median_family_income','loan_amount_000s','number_of_1_to_4_family_units','number_of_owner_occupied_units','minority_population','population','rate_spread','tract_to_msamd_income']
        }
      };
    }

    // fetch, compile queries
    url += this._buildApiQuery( apiCallParams );

    return url;

  };

  // builds the query string to append to api url
  // arg: params, object. if you only need a 'where' clause, passing in
  // query.params will do just fine
  // if you need to use the 'select' and 'group' clauses, pass an object
  // that has a property 'clauses' with an array of objects that correspond to
  // each clause. example:
  // params = {
  //   clauses: {
  //     select: ['var_one', 'var_two'],
  //     group: ['var_one', 'var_two']
  //   }
  // }
  query._buildApiQuery = function( params ) {
    var url = '', key;

    if ( params.hasOwnProperty('clauses') ) {
      for ( key in params.clauses ) {
        if ( params.clauses.hasOwnProperty( key ) ) {
          url += this._buildClause[key]( params.clauses[key] );
        }
      }
    } else {
      url = this._buildClause.where( params );
    }

    return url;

  };

  // methods correspond to each type of clause that the API takes
  // builds part of api call query string pertaining to clause
  query._buildClause = {

  // Convert each param to a proper [`$where` clause](http://cfpb.github.io/qu/articles/queries.html#where_in_detail).
    where: function( params ) {

      var _params = {},
          queryVals = [],
          locVals = [],
          locGroup = {}, //Create a group that finds state / counties with similar numbers.
          where;

      // In order to compensate for enumerated location fields (state_code-1, county_name-1, etc.)
      // we have to go through and consolidate all enumerated params into unified objects.
      _.forEach( params, function( param, paramName ) {
        //joiner used to allow for congifurable AND/OR statements in query
        param.joiner = ' AND ';

        if ( !param.values || !param.values[0] ) {
          return;
        }

        var consolidatedName, groupName;
        // If the parameter is an enumerated (state-code-1) field then
        if ( paramName.match(/\-\d+$/) ) {
          param.joiner = ' OR ';

          // If this is a special case with county, state, or census tract
          // then they needs to be grouped together as an object for appropriate query creation
          if ( paramName.indexOf('state_code') > -1 || paramName.indexOf('county_code') > -1 || paramName.indexOf('census_tract_number') > -1 ){
            // If a number exists, create a location group to bring city, state, and census tract together
            groupName = paramName.slice(-2);

            // Initialize an empty location group if necessary
            if( typeof locGroup[ groupName ] === 'undefined' ){
              locGroup[ groupName ] = {
                stateValue: '',
                countyValues: [],
                censusValues: [],
                comparator: '=',
                joiner: ' OR '
              };
            }
            // Loop through each location group parameter and push it to the appropriate object
            _.forEach( param.values, function( value ){
              if ( paramName.indexOf('state_code') > -1 ){
                locGroup[ groupName ].stateValue = value;
              } else if ( paramName.indexOf('county_code') > -1 ){
                locGroup[ groupName ].countyValues.push( value );
              } else if ( paramName.indexOf('census_tract_number') > -1 ){
                locGroup[ groupName ].censusValues.push( '"' + value + '"' );
              }
            });
          // If not state, county, census, then create a consolidated parameter (ie 'msamd')
          } else {
            // Initalize an empty param object if need be.
            consolidatedName = paramName.replace(/\-\d+$/, '');
            if ( typeof _params[ consolidatedName ] === 'undefined' ) {
              _params[ consolidatedName ] = {
                values: [],
                comparator: '=',
                joiner: ' AND '
              };
            }

            _.forEach( param.values, function( value ){
              _params[ consolidatedName ].values.push( value );
            });
          }
        // If the parameter is NOT an enumerated field, push it to _params
        } else {
          _params[ paramName ] = param;
        }
      });

      // We can now get back to business and generate that WERECLAWS
      _.forEach( _params, function( param, paramName ) {

        var paramVals;

        // Strip `-min/max` from the end of the param. This is mainly done for the loan_amount_000s fields.
        paramName = paramName.replace( /\-(min|max)$/, '' );
        paramVals = this._formatComparisonValues( param, paramName );
        // If calling msamd, then it needs to be joined to location data with "OR" and placed at end of array
        if( paramName.indexOf('msamd') > -1 ){
          param.joiner = ' OR ';
          locVals.push( paramVals );
          locVals.push( param.joiner );
        // Otherwise, push the parameter to the queryVals array which is joined first (below)
        } else {
          queryVals.push( paramVals );
        }
      }.bind( this ));

      // For each location group, iterate through and create valid, grouped query string
      _.forEach( locGroup, function(i, val){
        var queryStr = '', item = locGroup[val];
        if( item.stateValue === "" ){
        } else if( item.countyValues.length === 0 ){
          queryStr += 'state_code=' + item.stateValue;
          locVals.push(queryStr);
          locVals.push(item.joiner);
        } else if( item.censusValues.length === 0 ){
          queryStr += '(state_code=' + item.stateValue + ' AND county_code IN (' + item.countyValues.toString() + '))';
          locVals.push(queryStr);
          locVals.push(item.joiner);
        } else {
          queryStr += '(state_code=' + item.stateValue + ' AND county_code IN (' + item.countyValues.toString() + ') AND census_tract_number IN (' + item.censusValues + '))';
          locVals.push(queryStr);
          locVals.push(item.joiner);
        }
      });

      locVals.pop(); //Get rid of the last joiner / operator - not needed.
      // Add each queryVals parameter and their joiner string to where variable
      where = queryVals.join(' AND ');
      // If location information selected, then join that as well
      if( locVals.length > 0 ){
        where += ' AND (' + locVals.join('') + ')';
      }
      // A REGEX used to be here that substituted in certain scenarios - this was not sufficient for the use case.

      // Encode for URIs and replace spaces with plus signs.
      return '&$where=' + encodeURI( where ).replace( /%20/g, '+' );

    },

    // select and group clauses are formatted the same way sans name
    select: function( param ) {
      return '&$select=' + this._listVals( param );
    },

    group: function( param ) {
      return '&$group=' + this._listVals( param ) + '&$orderBy=' + this._listVals( _.clone( param ).reverse() );
    },

    // formats single value clauses
    // returns string of comma-delimited values
    _listVals: function( param ) {

      var i = param.length,
          str = '';

      while( i-- ) {
        if ( typeof param[i] !== 'undefined' ) {
          str += param[i];
          // if this is not the last value, add comma
          if ( i > 0 ) {
            str += ',';
          }
        }
      }

      return str;
    },

    // formats api call values that have a comparison operator
    _formatComparisonValues: function( param, paramName ){

      var paramVal,
          paramVals = [];

      // If there's only value for the param, meaning they only selected one item or
      // it's a radio button that only allows once value, add the stringified
      // param to the `queryVals` array.
      if ( param.values.length === 1 ) {

        // Rate spread specialness
        if ( param.values[0] == 'null' ) {
          paramVal = paramName + param.comparator + '""';
        // Strings
        } else if ( isNaN( param.values[0] ) || paramName === 'msamd' || paramName === 'respondent_id' || paramName === 'census_tract_number' ) {
          paramVal = paramName + param.comparator + '"' + param.values[0] + '"';
        // Numbers
        } else {
          paramVal = paramName + param.comparator + param.values[0];
        }

        return paramVal;

      // If there are multiple values for a single parameter, we iterate over them and
      // put an `OR` operator between them. We then then [group them](http://cfpb.github.io/qu/articles/queries.html#boolean_operators)
      // with parens and add the grouping to the `params` array.
      } else {

        _.forEach( param.values, function( val, key ){

          if ( isNaN( val ) || paramName === 'msamd' || paramName === 'respondent_id' || paramName === 'census_tract_number' ) {
            paramVals.push( '"' + val + '"' );
          } else {
            paramVals.push( val );
          }

        });

        return paramName + ' IN (' + paramVals + ')';

      }

    }

  };

  // The `fetch` method requests and returns JSON from Qu matching the
  // user's filter and grouping clauses
  query.fetch = function() {

  };

  // Export the public API.
  pdp.query = query;

  return pdp;

}( PDP || {} ));
<|endoftext|>


<commit_before>/*globals define*/
/*jshint node:true, browser: true*/
/**
 * This class defines the common interface for a storage-project
 * @author pmeijer / https://github.com/pmeijer
 */

define([
    'common/storage/project/cache',
    'common/storage/constants',
], function (ProjectCache, CONSTANTS) {
    'use strict';

    function ProjectInterface(projectId, storageObjectsAccessor, mainLogger, gmeConfig) {
        this.projectId = projectId;
        this.CONSTANTS = CONSTANTS;
        this.ID_NAME = CONSTANTS.MONGO_ID;
        this.logger = mainLogger.fork('Project:' + this.projectId);
        this.logger.debug('ctor', projectId);
        this.projectCache = new ProjectCache(storageObjectsAccessor, this.projectId, this.logger, gmeConfig);

        // Functions forwarded to project cache.
        this.insertObject = this.projectCache.insertObject;
        this.loadObject = this.projectCache.loadObject;

        // Functions forwarded to storage.
        this.makeCommit = function (branchName, parents, rootHash, coreObjects, msg, callback) {
            throw new Error('makeCommit must be overridden in derived class');
        };

        this.setBranchHash = function (branchName, newHash, oldHash, callback) {
            throw new Error('setBranchHash must be overridden in derived class');
        };

        this.getBranchHash = function (branchName, callback) {
            throw new Error('setBranchHash must be overridden in derived class');
        };

        this.createBranch = function (branchName, newHash, callback) {
            throw new Error('createBranch must be overridden in derived class');
        };

        this.deleteBranch = function (branchName, oldHash, callback) {
            throw new Error('createBranch must be overridden in derived class');
        };

        this.getBranches = function (callback) {
            throw new Error('getBranches must be overridden in derived class');
        };

        this.getCommits = function (before, number, callback) {
            throw new Error('getCommits must be overridden in derived class');
        };

        this.getCommonAncestorCommit = function (commitA, commitB, callback) {
            throw new Error('getCommonAncestorCommit must be overridden in derived class');
        };
    }

    return ProjectInterface;
});<commit_msg>Update interface.js<commit_after>/*globals define*/
/*jshint node:true, browser: true*/
/**
 * This class defines the common interface for a storage-project
 * @author pmeijer / https://github.com/pmeijer
 */

define([
    'common/storage/project/cache',
    'common/storage/constants',
], function (ProjectCache, CONSTANTS) {
    'use strict';

    function ProjectInterface(projectId, storageObjectsAccessor, mainLogger, gmeConfig) {
        this.projectId = projectId;
        this.CONSTANTS = CONSTANTS;
        this.ID_NAME = CONSTANTS.MONGO_ID;
        this.logger = mainLogger.fork('Project:' + this.projectId);
        this.logger.debug('ctor', projectId);
        this.projectCache = new ProjectCache(storageObjectsAccessor, this.projectId, this.logger, gmeConfig);

        // Functions forwarded to project cache.
        this.insertObject = this.projectCache.insertObject;
        this.loadObject = this.projectCache.loadObject;

        // Functions forwarded to storage.
        this.makeCommit = function (branchName, parents, rootHash, coreObjects, msg, callback) {
            throw new Error('makeCommit must be overridden in derived class');
        };

        this.setBranchHash = function (branchName, newHash, oldHash, callback) {
            throw new Error('setBranchHash must be overridden in derived class');
        };

        this.getBranchHash = function (branchName, callback) {
            throw new Error('getBranchHash must be overridden in derived class');
        };

        this.createBranch = function (branchName, newHash, callback) {
            throw new Error('createBranch must be overridden in derived class');
        };

        this.deleteBranch = function (branchName, oldHash, callback) {
            throw new Error('deleteBranch must be overridden in derived class');
        };

        this.getBranches = function (callback) {
            throw new Error('getBranches must be overridden in derived class');
        };

        this.getCommits = function (before, number, callback) {
            throw new Error('getCommits must be overridden in derived class');
        };

        this.getCommonAncestorCommit = function (commitA, commitB, callback) {
            throw new Error('getCommonAncestorCommit must be overridden in derived class');
        };
    }

    return ProjectInterface;
});
<|endoftext|>


<commit_before>/*************************
**	Modules		**
**************************/

var request	=	require('request');
var cheerio	=	require('cheerio');

/*************************
**	Variables	**
**************************/

var BASE_URL	=	"http://eztv.it";
var SHOWLIST	=	"/showlist/";
var LATEST	=	"/sort/100/";
var SEARCH	=	"/search/";
var SHOWS   =   "/shows/";

exports.getAllShows	=	function(cb) {
	if(cb == null) return;
    	request(BASE_URL + SHOWLIST, function(err, res, html){

		if(err) return (err, null);

		var $ = cheerio.load(html);
		var title, show;
		var allShows = [];

		$('.thread_link').each(function(){
			var entry = $(this);
			var show = entry.text();
            var id = entry.attr('href').match(/\/shows\/(.*)\/(.*)\//)[1];
            var slug = entry.attr('href').match(/\/shows\/(.*)\/(.*)\//)[2];
			allShows.push({show: show, id: id, slug: slug});
		});

		return cb(null, allShows);
    	});
}

exports.getEpisodeMagnet	=	function(data, cb) {
	if(cb == null) return;
	var show = data.show;
	var season = data.season;
	var episode = data.episode;
	if(season.toString().length==1) season = "0"+season;

	if(episode.toString().length==1) episode = "0"+episode;

	var searchString = show +"+S"+ season + "E" + episode;

	request.post(BASE_URL + SEARCH, {form: {SearchString1: searchString}}, function (err, res, html) {
		if(err) return cb(err, null);

		var $ = cheerio.load(html);

		var show_rows = $('tr.forum_header_border[name="hover"]').filter(function(){
			var entry = $(this);
			return entry.find('img[title="Show Description about '+ show+'"]').length > 0;
		});

		if(show_rows.length === 0) return cb("Show Not Found", null);

		var episode_row = show_rows.filter(function() {
			var entry = $(this);
			return entry.text().indexOf("S"+season+"E"+episode) !== -1;
		});

		if(episode_row.length === 0) return cb("Episode Not Found", null);

		var magnet_link = episode_row.children('td[align="center"]').children('a').first().attr('href');
		return cb(null, magnet_link);
	});
};

exports.getAllEpisodes = function(data, cb) {
    if(cb == null) return;
    var episodes = {};

    request.get(BASE_URL + SHOWS + data.id + "/"+ data.slug +"/", function (err, res, html) {
        if(err) return cb(err, null);

        var $ = cheerio.load(html);

        var show_rows = $('tr.forum_header_border[name="hover"]').filter(function() {
            return $(this).children('.forum_thread_post').length > 0;
        });

        if(show_rows.length === 0) return cb("Show Not Found", null);

        show_rows.each(function() {
            var entry = $(this);
            var title = entry.children('td').eq(1).text();
            var magnet = entry.children('td').eq(2).children('a').first().attr('href');
            var matcher = title.match(/S([0-9]+)E([0-9]+)/);
            if(!matcher) matcher = title.match(/([0-9]+)x([0-9]+)/);
            if(matcher) {
                var season = matcher[1];
                var episode = matcher[2];
                var episodeStruct = {};
                episodeStruct.url = magnet;
                episodeStruct.seeds = 0;
                episodeStruct.peers = 0;
                if(!episodes[season]) episodes[season] = {};
                episodes[season][episode] = episodeStruct;
            }
        });
        return cb(null, episodes);
    });
}
<commit_msg>Remove leading zeroes from season+episode numbers<commit_after>/*************************
**	Modules		**
**************************/

var request	=	require('request');
var cheerio	=	require('cheerio');

/*************************
**	Variables	**
**************************/

var BASE_URL	=	"http://eztv.it";
var SHOWLIST	=	"/showlist/";
var LATEST	=	"/sort/100/";
var SEARCH	=	"/search/";
var SHOWS   =   "/shows/";

exports.getAllShows	=	function(cb) {
	if(cb == null) return;
    	request(BASE_URL + SHOWLIST, function(err, res, html){

		if(err) return (err, null);

		var $ = cheerio.load(html);
		var title, show;
		var allShows = [];

		$('.thread_link').each(function(){
			var entry = $(this);
			var show = entry.text();
            var id = entry.attr('href').match(/\/shows\/(.*)\/(.*)\//)[1];
            var slug = entry.attr('href').match(/\/shows\/(.*)\/(.*)\//)[2];
			allShows.push({show: show, id: id, slug: slug});
		});

		return cb(null, allShows);
    	});
}

exports.getEpisodeMagnet	=	function(data, cb) {
	if(cb == null) return;
	var show = data.show;
	var season = data.season;
	var episode = data.episode;
	if(season.toString().length==1) season = "0"+season;

	if(episode.toString().length==1) episode = "0"+episode;

	var searchString = show +"+S"+ season + "E" + episode;

	request.post(BASE_URL + SEARCH, {form: {SearchString1: searchString}}, function (err, res, html) {
		if(err) return cb(err, null);

		var $ = cheerio.load(html);

		var show_rows = $('tr.forum_header_border[name="hover"]').filter(function(){
			var entry = $(this);
			return entry.find('img[title="Show Description about '+ show+'"]').length > 0;
		});

		if(show_rows.length === 0) return cb("Show Not Found", null);

		var episode_row = show_rows.filter(function() {
			var entry = $(this);
			return entry.text().indexOf("S"+season+"E"+episode) !== -1;
		});

		if(episode_row.length === 0) return cb("Episode Not Found", null);

		var magnet_link = episode_row.children('td[align="center"]').children('a').first().attr('href');
		return cb(null, magnet_link);
	});
};

exports.getAllEpisodes = function(data, cb) {
    if(cb == null) return;
    var episodes = {};

    request.get(BASE_URL + SHOWS + data.id + "/"+ data.slug +"/", function (err, res, html) {
        if(err) return cb(err, null);

        var $ = cheerio.load(html);

        var show_rows = $('tr.forum_header_border[name="hover"]').filter(function() {
            return $(this).children('.forum_thread_post').length > 0;
        });

        if(show_rows.length === 0) return cb("Show Not Found", null);

        show_rows.each(function() {
            var entry = $(this);
            var title = entry.children('td').eq(1).text();
            var magnet = entry.children('td').eq(2).children('a').first().attr('href');
            var matcher = title.match(/S([0-9]+)E([0-9]+)/);
            if(!matcher) matcher = title.match(/([0-9]+)x([0-9]+)/);
            if(matcher) {
                var season = parseInt(matcher[1], 10);
                var episode = parseInt(matcher[2], 10);
                var episodeStruct = {};
                episodeStruct.url = magnet;
                episodeStruct.seeds = 0;
                episodeStruct.peers = 0;
                if(!episodes[season]) episodes[season] = {};
                episodes[season][episode] = episodeStruct;
            }
        });
        return cb(null, episodes);
    });
}
<|endoftext|>