<commit_before>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // Util
    // =======

    function _request(method, path, data, cb, raw) {
      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json"}
      xhr.open(method, API_URL + path);
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : JSON.parse(this.responseText));
          } else {
            cb(this.status);
          }
        }
      }
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        _request("GET", "/users/"+username, null, function(err, res) {
          cb(err, res);
        });
      }

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // List all user gists
      // This will return all public gists if user is not authenticated
      // -------

      this.userGists = function(username,cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef(branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/heads/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef(branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        var data = {
          "content": content,
          "encoding": "utf-8"
        };
        _request("POST", repoPath + "/git/blobs", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, function(err, info) {
          cb(null, info);
        });
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, cb);
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.postBlob(content, function(err, blob) {
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              that.commit(latestCommit, tree, message, function(err, commit) {
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var that = this;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.show = function(cb) {
        _request("GET", gistPath, null, function(err,info) {
          cb(err,info);
        });
      };

      // Star the gist
      // --------

      this.star = function(cb) {
        _request("PUT", gistPath+"/star", null, function(err,res) {
          cb(err,res);
        });
      }

      // Check if the Gist is starred
      // --------

      this.isStarred = function(cb) {
        _request("GET", gistPath+"/star", null, function(err,res) {
          cb(err,res);
        });
      };

      // Unstar the gist
      // --------

      this.unstar = function(cb) {
        _request("DELETE", gistPath+"/star", null, function(err,res) {
          cb(err,res);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.edit = function(cb,options) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };

      // Update Gist Description
      // --------

      this.updateDescription = function(cb,description) {
        that.edit(cb,{description: description});
      };

      // Rename a file in the gist
      // --------

      this.renameFile = function(oldName, newName, cb) {
        var options = {files:{}};
        options.files[oldName] = newName;
        that.edit(cb, options);
      };

      // Delete a file in the gist
      // --------

      this.deleteFile = function(fileName, cb) {
        var options = {files:{}};
        options.files[fileName] = null;
        that.edit(cb,options);
      };

      // Update a particular file in the gist
      this.updateFile = function(filename, contents, cb) {
        var options = {files:{}};
        options.files[filename] = {content: contents};
        that.edit(cb,options);
      }
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<commit_msg>Updated GitHub.js to fix a bunch of mad errors.<commit_after>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // Util
    // =======

    function _request(method, path, data, cb, raw) {
      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json"}
      xhr.open(method, API_URL + path);
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
          } else {
            cb({request: this, error: this.status});
          }
        }
      }
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        _request("GET", "/users/"+username, null, function(err, res) {
          cb(err, res);
        });
      }

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef(branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/heads/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef(branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, function(err, info) {
          cb(null, info);
        });
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, cb);
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var that = this;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<|endoftext|>


<commit_before>module.exports = function(grunt) {

    "use strict";

    var monkeyBarsName = "MonkeyBars";
    var monkeyBarsVersion = "0.9.10";
    var monkeyBarsDescription = "Task library that provides a simple structure for handling singular, sequential and parallel units of code.";
    var monkeyBarsRepository = "https://github.com/mcgaryes/monkeybars/";
    var monkeyBarsBanner = "/*!\n* MonkeyBars v" + monkeyBarsVersion + "\n* " + monkeyBarsDescription + " \n* " + monkeyBarsRepository + "\n*/";

    // object will be used to create the package.json file for npm manager
    var monkeyBarsPackageJsonTemplate = {
        "name": monkeyBarsName.toLowerCase(),
        "version": monkeyBarsVersion,
        "description": monkeyBarsDescription,
        "keywords": ["task", "sequence", "parallel", "asynchronous", "async", "util"],
        "homepage": monkeyBarsRepository,
        "bugs": {
            "url": monkeyBarsRepository + "issues"
        },
        "main": monkeyBarsName.toLowerCase() + ".js",
        "repository": {
            "type": "git",
            "url": monkeyBarsRepository
        },
        "licenses": [{
            "type": "MIT",
            "url": monkeyBarsRepository + "master/LICENSE"
        }]
    };

    // config
    grunt.initConfig({
        lint: {
            files: ['grunt.js', '../monkeybars.js']
        },
        meta: {
            banner: monkeyBarsBanner
        },
        jasmine: {
            all: {
                src: ['../tests/index-dist.html'],
                errorReporting: true
            }
        },
        min: {
            dist: {
                src: ['<banner>', '../monkeybars.js'],
                dest: '../monkeybars.min.js'
            }
        },
        combine: {
            source: {
                input: "../source/core.js",
                output: "../monkeybars.js",
                tokens: [{
                    token:"//%pre",
                    string:"/*!\n * @module MonkeyBars\n * @main MonkeyBars\n*/\n\n(function() {"
                },{
                    token:"//%worker",
                    file:"../source/worker.js"
                },{
                    token:"//%simple",
                    file:"../source/simple.js"
                },{
                    token:"//%group",
                    file:"../source/group.js"
                },{
                    token:"//%parallel",
                    file:"../source/parallel.js"
                },{
                    token:"//%sequence",
                    file:"../source/sequence.js"
                },{
                    token:"//%decorators",
                    file:"../source/decorators.js"
                },{
                    token:"//%post",
                    string:"}).call(this);"
                }]
            }
        },
        copy: {
            package: {
                options: {
                    processContent: function() {
                        return JSON.stringify(monkeyBarsPackageJsonTemplate);
                    }
                },
                files: {
                    "../package.json": "../package.json"
                }
            },
            version: {
                options: {
                    processContent: function() {
                        return monkeyBarsVersion;
                    }
                },
                files: {
                    "../VERSION": "../VERSION"
                }
            }
        },
        yuidoc: {
            compile: {
                "name": monkeyBarsName,
                "description": monkeyBarsDescription,
                "version": monkeyBarsVersion,
                "url": monkeyBarsRepository,
                options: {
                    paths: "../",
                    outdir: "../docs/"
                }
            }
        },
        jsbeautifier : {
          files : ["../monkeybars.js"],
          options : {
            "indent_size": 4
            // "indent_char": " ",
            // "indent_level": 0,
            // "indent_with_tabs": false,
            // "preserve_newlines": true,
            // "max_preserve_newlines": 10,
            // "jslint_happy": false,
            // "brace_style": "collapse",
            // "keep_array_indentation": false,
            // "keep_function_indentation": false,
            // "space_before_conditional": true,
            // "eval_code": false,
            // "indent_case": false,
            // "unescape_strings": false
          }
        },
        jshint: {
            options: {
                curly: true,
                eqeqeq: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                sub: true,
                undef: true,
                boss: true,
                eqnull: true,
                node: true,
                es5: true,
                smarttabs: false,
                strict: true
            },
            globals: {
                yui: true,
                Worker: false,
                Blob: false,
                postMessage: false
            }
        }
    });

    // load npm tasks
    grunt.loadNpmTasks('grunt-jasmine-task');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-combine');
    grunt.loadNpmTasks('grunt-jsbeautifier');

    // tasks
    grunt.registerTask('default', 'combine:source lint min jasmine jsbeautifier copy:package copy:version yuidoc');

};<commit_msg>separated test and release out in grunt.js file<commit_after>module.exports = function(grunt) {

    "use strict";

    var monkeyBarsName = "MonkeyBars";
    var monkeyBarsVersion = "0.9.10";
    var monkeyBarsDescription = "Task library that provides a simple structure for handling singular, sequential and parallel units of code.";
    var monkeyBarsRepository = "https://github.com/mcgaryes/monkeybars/";
    var monkeyBarsBanner = "/*!\n* MonkeyBars v" + monkeyBarsVersion + "\n* " + monkeyBarsDescription + " \n* " + monkeyBarsRepository + "\n*/";

    // object will be used to create the package.json file for npm manager
    var monkeyBarsPackageJsonTemplate = {
        "name": monkeyBarsName.toLowerCase(),
        "version": monkeyBarsVersion,
        "description": monkeyBarsDescription,
        "keywords": ["task", "sequence", "parallel", "asynchronous", "async", "util"],
        "homepage": monkeyBarsRepository,
        "bugs": {
            "url": monkeyBarsRepository + "issues"
        },
        "main": monkeyBarsName.toLowerCase() + ".js",
        "repository": {
            "type": "git",
            "url": monkeyBarsRepository
        },
        "licenses": [{
            "type": "MIT",
            "url": monkeyBarsRepository + "master/LICENSE"
        }]
    };

    // config
    grunt.initConfig({
        lint: {
            files: ['grunt.js', '../monkeybars.js']
        },
        meta: {
            banner: monkeyBarsBanner
        },
        jasmine: {
            all: {
                src: ['../tests/index-dist.html'],
                errorReporting: true
            }
        },
        min: {
            dist: {
                src: ['<banner>', '../monkeybars.js'],
                dest: '../monkeybars.min.js'
            }
        },
        combine: {
            source: {
                input: "../source/core.js",
                output: "../monkeybars.js",
                tokens: [{
                    token:"//%pre",
                    string:"/*!\n * @module MonkeyBars\n * @main MonkeyBars\n*/\n\n(function() {"
                },{
                    token:"//%worker",
                    file:"../source/worker.js"
                },{
                    token:"//%simple",
                    file:"../source/simple.js"
                },{
                    token:"//%group",
                    file:"../source/group.js"
                },{
                    token:"//%parallel",
                    file:"../source/parallel.js"
                },{
                    token:"//%sequence",
                    file:"../source/sequence.js"
                },{
                    token:"//%decorators",
                    file:"../source/decorators.js"
                },{
                    token:"//%post",
                    string:"}).call(this);"
                }]
            }
        },
        copy: {
            package: {
                options: {
                    processContent: function() {
                        return JSON.stringify(monkeyBarsPackageJsonTemplate);
                    }
                },
                files: {
                    "../package.json": "../package.json"
                }
            },
            version: {
                options: {
                    processContent: function() {
                        return monkeyBarsVersion;
                    }
                },
                files: {
                    "../VERSION": "../VERSION"
                }
            }
        },
        yuidoc: {
            compile: {
                "name": monkeyBarsName,
                "description": monkeyBarsDescription,
                "version": monkeyBarsVersion,
                "url": monkeyBarsRepository,
                options: {
                    paths: "../",
                    outdir: "../docs/"
                }
            }
        },
        jsbeautifier : {
          files : ["../monkeybars.js"],
          options : {
            "indent_size": 4
          }
        },
        jshint: {
            options: {
                curly: true,
                eqeqeq: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                sub: true,
                undef: true,
                boss: true,
                eqnull: true,
                node: true,
                es5: true,
                smarttabs: false,
                strict: true
            },
            globals: {
                yui: true,
                Worker: false,
                Blob: false,
                postMessage: false
            }
        }
    });

    // load npm tasks
    grunt.loadNpmTasks('grunt-jasmine-task');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-combine');
    grunt.loadNpmTasks('grunt-jsbeautifier');

    // tasks
    grunt.registerTask('test', 'lint jasmine');
    grunt.registerTask('release', 'combine:source lint min jasmine jsbeautifier copy:package copy:version yuidoc');
};<|endoftext|>


<commit_before>var VisualScheduleCard = {
    name: 'VisualScheduleCard',
    dom_target: undefined,
    term: 'current',
    ck_student_schedule: false,
    ck_instructor_schedule: false,
    day_label_offset: 0,

    should_hide: function() {
        if (window.user.student || window.user.instructor) {
            return false;
        }
        return true;
    },

    render_init: function(term, course_index) {
        if (VisualScheduleCard.should_hide()) {
            VisualScheduleCard.hide_card();
            return;
        }
        WSData.fetch_visual_schedule_term(VisualScheduleCard.term,
                                          VisualScheduleCard.render_handler,
                                          VisualScheduleCard.render_handler);
    },

    hide_card: function(){
        $("#VisualScheduleCard").hide();
    },

    render_handler: function() {
        var schedule_data = WSData.visual_schedule_data(VisualScheduleCard.term);
        if (schedule_data === undefined){
            VisualScheduleCard.hide_card();
            return;
        }
        var default_period = VisualScheduleCard._get_default_period(schedule_data.periods);

        VisualScheduleCard.display_schedule_for_period(default_period);
    },

    _render_error: function() {
        VisualScheduleCard.hide_card();
    },

    _get_period_lables: function(schedule_data){
        var periods = {};
        $(schedule_data.periods).each(function(idx, period){
            periods[period.id] = {'start_date': period.start_date,
                'end_date': period.end_date};
        });
        return periods;
    },

    _get_data_for_period: function(course_data, term){
        var days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
        var visual_data = {
            //has_early_fall_start: ((course_data && course_data.has_early_fall_start) ||
            //                       (instructed_course_data &&
            //                        instructed_course_data.has_early_fall_start)),
            is_pce: window.user.pce,
            total_sections: course_data.sections.length,
            quarter: term.quarter,
            year: term.year,
            summer_term: term.summer_term,
            latest_ending: 0,
            earliest_start: 24*60,
            monday: [],
            tuesday: [],
            wednesday: [],
            thursday: [],
            friday: [],
            saturday: [],
            sunday: [],
            display_hours: [],
            day_class: "five-day",
            courses_meeting_tbd: [],
            courses_no_meeting: [],
            meets_saturday: false,
            meets_sunday: false,
            disabled_days: course_data.disabled_days
        };

        var set_meeting = function(course_data) {
            $.each(course_data.sections, function(section_index) {
                var section = this;
                $.each(section.meetings, function(){
                    var meeting = this;
                    var has_meetings = VisualScheduleCard._meeting_has_meetings(meeting);
                    var seen = false;
                    if (!meeting.days_tbd && has_meetings) {
                        var start_parts = meeting.start_time.split(":");
                        var start_minutes = parseInt(start_parts[0], 10) * 60 + parseInt(start_parts[1], 10);

                        var end_parts = meeting.end_time.split(":");
                        var end_minutes = parseInt(end_parts[0], 10) * 60 + parseInt(end_parts[1], 10);

                        if (start_minutes < visual_data.earliest_start) {
                            visual_data.earliest_start = start_minutes;
                        }
                        if (end_minutes > visual_data.latest_ending) {
                            visual_data.latest_ending = end_minutes;
                        }

                        var meeting_info = {
                            is_meeting: true,
                            is_instructor: section.is_teaching,
                            start: start_minutes,
                            end: end_minutes,
                            color_id: section.color_id,
                            curriculum: section.curriculum_abbr,
                            course_number: section.course_number,
                            //term: term,
                            section_id: section.section_id,
                            section_index: section_index,
                            building_tbd: meeting.building_tbd,
                            building: meeting.building,
                            building_name: meeting.building_name,
                            room_tbd: meeting.room_tbd,
                            room: meeting.room,
                            latitude: meeting.latitude,
                            longitude: meeting.longitude,
                            early_fall_start: section.early_fall_start,
                            has_early_fall_start: course_data.has_early_fall_start
                        };
                        if(course_data.meets_saturday && course_data.meets_sunday){
                            visual_data.day_class = "seven-day";
                        } else if(course_data.meets_saturday || course_data.meets_sunday){
                            visual_data.day_class = "seven-day";
                        } else {

                        }

                        visual_data.meets_saturday = course_data.meets_saturday;
                        visual_data.meets_sunday = course_data.meets_sunday;

                        $.each(days, function(){
                            day = this.toString();
                            if (meeting.meeting_days[day]) {
                                visual_data[day].push(meeting_info);
                            }
                        });
                    }
                    else {
                        $.each(visual_data.courses_no_meeting, function () {
                            if (this.section_index === section_index) {
                                seen = true;
                                return false;
                            }
                        });

                        // Has no meetings, or TBD (eg individual start PCE courses)
                        if (!seen) {
                            visual_data.courses_no_meeting.push({
                                color_id: section.color_id,
                                curriculum: section.curriculum_abbr,
                                course_number: section.course_number,
                                section_id: section.section_id,
                                section_index: section_index
                            });
                        }
                    }
                });
            });
        };
        var day, day_index, i, height, top;

        if (course_data) {
            set_meeting(course_data);
        }

        // Make it so the start and end times are always on the hour:
        var start_hour = parseInt(visual_data.earliest_start / 60, 10);

        if ((start_hour * 60) === visual_data.earliest_start) {
            visual_data.start_time = (start_hour * 60) - 60;
        }
        else {
            visual_data.start_time = (start_hour * 60);
        }

        var end_hour = parseInt(visual_data.latest_ending / 60, 10) + 1;
        if ((end_hour * 60) === visual_data.latest_ending) {
            visual_data.end_time = (end_hour * 60) - 60;
        }
        else {
            visual_data.end_time = (end_hour * 60);
        }

        i = 0;
        var position_index = 0;
        // We don't want to add the last hour - it's just off the end of the visual schedule
        for (i = visual_data.start_time; i <= visual_data.end_time - 1; i += 60) {
            visual_data.display_hours.push({
                                               hour: (i / 60),
                                               position: i,
                                               hour_count: position_index
                                           });
            position_index += 1;
        }

        visual_data.total_hours = (visual_data.end_time - visual_data.start_time) / 60;

        var hours_count = parseInt((visual_data.end_time - visual_data.start_time) / 60, 0);
        if (hours_count <= 6) {
            visual_data.schedule_hours_class = "six-hour";
        }
        else if (hours_count <= 12) {
            visual_data.schedule_hours_class = "twelve-hour";
        }
        else {
            visual_data.schedule_hours_class = "twelve-plus";
        }

        for (day_index = 0; day_index < days.length; day_index++) {
            day = days[day_index];
            i = 0;
            while (i < visual_data[day].length) {

                top = VisualScheduleCard.get_scaled_percentage(visual_data[day][i].start, visual_data.start_time, visual_data.end_time);
                height =  VisualScheduleCard.get_scaled_percentage(visual_data[day][i].end, visual_data.start_time, visual_data.end_time) - top;
                visual_data[day][i].top=top;
                visual_data[day][i].height=height;
                i += 1;
            }

            var start_at_hr = true;
            var position_start = visual_data.start_time;
            while (position_start < visual_data.end_time) {
                var position_end = position_start + 30;
                top = VisualScheduleCard.get_scaled_percentage(position_start, visual_data.start_time, visual_data.end_time);
                height =  VisualScheduleCard.get_scaled_percentage(position_end, visual_data.start_time, visual_data.end_time) - top;
                visual_data[day].push({
                                          is_meeting: false,
                                          start_at_hr: start_at_hr,
                                          top:top,
                                          height:height,
                                          start: position_start,
                                          end: position_end});
                position_start = position_end;
                start_at_hr = !start_at_hr;
            }
        }
        return visual_data;
    },
    _meeting_has_meetings: function(meeting){
        var has_meeting = false;
        $.each(meeting.meeting_days, function (idx, meeting) {
            if (meeting !== null){
                has_meeting = true;
            }
        });
        return has_meeting;
    },
    get_scaled_percentage: function(pos, min, max) {
        var base_percentage = (pos - min) / (max - min);
        var offset_percentage = (VisualScheduleCard.day_label_offset * 2) + (base_percentage * (100 - (VisualScheduleCard.day_label_offset * 2)));

        // The second one is for positioning the last hour label.
        return offset_percentage - VisualScheduleCard.day_label_offset;
    },
    add_events: function(term) {
        $(".show_visual_map").on("click", function(ev) {
            var building_name = ev.currentTarget.getAttribute("rel");
            building_name = building_name.replace(/[^a-z0-9]/gi, '_');
            var building = ev.currentTarget.getAttribute("rel");
            building = building.replace(/[^a-z0-9]/gi, '_');
            WSData.log_interaction("show_map_from_visual_card_"+building, term);
        });

        $("a.schedule-period-anchor").on("click", function(ev){
            var period_id = $(this).attr('data-period_id');
            VisualScheduleCard.display_schedule_for_period(period_id);
            return false;
        });
    },

    render_schedule: function(data){
        // Add in off_term data
        var schedule_data = WSData.visual_schedule_data(VisualScheduleCard.term);
        data.off_term_trimmed = schedule_data.off_term_trimmed;
        var source = $("#visual_schedule_card_content").html();
        var template = Handlebars.compile(source);
        var t = template(data);
        VisualScheduleCard.dom_target.html(t);
        VisualScheduleCard.add_events();

    },

    display_schedule_for_period: function(period_id){
        var schedule_data = WSData.visual_schedule_data(VisualScheduleCard.term),
            period,
            processed_period;

        if(period_id === "finals"){
            // Render VS with first period data to get correct labels
            processed_period = VisualScheduleCard._get_processed_data_for_period(0);
            processed_period.active_period_id = period_id;
            if (VisualScheduleCard._get_finals_period(schedule_data.periods) !== undefined){
                processed_period.sr_finals = VisualScheduleCard._get_finals_period(schedule_data.periods).sections;
            }
            VisualScheduleCard.render_schedule(processed_period);

            period = VisualScheduleCard._get_finals_period(schedule_data.periods);
            var target = $("#schedule_area").first();
            FinalExamSchedule.render(period, schedule_data.term, false, target);
        } else {
            processed_period = VisualScheduleCard._get_processed_data_for_period(period_id);
            processed_period.active_period_id = String(period_id);

            if (VisualScheduleCard._get_finals_period(schedule_data.periods) !== undefined){
                processed_period.sr_finals = VisualScheduleCard._get_finals_period(schedule_data.periods).sections;
            }
            VisualScheduleCard.render_schedule(processed_period);
        }
        LogUtils.cardLoaded(VisualScheduleCard.name, VisualScheduleCard.dom_target);
    },

    _get_processed_data_for_period: function(period_id){
        var schedule_data = WSData.visual_schedule_data(VisualScheduleCard.term),
            period = schedule_data.periods[period_id];
        var processed_period = VisualScheduleCard._get_data_for_period(period, schedule_data.term);
        var period_labels = VisualScheduleCard._get_period_lables(schedule_data);
        processed_period.schedule_periods = period_labels;
        processed_period.show_period_headers = Object.keys(period_labels).length > 1;
        processed_period.active_period_id = period_id;
        return processed_period;
    },

    _get_finals_period: function(periods){
        var finals_period;
        $(periods).each(function(idx, period){
            if (period.id === "finals"){
                finals_period = period;
            }
        });
        return finals_period;
    },

    _get_default_period: function(periods){
        var today = moment.utc(window.card_display_dates.comparison_date, "YYYY-MM-DD"),
            default_period,
            i;
        $.each(periods, function(idx, period){
            if (moment.utc(period.start_date, "YYYY-MM-DD").isSameOrBefore(today) &&
                            moment.utc(period.end_date, "YYYY-MM-DD").isSameOrAfter(today)){
                default_period = period.id;
            }
        });

        // Case where current date falls between weeks, pick closest future week
        if (default_period === undefined){
            $.each(periods, function(idx, period){
                if (moment.utc(period.end_date, "YYYY-MM-DD").isBefore(today)){
                    if(periods[idx + 1] !== undefined){
                        if(moment.utc(periods[idx + 1].start_date, "YYYY-MM-DD").isAfter(today)){
                            default_period = period.id + 1;
                        }
                    }

                }
            });
        }

        // Default to first period if no match
        if (default_period === undefined){
            default_period = Object.keys(periods)[0];
        }

        return default_period;
    }

};

/* node.js exports */
if (typeof exports === "undefined") {
    var exports = {};
}
exports.VisualScheduleCard = VisualScheduleCard;
<commit_msg>fixing issue with false meetings<commit_after>var VisualScheduleCard = {
    name: 'VisualScheduleCard',
    dom_target: undefined,
    term: 'current',
    ck_student_schedule: false,
    ck_instructor_schedule: false,
    day_label_offset: 0,

    should_hide: function() {
        if (window.user.student || window.user.instructor) {
            return false;
        }
        return true;
    },

    render_init: function(term, course_index) {
        if (VisualScheduleCard.should_hide()) {
            VisualScheduleCard.hide_card();
            return;
        }
        WSData.fetch_visual_schedule_term(VisualScheduleCard.term,
                                          VisualScheduleCard.render_handler,
                                          VisualScheduleCard.render_handler);
    },

    hide_card: function(){
        $("#VisualScheduleCard").hide();
    },

    render_handler: function() {
        var schedule_data = WSData.visual_schedule_data(VisualScheduleCard.term);
        if (schedule_data === undefined){
            VisualScheduleCard.hide_card();
            return;
        }
        var default_period = VisualScheduleCard._get_default_period(schedule_data.periods);

        VisualScheduleCard.display_schedule_for_period(default_period);
    },

    _render_error: function() {
        VisualScheduleCard.hide_card();
    },

    _get_period_lables: function(schedule_data){
        var periods = {};
        $(schedule_data.periods).each(function(idx, period){
            periods[period.id] = {'start_date': period.start_date,
                'end_date': period.end_date};
        });
        return periods;
    },

    _get_data_for_period: function(course_data, term){
        var days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
        var visual_data = {
            //has_early_fall_start: ((course_data && course_data.has_early_fall_start) ||
            //                       (instructed_course_data &&
            //                        instructed_course_data.has_early_fall_start)),
            is_pce: window.user.pce,
            total_sections: course_data.sections.length,
            quarter: term.quarter,
            year: term.year,
            summer_term: term.summer_term,
            latest_ending: 0,
            earliest_start: 24*60,
            monday: [],
            tuesday: [],
            wednesday: [],
            thursday: [],
            friday: [],
            saturday: [],
            sunday: [],
            display_hours: [],
            day_class: "five-day",
            courses_meeting_tbd: [],
            courses_no_meeting: [],
            meets_saturday: false,
            meets_sunday: false,
            disabled_days: course_data.disabled_days
        };

        var set_meeting = function(course_data) {
            $.each(course_data.sections, function(section_index) {
                var section = this;
                $.each(section.meetings, function(){
                    var meeting = this;
                    var has_meetings = VisualScheduleCard._meeting_has_meetings(meeting);
                    var seen = false;
                    if (!meeting.days_tbd && has_meetings) {
                        var start_parts = meeting.start_time.split(":");
                        var start_minutes = parseInt(start_parts[0], 10) * 60 + parseInt(start_parts[1], 10);

                        var end_parts = meeting.end_time.split(":");
                        var end_minutes = parseInt(end_parts[0], 10) * 60 + parseInt(end_parts[1], 10);

                        if (start_minutes < visual_data.earliest_start) {
                            visual_data.earliest_start = start_minutes;
                        }
                        if (end_minutes > visual_data.latest_ending) {
                            visual_data.latest_ending = end_minutes;
                        }

                        var meeting_info = {
                            is_meeting: true,
                            is_instructor: section.is_teaching,
                            start: start_minutes,
                            end: end_minutes,
                            color_id: section.color_id,
                            curriculum: section.curriculum_abbr,
                            course_number: section.course_number,
                            //term: term,
                            section_id: section.section_id,
                            section_index: section_index,
                            building_tbd: meeting.building_tbd,
                            building: meeting.building,
                            building_name: meeting.building_name,
                            room_tbd: meeting.room_tbd,
                            room: meeting.room,
                            latitude: meeting.latitude,
                            longitude: meeting.longitude,
                            early_fall_start: section.early_fall_start,
                            has_early_fall_start: course_data.has_early_fall_start
                        };
                        if(course_data.meets_saturday && course_data.meets_sunday){
                            visual_data.day_class = "seven-day";
                        } else if(course_data.meets_saturday || course_data.meets_sunday){
                            visual_data.day_class = "seven-day";
                        } else {

                        }

                        visual_data.meets_saturday = course_data.meets_saturday;
                        visual_data.meets_sunday = course_data.meets_sunday;

                        $.each(days, function(){
                            day = this.toString();
                            if (meeting.meeting_days[day]) {
                                visual_data[day].push(meeting_info);
                            }
                        });
                    }
                    else {
                        $.each(visual_data.courses_no_meeting, function () {
                            if (this.section_index === section_index) {
                                seen = true;
                                return false;
                            }
                        });

                        // Has no meetings, or TBD (eg individual start PCE courses)
                        if (!seen) {
                            visual_data.courses_no_meeting.push({
                                color_id: section.color_id,
                                curriculum: section.curriculum_abbr,
                                course_number: section.course_number,
                                section_id: section.section_id,
                                section_index: section_index
                            });
                        }
                    }
                });
            });
        };
        var day, day_index, i, height, top;

        if (course_data) {
            set_meeting(course_data);
        }

        // Make it so the start and end times are always on the hour:
        var start_hour = parseInt(visual_data.earliest_start / 60, 10);

        if ((start_hour * 60) === visual_data.earliest_start) {
            visual_data.start_time = (start_hour * 60) - 60;
        }
        else {
            visual_data.start_time = (start_hour * 60);
        }

        var end_hour = parseInt(visual_data.latest_ending / 60, 10) + 1;
        if ((end_hour * 60) === visual_data.latest_ending) {
            visual_data.end_time = (end_hour * 60) - 60;
        }
        else {
            visual_data.end_time = (end_hour * 60);
        }

        i = 0;
        var position_index = 0;
        // We don't want to add the last hour - it's just off the end of the visual schedule
        for (i = visual_data.start_time; i <= visual_data.end_time - 1; i += 60) {
            visual_data.display_hours.push({
                                               hour: (i / 60),
                                               position: i,
                                               hour_count: position_index
                                           });
            position_index += 1;
        }

        visual_data.total_hours = (visual_data.end_time - visual_data.start_time) / 60;

        var hours_count = parseInt((visual_data.end_time - visual_data.start_time) / 60, 0);
        if (hours_count <= 6) {
            visual_data.schedule_hours_class = "six-hour";
        }
        else if (hours_count <= 12) {
            visual_data.schedule_hours_class = "twelve-hour";
        }
        else {
            visual_data.schedule_hours_class = "twelve-plus";
        }

        for (day_index = 0; day_index < days.length; day_index++) {
            day = days[day_index];
            i = 0;
            while (i < visual_data[day].length) {

                top = VisualScheduleCard.get_scaled_percentage(visual_data[day][i].start, visual_data.start_time, visual_data.end_time);
                height =  VisualScheduleCard.get_scaled_percentage(visual_data[day][i].end, visual_data.start_time, visual_data.end_time) - top;
                visual_data[day][i].top=top;
                visual_data[day][i].height=height;
                i += 1;
            }

            var start_at_hr = true;
            var position_start = visual_data.start_time;
            while (position_start < visual_data.end_time) {
                var position_end = position_start + 30;
                top = VisualScheduleCard.get_scaled_percentage(position_start, visual_data.start_time, visual_data.end_time);
                height =  VisualScheduleCard.get_scaled_percentage(position_end, visual_data.start_time, visual_data.end_time) - top;
                visual_data[day].push({
                                          is_meeting: false,
                                          start_at_hr: start_at_hr,
                                          top:top,
                                          height:height,
                                          start: position_start,
                                          end: position_end});
                position_start = position_end;
                start_at_hr = !start_at_hr;
            }
        }
        return visual_data;
    },
    _meeting_has_meetings: function(meeting){
        var has_meeting = false;
        $.each(meeting.meeting_days, function (idx, meeting) {
            if (meeting !== null && meeting !== false){
                has_meeting = true;
            }
        });
        return has_meeting;
    },
    get_scaled_percentage: function(pos, min, max) {
        var base_percentage = (pos - min) / (max - min);
        var offset_percentage = (VisualScheduleCard.day_label_offset * 2) + (base_percentage * (100 - (VisualScheduleCard.day_label_offset * 2)));

        // The second one is for positioning the last hour label.
        return offset_percentage - VisualScheduleCard.day_label_offset;
    },
    add_events: function(term) {
        $(".show_visual_map").on("click", function(ev) {
            var building_name = ev.currentTarget.getAttribute("rel");
            building_name = building_name.replace(/[^a-z0-9]/gi, '_');
            var building = ev.currentTarget.getAttribute("rel");
            building = building.replace(/[^a-z0-9]/gi, '_');
            WSData.log_interaction("show_map_from_visual_card_"+building, term);
        });

        $("a.schedule-period-anchor").on("click", function(ev){
            var period_id = $(this).attr('data-period_id');
            VisualScheduleCard.display_schedule_for_period(period_id);
            return false;
        });
    },

    render_schedule: function(data){
        // Add in off_term data
        var schedule_data = WSData.visual_schedule_data(VisualScheduleCard.term);
        data.off_term_trimmed = schedule_data.off_term_trimmed;
        var source = $("#visual_schedule_card_content").html();
        var template = Handlebars.compile(source);
        var t = template(data);
        VisualScheduleCard.dom_target.html(t);
        VisualScheduleCard.add_events();

    },

    display_schedule_for_period: function(period_id){
        var schedule_data = WSData.visual_schedule_data(VisualScheduleCard.term),
            period,
            processed_period;

        if(period_id === "finals"){
            // Render VS with first period data to get correct labels
            processed_period = VisualScheduleCard._get_processed_data_for_period(0);
            processed_period.active_period_id = period_id;
            if (VisualScheduleCard._get_finals_period(schedule_data.periods) !== undefined){
                processed_period.sr_finals = VisualScheduleCard._get_finals_period(schedule_data.periods).sections;
            }
            VisualScheduleCard.render_schedule(processed_period);

            period = VisualScheduleCard._get_finals_period(schedule_data.periods);
            var target = $("#schedule_area").first();
            FinalExamSchedule.render(period, schedule_data.term, false, target);
        } else {
            processed_period = VisualScheduleCard._get_processed_data_for_period(period_id);
            processed_period.active_period_id = String(period_id);

            if (VisualScheduleCard._get_finals_period(schedule_data.periods) !== undefined){
                processed_period.sr_finals = VisualScheduleCard._get_finals_period(schedule_data.periods).sections;
            }
            VisualScheduleCard.render_schedule(processed_period);
        }
        LogUtils.cardLoaded(VisualScheduleCard.name, VisualScheduleCard.dom_target);
    },

    _get_processed_data_for_period: function(period_id){
        var schedule_data = WSData.visual_schedule_data(VisualScheduleCard.term),
            period = schedule_data.periods[period_id];
        var processed_period = VisualScheduleCard._get_data_for_period(period, schedule_data.term);
        var period_labels = VisualScheduleCard._get_period_lables(schedule_data);
        processed_period.schedule_periods = period_labels;
        processed_period.show_period_headers = Object.keys(period_labels).length > 1;
        processed_period.active_period_id = period_id;
        return processed_period;
    },

    _get_finals_period: function(periods){
        var finals_period;
        $(periods).each(function(idx, period){
            if (period.id === "finals"){
                finals_period = period;
            }
        });
        return finals_period;
    },

    _get_default_period: function(periods){
        var today = moment.utc(window.card_display_dates.comparison_date, "YYYY-MM-DD"),
            default_period,
            i;
        $.each(periods, function(idx, period){
            if (moment.utc(period.start_date, "YYYY-MM-DD").isSameOrBefore(today) &&
                            moment.utc(period.end_date, "YYYY-MM-DD").isSameOrAfter(today)){
                default_period = period.id;
            }
        });

        // Case where current date falls between weeks, pick closest future week
        if (default_period === undefined){
            $.each(periods, function(idx, period){
                if (moment.utc(period.end_date, "YYYY-MM-DD").isBefore(today)){
                    if(periods[idx + 1] !== undefined){
                        if(moment.utc(periods[idx + 1].start_date, "YYYY-MM-DD").isAfter(today)){
                            default_period = period.id + 1;
                        }
                    }

                }
            });
        }

        // Default to first period if no match
        if (default_period === undefined){
            default_period = Object.keys(periods)[0];
        }

        return default_period;
    }

};

/* node.js exports */
if (typeof exports === "undefined") {
    var exports = {};
}
exports.VisualScheduleCard = VisualScheduleCard;
<|endoftext|>


<commit_before>/*eslint-disable */
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var config = require('../webpack.dev.config')
var app = express()
var compiler = webpack(config)

// Development Middleware
app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}))
app.use(require('webpack-hot-middleware')(compiler))

// Main entry for app
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'dev.html'))
})

// Assets
app.use(express.static('public/assets'))

// Catchall for any requests like /onboarding
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'dev.html'))
})

app.listen(6660, 'localhost', function(err) {
  if (err) {
    console.log(err)
    return
  }
  console.log('Listening at http://localhost:6660')
})
<commit_msg>Move static asset middleware up a few notches<commit_after>/*eslint-disable */
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var config = require('../webpack.dev.config')
var app = express()
var compiler = webpack(config)

// Development Middleware
app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}))
app.use(require('webpack-hot-middleware')(compiler))

// Assets
app.use(express.static('public/assets'))

// Main entry for app
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'dev.html'))
})

// Catchall for any requests like /onboarding
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'dev.html'))
})

app.listen(6660, 'localhost', function(err) {
  if (err) {
    console.log(err)
    return
  }
  console.log('Listening at http://localhost:6660')
})
<|endoftext|>


<commit_before>const Application = require("spectron").Application;
const chai = require('chai');
const should = chai.should();
const chaiAsPromised = require('chai-as-promised');
const testPage = require('./test.page.js');

var page = new testPage();
var path = require('path');

var electronPath = path.join(__dirname, '..', 'node_modules', '.bin', 'electron.cmd');

if (process.platform === 'win32') {
    electronPath += '.cmd';
}

// Path to your application
var appPath = path.join(__dirname, '..');

var app = new Application({
            path: electronPath,
            args: [appPath]
        });

global.before(function () {
    //chai.should();
    chai.use(chaiAsPromised);
    page.setApp(app);
});

describe('Test Example', function () {
    beforeEach(function () {
        return app.start();
    });

    afterEach(function () {
        return app.stop();
    });

    it('should fail, yes == no ', function () {
        chai.expect("yes").to.equal("no");
    });

    it('should succeed, yes == yes', function () {
        chai.expect("yes").to.equal("yes");
    });

    it('should fail, yes != no', function () {
        function fn() {
            var yes = 'yes';
            yes.should.equal('no');
        }
        fn();
    });

    it('should fail, pass in text', function () {
        function fn(txt) {
            var yes = 'yes';
            yes.should.equal(txt);
        }
        fn("no");
    });

    it('should fail, waitUntilWindowLoaded, yes != no', function () {
        app.client.waitUntilWindowLoaded().getTitle().then(
            function (txt) {
                console.log('txt = ' + txt);
                var yes = 'yes';
                yes.should.equal('no');
            }
        );
    });

    it('should succeed, tests the not NOT title', function () {
        return app.client.waitUntilWindowLoaded().getTitle().then(function (txt) { chai.expect(txt).to.not.equal("NOT" + page.pageTitle); });
    });

    it('should fail, tests the NOT title', function () {
        return app.client.waitUntilWindowLoaded().getTitle().then(function (txt) { chai.expect(txt).to.equal("NOT" + page.pageTitle); });
    });

    it('should succeed, tests the page title', function () {
        return page.getApplicationTitle().should.eventually.equal(page.pageTitle);
    });

    it('should fail, tests the NOT page title', function () {
        return page.getApplicationTitle().should.eventually.not.equal("NOT" + page.pageTitle);
    });

    it('should fail, tests the NOT page title', function () {
        return page.getApplicationTitle().should.eventually.equal("NOT" + page.pageTitle);
    });

    it('should succeed, tests window open count', function () {
        app.client.debug();
        return page.getWindowCount().should.eventually.equal(page.windowCount);
    });

    it('should fail, tests window open count', function () {
        app.client.debug();
        return page.getWindowCount().should.eventually.equal(page.windowCount + 1);
    });

    it('should succeed, clicks the button', function () {
        return page.clickButtonAndGetText().should.eventually.equal(page.helloText);
    });

    it('should fail, clicks the button', function () {
        return page.clickButtonAndGetText().should.eventually.equal("NOT" + page.helloText);
    });
});
<commit_msg>fix build<commit_after>const Application = require("spectron").Application;
const chai = require('chai');
const should = chai.should();
const chaiAsPromised = require('chai-as-promised');
const testPage = require('./test.page.js');

var page = new testPage();
let path = require('path');

var electronPath = path.join(__dirname, '..', 'node_modules', '.bin', 'electron.cmd');

if (process.platform === 'win32') {
    electronPath += '.cmd';
}

// Path to your application
var appPath = path.join(__dirname, '..');

var app = new Application({
            path: electronPath,
            args: [appPath]
        });

global.before(function () {
    //chai.should();
    chai.use(chaiAsPromised);
    page.setApp(app);
});

describe('Test Example', function () {
    beforeEach(function () {
        return app.start();
    });

    afterEach(function () {
        return app.stop();
    });

    it('should fail, yes == no ', function () {
        chai.expect("yes").to.equal("no");
    });

    it('should succeed, yes == yes', function () {
        chai.expect("yes").to.equal("yes");
    });

    it('should fail, yes != no', function () {
        function fn() {
            var yes = 'yes';
            yes.should.equal('no');
        }
        fn();
    });

    it('should fail, pass in text', function () {
        function fn(txt) {
            var yes = 'yes';
            yes.should.equal(txt);
        }
        fn("no");
    });

    it('should fail, waitUntilWindowLoaded, yes != no', function () {
        app.client.waitUntilWindowLoaded().getTitle().then(
            function (txt) {
                console.log('txt = ' + txt);
                var yes = 'yes';
                yes.should.equal('no');
            }
        );
    });

    it('should succeed, tests the not NOT title', function () {
        return app.client.waitUntilWindowLoaded().getTitle().then(function (txt) { chai.expect(txt).to.not.equal("NOT" + page.pageTitle); });
    });

    it('should fail, tests the NOT title', function () {
        return app.client.waitUntilWindowLoaded().getTitle().then(function (txt) { chai.expect(txt).to.equal("NOT" + page.pageTitle); });
    });

    it('should succeed, tests the page title', function () {
        return page.getApplicationTitle().should.eventually.equal(page.pageTitle);
    });

    it('should fail, tests the NOT page title', function () {
        return page.getApplicationTitle().should.eventually.not.equal("NOT" + page.pageTitle);
    });

    it('should fail, tests the NOT page title', function () {
        return page.getApplicationTitle().should.eventually.equal("NOT" + page.pageTitle);
    });

    it('should succeed, tests window open count', function () {
        app.client.debug();
        return page.getWindowCount().should.eventually.equal(page.windowCount);
    });

    it('should fail, tests window open count', function () {
        app.client.debug();
        return page.getWindowCount().should.eventually.equal(page.windowCount + 1);
    });

    it('should succeed, clicks the button', function () {
        return page.clickButtonAndGetText().should.eventually.equal(page.helloText);
    });

    it('should fail, clicks the button', function () {
        return page.clickButtonAndGetText().should.eventually.equal("NOT" + page.helloText);
    });
});
<|endoftext|>


<commit_before>'use babel';

import {CompositeDisposable} from 'atom';
import Comb from 'csscomb';
import path from 'path';

export default {
    config: {
        projectConfigs: {
            title: 'Use project config',
            description: 'Relative to the project directory. Example: `.csscomb.json` or `configs/.csscomb.json`. Leave blank if you want to use the following setting',
            default: '',
            type: 'string'
        },
        commonConfigs: {
            title: 'Use common config',
            description: 'Put here a full path to your config. Example: `/Users/jchouse/propjects/.csscomb.json`. Leave blank if you want to use the following setting',
            default: '',
            type: 'string'
        },
        readyMadeConfigs: {
            title: 'Ready made configs',
            description: 'Used when you do not specify a project or common file. The details below.',
            type: 'string',
            default: 'yandex',
            enum: ['yandex', 'csscomb', 'zen']
        },
		runOnSave: {
			title: 'Run on save',
            description: 'Format your files everytime you save',
            default: false,
            type: 'boolean'
		}
    },

    subscriptions: new CompositeDisposable(),

    getSettingsConfig() {
        var cssCombPackage = atom.packages.getLoadedPackage('atom-css-comb'),
            error,
            optionsFilePath,
            projectConfigs = atom.config.get('atom-css-comb.projectConfigs'),
            projectPath = atom.project.getPaths()[0],
            commonConfigs = atom.config.get('atom-css-comb.commonConfigs'),
            readyMadeConfigs = atom.config.get('atom-css-comb.readyMadeConfigs');

        if (projectConfigs) {
            optionsFilePath = path.join(projectPath, projectConfigs);
            try {
                return require(optionsFilePath);
            } catch (error) {
                return error;
            }
        } else if (commonConfigs) {
            try {
                return require(commonConfigs);
            } catch (error) {
                return error;
            }
        } else {
            return readyMadeConfigs || 'yandex';
        }
    },

    activate() {
        this.subscriptions.add(atom.commands.add('atom-workspace', {
          'css-comb:comb': () => this.comb()
        }));

		this.observeSave();
    },

    destroy() {
        this.subscriptions.dispose();
    },

    combFile(comb, syntax) {
        const text = this._getText();

        comb.processString(text, {syntax: syntax})
            .then(combed => atom.workspace.getActivePaneItem().setText(combed))
            .catch(error => atom.notifications.addError(error.message));
    },

    combText(comb, text) {
        var combed,
            syntax = this._getSytax(),
            activePane = atom.workspace.getActivePaneItem();

        comb.processString(text, {syntax: syntax})
            .then(result => activePane.setTextInBufferRange(activePane.getSelectedBufferRange(), result))
            .catch(error => atom.notifications.addError(error.message));
    },

	observeSave () {
        this.subscriptions.add(atom.workspace.observeTextEditors(editor => {
            this.subscriptions.add(editor.getBuffer().onWillSave(() => {
                var runOnSave = atom.config.get('atom-css-comb.runOnSave');
				var syntax = this._getSytax();
				if (!(syntax instanceof Error) && runOnSave) {
					this.comb();
				}
            }));
        }));
    },

    _getSytax() {
        var syntax = atom.workspace.getActiveTextEditor().getGrammar().name.toLowerCase();

        if (['css', 'less', 'sass', 'scss'].indexOf(syntax) !== -1) {
            return syntax;
        } else if (syntax === 'html' || syntax === 'postcss') {
            return 'css';
        } else {
            return new Error();
        }
    },

    _getSelectedText() {
        return atom.workspace.getActiveTextEditor().getSelectedText();
    },

    _getText() {
        return atom.workspace.getActiveTextEditor().getText();
    },

    comb() {
        var comb,
            config = this.getSettingsConfig(),
            selectedText = this._getSelectedText(),
            syntax = this._getSytax();

        if (config instanceof Error) {
            return atom.notifications.addError(config.message);
        } else if (syntax instanceof Error) {
            return atom.notifications.addError('Not supported syntax');
        } else {
            comb = new Comb(config);

            if (selectedText !== '') {
                this.combText(comb, selectedText, syntax);
            } else {
                let _name = atom.workspace.getActiveTextEditor().getGrammar().name;
                if (syntax === 'css' && _name === 'HTML') {
                    atom.notifications.addError('Please select the text for combing.');
                    return;
                }
                this.combFile(comb, syntax);
            }
        }
    }
};
<commit_msg>Add postcss syntax support<commit_after>'use babel';

import {CompositeDisposable} from 'atom';
import Comb from 'csscomb';
import path from 'path';

export default {
    config: {
        projectConfigs: {
            title: 'Use project config',
            description: 'Relative to the project directory. Example: `.csscomb.json` or `configs/.csscomb.json`. Leave blank if you want to use the following setting',
            default: '',
            type: 'string'
        },
        commonConfigs: {
            title: 'Use common config',
            description: 'Put here a full path to your config. Example: `/Users/jchouse/propjects/.csscomb.json`. Leave blank if you want to use the following setting',
            default: '',
            type: 'string'
        },
        readyMadeConfigs: {
            title: 'Ready made configs',
            description: 'Used when you do not specify a project or common file. The details below.',
            type: 'string',
            default: 'yandex',
            enum: ['yandex', 'csscomb', 'zen']
        },
		runOnSave: {
			title: 'Run on save',
            description: 'Format your files everytime you save',
            default: false,
            type: 'boolean'
		}
    },

    subscriptions: new CompositeDisposable(),

    getSettingsConfig() {
        var cssCombPackage = atom.packages.getLoadedPackage('atom-css-comb'),
            error,
            optionsFilePath,
            projectConfigs = atom.config.get('atom-css-comb.projectConfigs'),
            projectPath = atom.project.getPaths()[0],
            commonConfigs = atom.config.get('atom-css-comb.commonConfigs'),
            readyMadeConfigs = atom.config.get('atom-css-comb.readyMadeConfigs');

        if (projectConfigs) {
            optionsFilePath = path.join(projectPath, projectConfigs);
            try {
                return require(optionsFilePath);
            } catch (error) {
                return error;
            }
        } else if (commonConfigs) {
            try {
                return require(commonConfigs);
            } catch (error) {
                return error;
            }
        } else {
            return readyMadeConfigs || 'yandex';
        }
    },

    activate() {
        this.subscriptions.add(atom.commands.add('atom-workspace', {
          'css-comb:comb': () => this.comb()
        }));

		this.observeSave();
    },

    destroy() {
        this.subscriptions.dispose();
    },

    combFile(comb, syntax) {
        const text = this._getText();

        comb.processString(text, {syntax: syntax})
            .then(combed => atom.workspace.getActivePaneItem().setText(combed))
            .catch(error => atom.notifications.addError(error.message));
    },

    combText(comb, text) {
        var combed,
            syntax = this._getSytax(),
            activePane = atom.workspace.getActivePaneItem();

        comb.processString(text, {syntax: syntax})
            .then(result => activePane.setTextInBufferRange(activePane.getSelectedBufferRange(), result))
            .catch(error => atom.notifications.addError(error.message));
    },

	observeSave () {
        this.subscriptions.add(atom.workspace.observeTextEditors(editor => {
            this.subscriptions.add(editor.getBuffer().onWillSave(() => {
                var runOnSave = atom.config.get('atom-css-comb.runOnSave');
				var syntax = this._getSytax();
				if (!(syntax instanceof Error) && runOnSave) {
					this.comb();
				}
            }));
        }));
    },

    _getSytax() {
        var syntax = atom.workspace.getActiveTextEditor().getGrammar().name.toLowerCase();

        if (['css', 'less', 'sass', 'scss'].includes(syntax)) {
            return syntax;
        } else if ['html', 'postcss'].includes(syntax) {
            return 'css';
        } else {
            return new Error();
        }
    },

    _getSelectedText() {
        return atom.workspace.getActiveTextEditor().getSelectedText();
    },

    _getText() {
        return atom.workspace.getActiveTextEditor().getText();
    },

    comb() {
        var comb,
            config = this.getSettingsConfig(),
            selectedText = this._getSelectedText(),
            syntax = this._getSytax();

        if (config instanceof Error) {
            return atom.notifications.addError(config.message);
        } else if (syntax instanceof Error) {
            return atom.notifications.addError('Not supported syntax');
        } else {
            comb = new Comb(config);

            if (selectedText !== '') {
                this.combText(comb, selectedText, syntax);
            } else {
                let _name = atom.workspace.getActiveTextEditor().getGrammar().name;
                if (syntax === 'css' && _name === 'HTML') {
                    atom.notifications.addError('Please select the text for combing.');
                    return;
                }
                this.combFile(comb, syntax);
            }
        }
    }
};
<|endoftext|>