<commit_before>/** @babel */

import path from 'path'

import {CompositeDisposable, Disposable, File} from 'atom'

import React from 'react'
import ReactDom from 'react-dom'

import EtchWrapper from '../views/etch-wrapper'
import StatusBar from '../views/status-bar'
import Panel from '../views/panel'
import PaneItem from '../views/pane-item'
import FilePatchController from './file-patch-controller'
import GitPanelController from './git-panel-controller'
import StatusBarTileController from './status-bar-tile-controller'
import ModelObserver from '../models/model-observer'

const nullFilePatchState = {
  filePath: null,
  filePatch: null,
  stagingStatus: null,
  amending: null,
}

export default class GitController extends React.Component {
  static propTypes = {
    workspace: React.PropTypes.object.isRequired,
    commandRegistry: React.PropTypes.object.isRequired,
    notificationManager: React.PropTypes.object.isRequired,
    repository: React.PropTypes.object,
    statusBar: React.PropTypes.object,
    savedState: React.PropTypes.object,
  }

  static defaultProps = {
    savedState: {},
  }

  serialize () {
    return {
      gitPanelActive: this.state.gitPanelActive
    }
  }

  constructor (props, context) {
    super(props, context)
    this.state = {
      ...nullFilePatchState,
      gitPanelActive: !!props.savedState.gitPanelActive,
    }

    this.showFilePatchForPath = this.showFilePatchForPath.bind(this)
    this.showMergeConflictFileForPath = this.showMergeConflictFileForPath.bind(this)
    this.didChangeAmending = this.didChangeAmending.bind(this)
    this.onRepoRefresh = this.onRepoRefresh.bind(this)
    this.toggleGitPanel = this.toggleGitPanel.bind(this)
    this.openAndFocusGitPanel = this.openAndFocusGitPanel.bind(this)
    this.focusFilePatchView = this.focusFilePatchView.bind(this)
    this.focusGitPanel = this.focusGitPanel.bind(this)
    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(
      props.commandRegistry.add('atom-workspace', {
        'git:toggle-git-panel': this.toggleGitPanel.bind(this),
        'git:focus-git-panel': this.openAndFocusGitPanel.bind(this),
      })
    )

    this.repositoryObserver = new ModelObserver({
      didUpdate: () => this.onRepoRefresh()
    })
    this.repositoryObserver.setActiveModel(props.repository)
    this.subscriptions.add(
      new Disposable(() => this.repositoryObserver.destroy())
    )
  }

  componentWillReceiveProps(newProps) {
    this.repositoryObserver.setActiveModel(newProps.repository)
  }

  render () {
    return (

        {this.renderStatusBarTile()}
        {this.renderGitPanel()}
        {(this.state.filePath && this.state.filePatch) ? this.renderFilePatchController() : null}

    )
  }

  renderStatusBarTile () {
    return (
      <StatusBar statusBar={this.props.statusBar} onConsumeStatusBar={(sb) => this.onConsumeStatusBar(sb)}>
        <EtchWrapper type="span">
          <StatusBarTileController
            workspace={this.props.workspace}
            repository={this.props.repository}
            toggleGitPanel={this.toggleGitPanel}
          />
        </EtchWrapper>
      </StatusBar>
    )
  }

  renderGitPanel () {
    return (
      <Panel
        workspace={this.props.workspace}
        location="right"
        getItem={({subtree}) => subtree.getWrappedComponent()}
        onDidClosePanel={() => this.setState({gitPanelActive: false})}
        visible={!!this.state.gitPanelActive}
      >
        <EtchWrapper ref={c => this.gitPanelController = c} reattachDomNode={false}>
          <GitPanelController
            workspace={this.props.workspace}
            commandRegistry={this.props.commandRegistry}
            notificationManager={this.props.notificationManager}
            repository={this.props.repository}
            didSelectFilePath={this.showFilePatchForPath}
            didSelectMergeConflictFile={this.showMergeConflictFileForPath}
            didChangeAmending={this.didChangeAmending}
            focusFilePatchView={this.focusFilePatchView}
          />
        </EtchWrapper>
      </Panel>
    )
  }

  renderFilePatchController () {
    return (
      <PaneItem
        workspace={this.props.workspace}
        getItem={({subtree}) => subtree.getWrappedComponent()}
        ref={c => this.filePatchControllerPane = c}
        onDidCloseItem={() => this.setState({...nullFilePatchState})}
      >
        <EtchWrapper ref={c => this.filePatchController = c} reattachDomNode={false}>
          <FilePatchController
            repository={this.props.repository}
            filePatch={this.state.filePatch}
            stagingStatus={this.state.stagingStatus}
            onRepoRefresh={this.onRepoRefresh}
          />
        </EtchWrapper>
      </PaneItem>
    )
  }

  componentWillUnmount () {
    this.subscriptions.dispose()
  }

  onConsumeStatusBar (statusBar) {
    if (statusBar.disableGitInfoTile) {
      statusBar.disableGitInfoTile()
    }
  }

  async showFilePatchForPath (filePath, stagingStatus, {activate, amending} = {}) {
    if (!filePath) return
    const repository = this.props.repository
    if (!repository) return

    const filePatch = await repository.getFilePatchForPath(filePath, {staged: stagingStatus === 'staged', amending})
    if (filePatch) {
      this.setState({ filePath, filePatch, stagingStatus, amending }, () => {
        // TODO: can be better done w/ a prop?
        if (activate && this.filePatchControllerPane) {
          this.filePatchControllerPane.activate()
        }
      })
    } else {
      this.setState({...nullFilePatchState})
    }
  }

  onRepoRefresh () {
    return this.showFilePatchForPath(this.state.filePath, this.state.stagingStatus, {amending: this.state.amending})
  }

  async showMergeConflictFileForPath (relativeFilePath, {focus} = {}) {
    const absolutePath = path.join(this.props.repository.getWorkingDirectoryPath(), relativeFilePath)
    if (await new File(absolutePath).exists()) {
      return this.props.workspace.open(absolutePath, {activatePane: Boolean(focus), pending: true})
    } else {
      this.props.notificationManager.addInfo('File has been deleted.')
    }
  }

  didChangeAmending (isAmending) {
    return this.showFilePatchForPath(this.state.filePath, this.state.stagingStatus, {amending: isAmending})
  }

  toggleGitPanel () {
    this.setState(state => ({gitPanelActive: !state.gitPanelActive}))
  }

  openAndFocusGitPanel () {
    if (!this.state.gitPanelActive) {
      this.setState({gitPanelActive: true}, () => {
        // TODO: why doesn't a setTimeout of 0 or even 100 work here?
        // Suspect it has to do with the command palette closing...
        setTimeout(() => this.focusGitPanel(), 200)
      })
    } else {
      this.focusGitPanel()
    }
  }

  focusGitPanel () {
    if (this.gitPanelController) {
      this.gitPanelController.getWrappedComponent().focus()
    }
  }

  focusFilePatchView () {
    if (this.filePatchController) {
      this.filePatchController.getWrappedComponent().focus()
    }
  }
}
<commit_msg>¯\(º_o)/¯<commit_after>/** @babel */

import path from 'path'

import {CompositeDisposable, Disposable, File} from 'atom'

import React from 'react'
import ReactDom from 'react-dom'

import EtchWrapper from '../views/etch-wrapper'
import StatusBar from '../views/status-bar'
import Panel from '../views/panel'
import PaneItem from '../views/pane-item'
import FilePatchController from './file-patch-controller'
import GitPanelController from './git-panel-controller'
import StatusBarTileController from './status-bar-tile-controller'
import ModelObserver from '../models/model-observer'

const nullFilePatchState = {
  filePath: null,
  filePatch: null,
  stagingStatus: null,
  amending: null,
}

export default class GitController extends React.Component {
  static propTypes = {
    workspace: React.PropTypes.object.isRequired,
    commandRegistry: React.PropTypes.object.isRequired,
    notificationManager: React.PropTypes.object.isRequired,
    repository: React.PropTypes.object,
    statusBar: React.PropTypes.object,
    savedState: React.PropTypes.object,
  }

  static defaultProps = {
    savedState: {},
  }

  serialize () {
    return {
      gitPanelActive: this.state.gitPanelActive
    }
  }

  constructor (props, context) {
    super(props, context)
    this.state = {
      ...nullFilePatchState,
      gitPanelActive: !!props.savedState.gitPanelActive,
    }

    this.showFilePatchForPath = this.showFilePatchForPath.bind(this)
    this.showMergeConflictFileForPath = this.showMergeConflictFileForPath.bind(this)
    this.didChangeAmending = this.didChangeAmending.bind(this)
    this.onRepoRefresh = this.onRepoRefresh.bind(this)
    this.toggleGitPanel = this.toggleGitPanel.bind(this)
    this.openAndFocusGitPanel = this.openAndFocusGitPanel.bind(this)
    this.focusFilePatchView = this.focusFilePatchView.bind(this)
    this.focusGitPanel = this.focusGitPanel.bind(this)
    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(
      props.commandRegistry.add('atom-workspace', {
        'git:toggle-git-panel': this.toggleGitPanel.bind(this),
        'git:focus-git-panel': this.openAndFocusGitPanel.bind(this),
      })
    )

    this.repositoryObserver = new ModelObserver({
      didUpdate: () => this.onRepoRefresh()
    })
    this.repositoryObserver.setActiveModel(props.repository)
    this.subscriptions.add(
      new Disposable(() => this.repositoryObserver.destroy())
    )
  }

  componentWillReceiveProps(newProps) {
    this.repositoryObserver.setActiveModel(newProps.repository)
  }

  render () {
    return (

        {this.renderStatusBarTile()}
        {this.renderGitPanel()}
        {(this.state.filePath && this.state.filePatch) ? this.renderFilePatchController() : null}

    )
  }

  renderStatusBarTile () {
    return (
      <StatusBar statusBar={this.props.statusBar} onConsumeStatusBar={(sb) => this.onConsumeStatusBar(sb)}>
        <EtchWrapper type="span">
          <StatusBarTileController
            workspace={this.props.workspace}
            repository={this.props.repository}
            toggleGitPanel={this.toggleGitPanel}
          />
        </EtchWrapper>
      </StatusBar>
    )
  }

  renderGitPanel () {
    return (
      <Panel
        workspace={this.props.workspace}
        location="right"
        getItem={({subtree}) => subtree.getWrappedComponent()}
        onDidClosePanel={() => this.setState({gitPanelActive: false})}
        visible={!!this.state.gitPanelActive}
      >
        <EtchWrapper ref={c => this.gitPanelController = c} reattachDomNode={false}>
          <GitPanelController
            workspace={this.props.workspace}
            commandRegistry={this.props.commandRegistry}
            notificationManager={this.props.notificationManager}
            repository={this.props.repository}
            didSelectFilePath={this.showFilePatchForPath}
            didSelectMergeConflictFile={this.showMergeConflictFileForPath}
            didChangeAmending={this.didChangeAmending}
            focusFilePatchView={this.focusFilePatchView}
          />
        </EtchWrapper>
      </Panel>
    )
  }

  renderFilePatchController () {
    return (
      <PaneItem
        workspace={this.props.workspace}
        getItem={({subtree}) => subtree.getWrappedComponent()}
        ref={c => this.filePatchControllerPane = c}
        onDidCloseItem={() => this.setState({...nullFilePatchState})}
      >
        <EtchWrapper ref={c => this.filePatchController = c} reattachDomNode={false}>
          <FilePatchController
            repository={this.props.repository}
            filePatch={this.state.filePatch}
            stagingStatus={this.state.stagingStatus}
            onRepoRefresh={this.onRepoRefresh}
          />
        </EtchWrapper>
      </PaneItem>
    )
  }

  componentWillUnmount () {
    this.subscriptions.dispose()
  }

  onConsumeStatusBar (statusBar) {
    if (statusBar.disableGitInfoTile) {
      statusBar.disableGitInfoTile()
    }
  }

  async showFilePatchForPath (filePath, stagingStatus, {activate, amending} = {}) {
    if (!filePath) return
    const repository = this.props.repository
    if (!repository) return

    const filePatch = await repository.getFilePatchForPath(filePath, {staged: stagingStatus === 'staged', amending})
    if (filePatch) {
      this.setState({ filePath, filePatch, stagingStatus, amending }, () => {
        // TODO: can be better done w/ a prop?
        if (activate && this.filePatchControllerPane) {
          this.filePatchControllerPane.activate()
        }
      })
    } else {
      this.setState({...nullFilePatchState})
    }
  }

  onRepoRefresh () {
    return this.showFilePatchForPath(this.state.filePath, this.state.stagingStatus, {amending: this.state.amending})
  }

  async showMergeConflictFileForPath (relativeFilePath, {focus} = {}) {
    const absolutePath = path.join(this.props.repository.getWorkingDirectoryPath(), relativeFilePath)
    if (await new File(absolutePath).exists()) {
      return this.props.workspace.open(absolutePath, {activatePane: Boolean(focus), pending: true})
    } else {
      this.props.notificationManager.addInfo('File has been deleted.')
    }
  }

  didChangeAmending (isAmending) {
    return this.showFilePatchForPath(this.state.filePath, this.state.stagingStatus, {amending: isAmending})
  }

  toggleGitPanel () {
    this.setState(state => ({gitPanelActive: !state.gitPanelActive}))
  }

  openAndFocusGitPanel () {
    if (!this.state.gitPanelActive) {
      this.setState({gitPanelActive: true}, () => this.focusGitPanel())
    } else {
      this.focusGitPanel()
    }
  }

  focusGitPanel () {
    if (this.gitPanelController) {
      this.gitPanelController.getWrappedComponent().focus()
    }
  }

  focusFilePatchView () {
    if (this.filePatchController) {
      this.filePatchController.getWrappedComponent().focus()
    }
  }
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify  = require('browserify');
var source      = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer      = require('vinyl-buffer');

// build src
gulp.task('browserify', function(cb){
 	return browserify('./src/app.js', {
            debug: true
        })
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./www/'));

    cb();
});

// build:release
gulp.task('browserify:release', function(cb){

 	return browserify('./src/app.js')
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest('./www/'));

    cb();
});

gulp.task('fonts', function(cb){
 	return gulp.src('node_modules/ionic-framework/release/fonts/**')
        .pipe(gulp.dest('./www/fonts/'));
    cb();
});

gulp.task('assets', function(cb){
 	return gulp.src('./assets/**')
        .pipe(gulp.dest('./www/'));
    cb();
});

// copy templates
gulp.task('templates', function(cb){
    return gulp.src('./src/**/*.html')
        .pipe(gulp.dest('./www/'));
    cb();
});<commit_msg>Update path fonts gulp task<commit_after>var gulp = require('gulp');
var browserify  = require('browserify');
var source      = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer      = require('vinyl-buffer');

// build src
gulp.task('browserify', function(cb){
 	return browserify('./src/app.js', {
            debug: true
        })
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./www/'));

    cb();
});

// build:release
gulp.task('browserify:release', function(cb){

 	return browserify('./src/app.js')
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest('./www/'));

    cb();
});

gulp.task('fonts', function(cb){
 	return gulp.src('node_modules/ionic-npm/fonts/**')
        .pipe(gulp.dest('./www/fonts/'));
    cb();
});

gulp.task('assets', function(cb){
 	return gulp.src('./assets/**')
        .pipe(gulp.dest('./www/'));
    cb();
});

// copy templates
gulp.task('templates', function(cb){
    return gulp.src('./src/**/*.html')
        .pipe(gulp.dest('./www/'));
    cb();
});
<|endoftext|>


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

module.exports = function (grunt) {
    "use strict";

    var common      = require("./common")(grunt),
        q           = require("q"),
        exec        = common.exec,
        spawn       = common.spawn,
        resolve     = common.resolve,
        platform    = common.platform,
        _           = grunt.util._;

    function getBracketsEnv() {
        var env = _.extend(process.env);

        env.BRACKETS_SRC = resolve(grunt.config("update-repo.brackets.repo"));
        env.BRACKETS_APP_NAME = grunt.config("build.name");

        return env;
    }

    // task: full-build
    grunt.registerTask("full-build", ["update-repo", "create-project", "build", "build-branch", "build-num", "build-sha", "stage", "package", "installer"]);

    // task: build
    grunt.registerTask("build", "Build shell executable. Run 'grunt full-build' to update repositories, build the shell, and build an installer.", function (wwwBranch, shellBranch) {
        grunt.task.run("build-" + platform());
    });

    // task: build-mac
    grunt.registerTask("build-mac", "Build mac shell", function () {
        var done = this.async();

        spawn([
            "xcodebuild -project appshell.xcodeproj -config Release clean",
            "xcodebuild -project appshell.xcodeproj -config Release build"
        ]).then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });

    // task: build-win
    grunt.registerTask("build-win", "Build windows shell", function () {
        var done = this.async();

        spawn("cmd.exe /c scripts\\build_projects.bat").then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });

    // task: git
    grunt.registerMultiTask("git", "Pull specified repo branch from origin", function () {
        var repo = this.data.repo;

        if (!repo) {
            grunt.fail.fatal("Missing repo config");
        }

        repo = resolve(repo);

        if (this.data.branch) {
            grunt.verbose.writeln("Updating repo " + this.target + " at " + repo);

            var done = this.async(),
                promise =
                    spawn([
                        "git checkout " + this.data.branch,
                        "git pull origin " + this.data.branch,
                        "git submodule update --init --recursive"
                    ], { cwd: repo });

            promise.then(function () {
                done();
            }, function (err) {
                grunt.log.writeln(err);
                done(false);
            });
        } else {
            grunt.log.writeln("Skipping fetch for " + this.target + " repo");
        }
    });

    // task: build-branch
    grunt.registerTask("build-branch", "Write www repo branch to config property build.build-branch", function () {
        var done = this.async(),
            wwwRepo = resolve(grunt.config("git.www.repo"));

        spawn(["git status"], { cwd: wwwRepo })
            .then(function (result) {
                var branch = /On branch (.*)/.exec(result.stdout.trim())[1];

                grunt.log.writeln("Build branch " + branch);
                grunt.config("build.build-branch", branch);

                done();
            }, function () {
                done(false);
            });
    });

    // task: build-num
    grunt.registerTask("build-num", "Compute www repo build number and set config property build.build-number", function () {
        var done = this.async(),
            wwwRepo = resolve(grunt.config("git.www.repo"));

        spawn(["git log --oneline"], { cwd: wwwRepo })
            .then(function (result) {
                var buildNum = result.stdout.trim().split("\n").length;

                grunt.log.writeln("Build number " + buildNum);
                grunt.config("build.build-number", buildNum);

                done();
            }, function () {
                done(false);
            });
    });

    // task: build-sha
    grunt.registerTask("build-sha", "Write www repo SHA to config property build.build-sha", function () {
        var done = this.async(),
            wwwRepo = resolve(grunt.config("git.www.repo"));

        spawn(["git log -1"], { cwd: wwwRepo })
            .then(function (result) {
                var sha = /commit (.*)/.exec(result.stdout.trim())[1];

                grunt.log.writeln("SHA " + sha);
                grunt.config("build.build-sha", sha);

                done();
            }, function (err) {
                done(false);
            });
    });

    // task: stage
    grunt.registerTask("stage", "Stage release files", function () {
        // stage platform-specific binaries
        grunt.task.run("stage-" + platform());
    });

    // task: stage-mac
    grunt.registerTask("stage-mac", "Stage mac executable files", function () {
        var done = this.async();

        common.deleteFile("installer/mac/staging");

        // this should have been a grunt-contrib-copy task "copy:mac", but something goes wrong when creating the .app folder
        spawn([
            "mkdir installer/mac/staging",
            "cp -R xcodebuild/Release/" + grunt.config("build.name") + ".app installer/mac/staging/"
        ]).then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });

    // task: stage-win
    grunt.registerTask("stage-win", "Stage win executable files", function () {
        // stage platform-specific binaries, then package www files
        grunt.task.run("copy:win");
    });

    // task: package
    grunt.registerTask("package", "Package www files", function () {
        common.deleteFile(grunt.config("build.staging") + "/www");
        common.deleteFile(grunt.config("build.staging") + "/samples");
        grunt.task.run(["copy:www", "copy:samples", "write-config"]);
    });

    // task: write-config
    grunt.registerTask("write-config", "Update version data in www config.json payload", function () {
        grunt.task.requires(["build-num", "build-branch", "build-sha"]);

        var configPath = grunt.config("build.staging") + "/www/config.json",
            configJSON = grunt.file.readJSON(configPath);

        configJSON.version = configJSON.version + "-" + grunt.config("build.build-number");
        configJSON.repository.branch = grunt.config("build.build-branch");
        configJSON.repository.SHA = grunt.config("build.build-sha");

        common.writeJSON(configPath, configJSON);
    });

    // task: installer
    grunt.registerTask("installer", "Build installer", function () {
        // TODO update brackets.config.json
        grunt.task.run("installer-" + platform());
    });

    // task: installer-mac
    grunt.registerTask("installer-mac", "Build mac installer", function () {
        var done = this.async();

        spawn(["bash buildInstaller.sh"], { cwd: resolve("installer/mac"), env: getBracketsEnv() }).then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });

    // task: installer
    grunt.registerTask("installer-win", "Build windows installer", function () {
        var done = this.async();

        spawn([
            "cmd.exe /c stageForInstaller.bat",
            "ant -f brackets-win-install-build.xml"
        ], { cwd: resolve("installer/win"), env: getBracketsEnv() }).then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });
};<commit_msg>renamed update-repo task to git. fix version string.<commit_after>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */
/*jslint vars:true, regexp:true, nomen:true*/
/*global module, require, process*/

module.exports = function (grunt) {
    "use strict";

    var common      = require("./common")(grunt),
        q           = require("q"),
        exec        = common.exec,
        spawn       = common.spawn,
        resolve     = common.resolve,
        platform    = common.platform,
        _           = grunt.util._;

    function getBracketsEnv() {
        var env = _.extend(process.env);

        env.BRACKETS_SRC = resolve(grunt.config("update-repo.brackets.repo"));
        env.BRACKETS_APP_NAME = grunt.config("build.name");

        return env;
    }

    // task: full-build
    grunt.registerTask("full-build", ["git", "create-project", "build", "build-branch", "build-num", "build-sha", "stage", "package", "installer"]);

    // task: build
    grunt.registerTask("build", "Build shell executable. Run 'grunt full-build' to update repositories, build the shell, and build an installer.", function (wwwBranch, shellBranch) {
        grunt.task.run("build-" + platform());
    });

    // task: build-mac
    grunt.registerTask("build-mac", "Build mac shell", function () {
        var done = this.async();

        spawn([
            "xcodebuild -project appshell.xcodeproj -config Release clean",
            "xcodebuild -project appshell.xcodeproj -config Release build"
        ]).then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });

    // task: build-win
    grunt.registerTask("build-win", "Build windows shell", function () {
        var done = this.async();

        spawn("cmd.exe /c scripts\\build_projects.bat").then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });

    // task: git
    grunt.registerMultiTask("git", "Pull specified repo branch from origin", function () {
        var repo = this.data.repo;

        if (!repo) {
            grunt.fail.fatal("Missing repo config");
        }

        repo = resolve(repo);

        if (this.data.branch) {
            grunt.verbose.writeln("Updating repo " + this.target + " at " + repo);

            var done = this.async(),
                promise =
                    spawn([
                        "git checkout " + this.data.branch,
                        "git pull origin " + this.data.branch,
                        "git submodule update --init --recursive"
                    ], { cwd: repo });

            promise.then(function () {
                done();
            }, function (err) {
                grunt.log.writeln(err);
                done(false);
            });
        } else {
            grunt.log.writeln("Skipping fetch for " + this.target + " repo");
        }
    });

    // task: build-branch
    grunt.registerTask("build-branch", "Write www repo branch to config property build.build-branch", function () {
        var done = this.async(),
            wwwRepo = resolve(grunt.config("git.www.repo"));

        spawn(["git status"], { cwd: wwwRepo })
            .then(function (result) {
                var branch = /On branch (.*)/.exec(result.stdout.trim())[1];

                grunt.log.writeln("Build branch " + branch);
                grunt.config("build.build-branch", branch);

                done();
            }, function () {
                done(false);
            });
    });

    // task: build-num
    grunt.registerTask("build-num", "Compute www repo build number and set config property build.build-number", function () {
        var done = this.async(),
            wwwRepo = resolve(grunt.config("git.www.repo"));

        spawn(["git log --oneline"], { cwd: wwwRepo })
            .then(function (result) {
                var buildNum = result.stdout.trim().split("\n").length;

                grunt.log.writeln("Build number " + buildNum);
                grunt.config("build.build-number", buildNum);

                done();
            }, function () {
                done(false);
            });
    });

    // task: build-sha
    grunt.registerTask("build-sha", "Write www repo SHA to config property build.build-sha", function () {
        var done = this.async(),
            wwwRepo = resolve(grunt.config("git.www.repo"));

        spawn(["git log -1"], { cwd: wwwRepo })
            .then(function (result) {
                var sha = /commit (.*)/.exec(result.stdout.trim())[1];

                grunt.log.writeln("SHA " + sha);
                grunt.config("build.build-sha", sha);

                done();
            }, function (err) {
                done(false);
            });
    });

    // task: stage
    grunt.registerTask("stage", "Stage release files", function () {
        // stage platform-specific binaries
        grunt.task.run("stage-" + platform());
    });

    // task: stage-mac
    grunt.registerTask("stage-mac", "Stage mac executable files", function () {
        var done = this.async();

        common.deleteFile("installer/mac/staging");

        // this should have been a grunt-contrib-copy task "copy:mac", but something goes wrong when creating the .app folder
        spawn([
            "mkdir installer/mac/staging",
            "cp -R xcodebuild/Release/" + grunt.config("build.name") + ".app installer/mac/staging/"
        ]).then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });

    // task: stage-win
    grunt.registerTask("stage-win", "Stage win executable files", function () {
        // stage platform-specific binaries, then package www files
        grunt.task.run("copy:win");
    });

    // task: package
    grunt.registerTask("package", "Package www files", function () {
        common.deleteFile(grunt.config("build.staging") + "/www");
        common.deleteFile(grunt.config("build.staging") + "/samples");
        grunt.task.run(["copy:www", "copy:samples", "write-config"]);
    });

    // task: write-config
    grunt.registerTask("write-config", "Update version data in www config.json payload", function () {
        grunt.task.requires(["build-num", "build-branch", "build-sha"]);

        var configPath = grunt.config("build.staging") + "/www/config.json",
            configJSON = grunt.file.readJSON(configPath);

        configJSON.version = configJSON.version.substr(0, configJSON.version.lastIndexOf("-") + 1) + grunt.config("build.build-number");
        configJSON.repository.branch = grunt.config("build.build-branch");
        configJSON.repository.SHA = grunt.config("build.build-sha");

        common.writeJSON(configPath, configJSON);
    });

    // task: installer
    grunt.registerTask("installer", "Build installer", function () {
        // TODO update brackets.config.json
        grunt.task.run("installer-" + platform());
    });

    // task: installer-mac
    grunt.registerTask("installer-mac", "Build mac installer", function () {
        var done = this.async();

        spawn(["bash buildInstaller.sh"], { cwd: resolve("installer/mac"), env: getBracketsEnv() }).then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });

    // task: installer
    grunt.registerTask("installer-win", "Build windows installer", function () {
        var done = this.async();

        spawn([
            "cmd.exe /c stageForInstaller.bat",
            "ant -f brackets-win-install-build.xml"
        ], { cwd: resolve("installer/win"), env: getBracketsEnv() }).then(function () {
            done();
        }, function (err) {
            grunt.log.error(err);
            done(false);
        });
    });
};<|endoftext|>


<commit_before>var level = new Array(30);
var insp;

// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
window.addEventListener('load', function () {
  var canvas, context, tool, px, py, tcolor, brush;
  var tool_default = 'rock';
  var total_brushes = 10;
  var brushes = new Array(total_brushes);
  var brushes_img = new Array(total_brushes);

  // Load the default brush, #1
  //var img = new Image();
  //img.src = '1.png';
  brush = '1';

  px = -100;
  py = -100;

  function init () {
    // Find the elements
    canvas = document.getElementById('imageView');
    for (var i = 0; i < total_brushes; i++) {
      brushes[i] = document.getElementById('brush'+i);
      brushes[i].addEventListener('mousedown', ev_brush, false);
      brushes_img[i] = new Image();
      brushes_img[i].src = i + '.png';
      }

	// init the global level data structure
	for (var i = 0; i < 30; i++) {
		level[i] = "0000000000000000000000000000000000000000";
		}

    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

    // Pencil tool instance.
    tool = new tool_pencil();

    canvas.addEventListener('mousedown', ev_canvas, false);
    canvas.addEventListener('mousemove', ev_canvas, false);
    canvas.addEventListener('mouseup',   ev_canvas, false);
  }

 function replaceOneChar(s,c,n){
(s = s.split(''))[n] = c;
return s.join('');
};

function drawCanvas() {
for (var y = 0; y < 15; y++)
          for (var x = 0; x < 20; x++)
            context.drawImage(brushes_img[parseInt(level[y][x])], x*32, y*32);
}

function ev_brush (ev) {
//img.src = this.src;
brush = this.src.substr(this.src.length-5,1);
}

  // This painting tool works like a drawing pencil which tracks the mouse
  // movements.
  function tool_pencil () {
    var tool = this;
    this.started = false;

    // This is called when you start holding down the mouse button.
    // This starts the pencil drawing.
    this.mousedown = function (ev) {
        level[Math.floor(ev._y/32)] = replaceOneChar(level[Math.floor(ev._y/32)], brush, [Math.floor(ev._x/32)]);
        //console.log(Math.floor(ev._x/32));
        tool.started = true;
        drawCanvas();
    };

    // This function is called every time you move the mouse. Obviously, it only
    // draws if the tool.started state is set to true (when you are holding down
    // the mouse button).
    this.mousemove = function (ev) {

		context.lineWidth = 2;
		context.strokeStyle = '#fff';
		context.strokeRect((Math.floor(px/32))*32, Math.floor(py/32)*32, 32, 32);
		context.strokeStyle = '#800';
		context.strokeRect((Math.floor(ev._x/32))*32, Math.floor(ev._y/32)*32, 32, 32);
		px = ev._x;
		py = ev._y;
      if (tool.started) {
        level[Math.floor(ev._y/32)] = replaceOneChar(level[Math.floor(ev._y/32)], brush, [Math.floor(ev._x/32)]);
        drawCanvas();
        }
    };

    // This is called when you release the mouse button.
    this.mouseup = function (ev) {
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
      }
    };
  }

  // The general-purpose event handler. This function just determines the mouse
  // position relative to the canvas element.
  function ev_canvas (ev) {
    if (ev.layerX || ev.layerX == 0) { // Firefox
      ev._x = ev.layerX;
      ev._y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
      ev._x = ev.offsetX;
      ev._y = ev.offsetY;
    }

    // Call the event handler of the tool.
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }

  }

  init();

}, false); }

// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:

<commit_msg>Scrolling on the x-axis is working in the editor<commit_after>var level = new Array(30);
var insp;

// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
window.addEventListener('load', function () {
  var canvas, context, tool, px, py, tcolor, brush, camx, camy;
  var tool_default = 'rock';
  var total_brushes = 10;
  var brushes = new Array(total_brushes);
  var brushes_img = new Array(total_brushes);

  // Load the default brush, #1
  //var img = new Image();
  //img.src = '1.png';
  brush = '1';

  camx = 0;
  camy = 0;
  px = -100;
  py = -100;

  function init () {
    // Find the elements
    canvas = document.getElementById('imageView');
    for (var i = 0; i < total_brushes; i++) {
      brushes[i] = document.getElementById('brush'+i);
      brushes[i].addEventListener('mousedown', ev_brush, false);
      brushes_img[i] = new Image();
      brushes_img[i].src = i + '.png';
      }

	// init the global level data structure
	for (var i = 0; i < 30; i++) {
		level[i] = "0000000000000000000000000000000000000000";
		}

    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

    // Pencil tool instance.
    tool = new tool_pencil();

    canvas.addEventListener('mousedown', ev_canvas, false);
    canvas.addEventListener('mousemove', ev_canvas, false);
    canvas.addEventListener('mouseup',   ev_canvas, false);
  }

 function replaceOneChar(s,c,n){
(s = s.split(''))[n] = c;
return s.join('');
};

function drawCanvas(cx, cy) {
for (var y = cy; y < cy+15; y++)
          for (var x = cx; x < cx+20; x++)
            context.drawImage(brushes_img[parseInt(level[y][x])], (x-camx)*32, (y-camy)*32);
}

function ev_brush (ev) {
brush = this.src.substr(this.src.length-5,1);
}

  // This painting tool works like a drawing pencil which tracks the mouse
  // movements.
  function tool_pencil () {
    var tool = this;
    this.started = false;

    // This is called when you start holding down the mouse button.
    this.mousedown = function (ev) {
        level[Math.floor(ev._y/32)] = replaceOneChar(level[Math.floor(ev._y/32)], brush, [Math.floor(ev._x/32)+camx]);
        tool.started = true;
        drawCanvas(camx,0);
    };

    // This function is called every time you move the mouse. Obviously, it only
    // draws if the tool.started state is set to true (when you are holding down
    // the mouse button).
    this.mousemove = function (ev) {

		context.lineWidth = 2;
		context.strokeStyle = '#fff';
		context.strokeRect((Math.floor(px/32))*32, Math.floor(py/32)*32, 32, 32);
		context.strokeStyle = '#800';
		context.strokeRect((Math.floor(ev._x/32))*32, Math.floor(ev._y/32)*32, 32, 32);
		px = ev._x;
		py = ev._y;

    // move the camera when you hit the edge of the screen
      if (ev._x > 600 && camx < 20) {
        camx += 1;
        drawCanvas(camx,0);
      }
      else if (ev._x < 40 && camx > 0) {
          camx -= 1;
          drawCanvas(camx,0);
        }

      if (tool.started) {
        level[Math.floor(ev._y/32)] = replaceOneChar(level[Math.floor(ev._y/32)], brush, [Math.floor(ev._x/32)+camx]);
        drawCanvas(camx,0);
        }
    };

    // This is called when you release the mouse button.
    this.mouseup = function (ev) {
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
      }
    };
  }

  // The general-purpose event handler. This function just determines the mouse
  // position relative to the canvas element.
  function ev_canvas (ev) {
    if (ev.layerX || ev.layerX == 0) { // Firefox
      ev._x = ev.layerX;
      ev._y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
      ev._x = ev.offsetX;
      ev._y = ev.offsetY;
    }

    // Call the event handler of the tool.
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }

  }

  init();

}, false); }

// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:

<|endoftext|>


<commit_before>if (typeof modalControllers === 'undefined')
    modalControllers = {};

modalControllers.blast = function($scope, $modalInstance,$http) {
    $scope.uploadButtonEnable = true;
    $scope.state = 'uploadState';
    $scope.graphName = "Blast graph";

    $scope.handleFileSelect = function(element) {
        $scope.file = element.files[0]; // FileList object
    }
    $scope.ok = function(graphName) {
        g5.loadGraphFromObjArray($scope.results, graphName,"s","t");
        $modalInstance.close({layout: "force", graphName: graphName});
    };

    $scope.fileUpload = function(evalue,bitscore,pident)
    {
            var formData = new FormData();

	        formData.append('file', $scope.file);
                formData.append('id', Math.floor(Math.random() * (10000)));
                var p ="";
                if(evalue)
                {
                    p+="evalue"
                }
                if(bitscore)
                {
                    p+="-bitscore"
                }
                if(pident)
                {
                    p+="-pident"
                }
                formData.append('p',p);
		$http({method: 'POST', url: '/runblast', data: formData, headers: {'Content-Type': undefined}, transformRequest: angular.identity})
		.success(function(data, status, headers, config) {
                       $scope.results = data.data;
                       $scope.state = 'previewState';

		});

    };

    $scope.previewGridOptions = {enableColumnResize: true, columnDefs: 'previewColumns', data: 'results', virtualizationThreshold: 10, enableSorting: false};

    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
};<commit_msg>blast change<commit_after>if (typeof modalControllers === 'undefined')
    modalControllers = {};

modalControllers.blast = function($scope, $modalInstance,$http) {
    $scope.uploadButtonEnable = true;
    $scope.state = 'uploadState';
    $scope.graphName = "Blast graph";

    $scope.handleFileSelect = function(element) {
        $scope.file = element.files[0]; // FileList object
    }
    $scope.ok = function(graphName) {
        g5.loadGraphFromObjArray($scope.results, graphName,"s","t");
        $modalInstance.close({layout: "force", graphName: graphName});
    };

    $scope.fileUpload = function(evalue,bitscore,pident)
    {
            var formData = new FormData();

	        formData.append('file', $scope.file);
                formData.append('id', Math.floor(Math.random() * (10000)));
                var p ="";
                if(evalue)
                {
                    p+="evalue"
                }
                if(bitscore)
                {
                    p+="-bitscore"
                }
                if(pident)
                {
                    p+="-pident"
                }
                formData.append('p',p);
		$http({method: 'POST', url: '/runblast?p=evalue&id=1233', data: formData, headers: {'Content-Type': undefined}, transformRequest: angular.identity})
		.success(function(data, status, headers, config) {
                       $scope.results = data.data;
                       $scope.state = 'previewState';

		});

    };

    $scope.previewGridOptions = {enableColumnResize: true, columnDefs: 'previewColumns', data: 'results', virtualizationThreshold: 10, enableSorting: false};

    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
};<|endoftext|>


<commit_before>var DataTransformer = DataTransformer || {};

(function (dt) {
    dt.transform = function(data) {
        var circleData = [];

        var counter = 1;
        var previous = 0;
        data = getRelativePlacement(data);
        data.forEach(function (o) {
            var adjustedScore = o.result.Score / 10;
            previous = previous + adjustedScore;

            circleData.push({
                "x_axis": counter * 10 + previous,
                "y_axis": counter * 10 + previous,
                "radius": adjustedScore,
                "color": o.color
            });

            counter++;
        });

        return circleData;
    };

    function getColor(num) {
        if (num <= 1)
            return "green";
        if (num <= 2)
            return "yellow";

        return "red";
    }

    function getRelativePlacement(scores) {
        scores.sort(function(a, b) {
            if (a.result.Score > b.result.Score) {
                return -1;
            }
            if (a.result.Score < b.result.Score) {
                return 1;
            }
            // a must be equal to b
            return 0;
        });

        var totalNumber = scores.length;
        for (var i = 0; i < scores.length; i++) {
            scores[i].color = getColor(i);
        }

        return scores;
    }
})(DataTransformer);<commit_msg>colors<commit_after>var DataTransformer = DataTransformer || {};

(function (dt) {
    dt.transform = function(data) {
        var circleData = [];

        var counter = 1;
        var previous = 0;
        data = getRelativePlacement(data);
        data.forEach(function (o) {
            var adjustedScore = o.result.Score / 10;
            previous = previous + adjustedScore;

            circleData.push({
                "x_axis": counter * 10 + previous,
                "y_axis": counter * 10 + previous,
                "radius": adjustedScore,
                "color": o.color
            });

            counter++;
        });

        return circleData;
    };

    function getColor(num) {
        if (num < 1)
            return "red";
        if (num < 2)
            return "yellow";

        return "green";
    }

    function getRelativePlacement(scores) {
        var sorted = _.sortBy(scores, function(s) {
            return s.result.Score;
        });

        var third = sorted.length / 3;

        for (var i = 0; i < sorted.length; i++) {
            if (i < third) {
                sorted[i].color = "red";
            }
            else if (i < third * 2) {
                sorted[i].color = "yellow";
            } else {
                sorted[i].color = "green"
            }
        }

        return sorted;
    }
})(DataTransformer);<|endoftext|>


<commit_before>//viewmodel for the assess page
function pageViewModel(gvm) {
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableSubmodules = ko.observableArray([]);
    gvm.availableGoals = ko.observableArray([]);

    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;
    gvm.currentSubmoduleId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-submodule span:first").text(item.course);
                    $(".btn-goal span:first").text(item.goal);
                    gvm.currentLocationId = item.locationid;
                    gvm.currentTrainingid = item.trainingid;
                    gvm.currentSubmoduleId = item.submoduleid;
                    gvm.currentGoalId = item.goalid;
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid);
                    gvm.updateSubmodules(item.trainingid);
                    gvm.updateGoals(item.submoduleid);
                    loadTablePage(item.submoduleid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-submodule span:first").text();
        data["submoduleid"] = gvm.currentSubmoduleId;
        data["goal"] = $(".btn-goal span:first").text();
        data["goalid"] = gvm.currentGoalId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateLocations = function() {
        $.getJSON('/api/courserapportdrop', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
              //  Put item in list
                gvm.availableLocations.push(item);

                // Add listener to listitem
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentSubmoduleId = null;
                    gvm.currentGoalId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                    $(".btn-training span:first").text("module");
                    $(".btn-submodule span:first").text("sub-module");
                    $(".btn-goal span:first").text("goal");
                });
            });
        });
    };

    /*
     * Update the course data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/coursesrapport/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = item.id;
                    gvm.currentSubmoduleId = null;
                    gvm.updateSubmodules(item.id);
                    $(".btn-training span:first").text($(this).text());
                    $(".btn-submodule span:first").text("course");
                });
            });
        });
    }

    /*
     * Update sub-module
     */
    gvm.updateSubmodules = function(id) {
        $.getJSON('/api/submodulerapport/' + id, function(data) {
            gvm.availableSubmodules.removeAll();
            $.each(data, function(i, item) {
                gvm.availableSubmodules.push(item);

                /* Add listener to listitem */
                $("#submodulebtn-" + item.id).click(function(){
                    $(".btn-submodule span:first").text($(this).text());
                    gvm.currentSubmoduleId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    /*
     * Update goals
     */
    gvm.updateGoals = function(id) {
        $.getJSON('/api/goalrapport/' + id, function(data) {
            gvm.availableGoals.removeAll();
            $.each(data, function(i, item) {
                gvm.availableGoals.push(item);

                /* Add listener to listitem */
                $("#goalbtn-" + item.id).click(function(){
                    $(".btn-goal span:first").text($(this).text());
                    gvm.currentGoalId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(submoduleid, pagenr)
{
    $.getJSON('/api/projects/' + submoduleid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(submoduleid, thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<commit_msg>undo courseid --> submoduleid<commit_after>//viewmodel for the assess page
function pageViewModel(gvm) {
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableSubmodules = ko.observableArray([]);
    gvm.availableGoals = ko.observableArray([]);

    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;
    gvm.currentSubmoduleId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-submodule span:first").text(item.course);
                    $(".btn-goal span:first").text(item.goal);
                    gvm.currentLocationId = item.locationid;
                    gvm.currentTrainingid = item.trainingid;
                    gvm.currentSubmoduleId = item.courseid;
                    gvm.currentGoalId = item.goalid;
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid);
                    gvm.updateSubmodules(item.trainingid);
                    gvm.updateGoals(item.courseid);
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-submodule span:first").text();
        data["courseid"] = gvm.currentSubmoduleId;
        data["goal"] = $(".btn-goal span:first").text();
        data["goalid"] = gvm.currentGoalId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateLocations = function() {
        $.getJSON('/api/courserapportdrop', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
              //  Put item in list
                gvm.availableLocations.push(item);

                // Add listener to listitem
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentSubmoduleId = null;
                    gvm.currentGoalId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                    $(".btn-training span:first").text("module");
                    $(".btn-submodule span:first").text("sub-module");
                    $(".btn-goal span:first").text("goal");
                });
            });
        });
    };

    /*
     * Update the course data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/coursesrapport/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = item.id;
                    gvm.currentSubmoduleId = null;
                    gvm.updateSubmodules(item.id);
                    $(".btn-training span:first").text($(this).text());
                    $(".btn-submodule span:first").text("course");
                });
            });
        });
    }

    /*
     * Update sub-module
     */
    gvm.updateSubmodules = function(id) {
        $.getJSON('/api/submodulerapport/' + id, function(data) {
            gvm.availableSubmodules.removeAll();
            $.each(data, function(i, item) {
                gvm.availableSubmodules.push(item);

                /* Add listener to listitem */
                $("#submodulebtn-" + item.id).click(function(){
                    $(".btn-submodule span:first").text($(this).text());
                    gvm.currentSubmoduleId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    /*
     * Update goals
     */
    gvm.updateGoals = function(id) {
        $.getJSON('/api/goalrapport/' + id, function(data) {
            gvm.availableGoals.removeAll();
            $.each(data, function(i, item) {
                gvm.availableGoals.push(item);

                /* Add listener to listitem */
                $("#goalbtn-" + item.id).click(function(){
                    $(".btn-goal span:first").text($(this).text());
                    gvm.currentGoalId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<|endoftext|>


<commit_before>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.userId = null;
    gvm.courseId = null;

    gvm.formdate = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormDate");}, gvm);
    gvm.formmodules = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormModules");}, gvm);
    gvm.formworksheet = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormWorksheet");}, gvm);

    gvm.modules = ko.observableArray([]);
    gvm.assessMethod = ko.observableArray([]);

    gvm.updateModules = function(courseid) {
        $.getJSON('/api/coursestructure/' + courseid, function(data) {
            if (!$.isEmptyObject(data)) {
                gvm.modules.removeAll();

                $.each(data, function(i, item) {
                    var tblObject = {modid: item.id, modname: item.name, competences: new Array()};
                    if (item.doelstellingen[Object.keys(item.doelstellingen)[0]].id !== null) {
                        gvm.updateCompetences(item.doelstellingen, tblObject.competences);
                    }
                    gvm.modules.push(tblObject);
                });
            }
        });
    }

    gvm.updateCompetences = function(data, competences) {
        $.each(data, function(i, item) {
            var tblObject = {comid: item.id, comname: item.name, criterias: new Array()}
            if (item.criterias[Object.keys(item.criterias)[0]] !== null) {
                gvm.updateCriteria(item.criterias, tblObject.criterias);
            }
            competences.push(tblObject);
        });
    }

    gvm.updateCriteria = function(data, criteria) {
        $.each(data, function(i, item){
            var tblObject = {critid: item.id, critname: item.name};
            criteria.push(tblObject);
        });
    }

    gvm.getAssessMethod = function(wid) {
        $.getJSON('/api/worksheetdata/' + wid, function(data) {
            switch(data[0].assessment) {
                case 'A - E':
                    var array = ['A', 'B', 'C', 'D', 'E'];
                    fillArray(array);
                    break;
                case '1 - 10':
                    var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
                    fillArray(array);
                    break;
                default:
                    //input field
                    break;
            }
        });
        console.log(viewModel.assessMethod());
    }
}

function fillArray(array) {
    $.each(array, function(i, item) {
        viewModel.assessMethod.push({score: item});
        $('ul.dropdown-assessMethod li').click(function(){
            $(".btn-assessScore span:first").text($(this).text());
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;

        viewModel.courseId = $('#storage').attr('data-value');
        viewModel.updateModules(viewModel.courseId);

        var wid = $('#header').attr('data-value');
        viewModel.getAssessMethod(wid);
    });

    $('#date').datepicker();
}
<commit_msg>worksheetassess page - modules<commit_after>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.userId = null;
    gvm.courseId = null;

    gvm.formdate = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormDate");}, gvm);
    gvm.formmodules = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormModules");}, gvm);
    gvm.formworksheet = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormWorksheet");}, gvm);

    gvm.modules = ko.observableArray([]);
    gvm.assessMethod = ko.observableArray([]);

    gvm.updateModules = function(courseid) {
        $.getJSON('/api/coursestructure/' + courseid, function(data) {
            if (!$.isEmptyObject(data)) {
                gvm.modules.removeAll();

                $.each(data, function(i, item) {
                    var tblObject = {modid: item.id, modname: item.name, competences: new Array()};
                    if (item.doelstellingen[Object.keys(item.doelstellingen)[0]].id !== null) {
                        gvm.updateCompetences(item.doelstellingen, tblObject.competences);
                    }
                    gvm.modules.push(tblObject);
                });
            }
        });
    }

    gvm.updateCompetences = function(data, competences) {
        $.each(data, function(i, item) {
            var tblObject = {comid: item.id, comname: item.name, criterias: new Array()}
            if (item.criterias[Object.keys(item.criterias)[0]] !== null) {
                gvm.updateCriteria(item.criterias, tblObject.criterias);
            }
            competences.push(tblObject);
        });
    }

    gvm.updateCriteria = function(data, criteria) {
        $.each(data, function(i, item){
            var tblObject = {critid: item.id, critname: item.name};
            criteria.push(tblObject);
        });
    }

    gvm.getAssessMethod = function(wid) {
        $.getJSON('/api/worksheetdata/' + wid, function(data) {
            switch(data[0].assessment) {
                case 'A - E':
                    var array = ['A', 'B', 'C', 'D', 'E'];
                    fillArray(array);
                    break;
                case '1 - 10':
                    var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
                    fillArray(array);
                    break;
                default:
                    //input field
                    break;
            }
        });
    }
}

function fillArray(array) {
    $.each(array, function(i, item) {
        viewModel.assessMethod.push({score: item});
        $('ul.dropdown-assessMethod li a').click(function(){
            $(".btn-assessScore span:first").text($(this).text());
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;

        viewModel.courseId = $('#storage').attr('data-value');
        viewModel.updateModules(viewModel.courseId);

        var wid = $('#header').attr('data-value');
        viewModel.getAssessMethod(wid);
    });

    $('#date').datepicker();
}
<|endoftext|>


<commit_before>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.userId = null;
    gvm.courseId = null;

    gvm.formdate = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormDate");}, gvm);
    gvm.formmodules = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormModules");}, gvm);
    gvm.formworksheet = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormWorksheet");}, gvm);

    gvm.modules = ko.observableArray([]);
    gvm.assessMethod = ko.observableArray([]);

    gvm.updateModules = function(courseid) {
        $.getJSON('/api/coursestructure/' + courseid, function(data) {
            if (!$.isEmptyObject(data)) {
                gvm.modules.removeAll();

                $.each(data, function(i, item) {
                    var tblObject = {modid: item.id, modname: item.name, competences: new Array()};
                    if (item.doelstellingen[Object.keys(item.doelstellingen)[0]].id !== null) {
                        gvm.updateCompetences(item.doelstellingen, tblObject.competences);
                    }
                    gvm.modules.push(tblObject);
                });
            }
        });
    }

    gvm.updateCompetences = function(data, competences) {
        $.each(data, function(i, item) {
            var tblObject = {comid: item.id, comname: item.name, criterias: new Array()}
            if (item.criterias[Object.keys(item.criterias)[0]] !== null) {
                gvm.updateCriteria(item.criterias, tblObject.criterias);
            }
            competences.push(tblObject);
        });
    }

    gvm.updateCriteria = function(data, criteria) {
        $.each(data, function(i, item){
            var tblObject = {critid: item.id, critname: item.name};
            criteria.push(tblObject);
        });
    }

    gvm.getAssessMethod = function(wid) {
        $.getJSON('/api/worksheetdata/' + wid, function(data) {
            switch(data[0].assessment) {
                case 'A - E':
                    viewModel.assessMethod = ['A', 'B', 'C', 'D', 'E'];
                    break;
                case '1 - 10':
                    viewModel.assessMethod = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
                    break;
                default:
                    //input field
                    break;
            }
        });
        console.log(viewModel.assessMethod());
    }
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;

        viewModel.courseId = $('#storage').attr('data-value');
        viewModel.updateModules(viewModel.courseId);

        var wid = $('#header').attr('data-value');
        viewModel.getAssessMethod(wid);
    });

    $('#date').datepicker();
}
<commit_msg>worksheetassess page - modules<commit_after>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.userId = null;
    gvm.courseId = null;

    gvm.formdate = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormDate");}, gvm);
    gvm.formmodules = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormModules");}, gvm);
    gvm.formworksheet = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormWorksheet");}, gvm);

    gvm.modules = ko.observableArray([]);
    gvm.assessMethod = ko.observableArray([]);

    gvm.updateModules = function(courseid) {
        $.getJSON('/api/coursestructure/' + courseid, function(data) {
            if (!$.isEmptyObject(data)) {
                gvm.modules.removeAll();

                $.each(data, function(i, item) {
                    var tblObject = {modid: item.id, modname: item.name, competences: new Array()};
                    if (item.doelstellingen[Object.keys(item.doelstellingen)[0]].id !== null) {
                        gvm.updateCompetences(item.doelstellingen, tblObject.competences);
                    }
                    gvm.modules.push(tblObject);
                });
            }
        });
    }

    gvm.updateCompetences = function(data, competences) {
        $.each(data, function(i, item) {
            var tblObject = {comid: item.id, comname: item.name, criterias: new Array()}
            if (item.criterias[Object.keys(item.criterias)[0]] !== null) {
                gvm.updateCriteria(item.criterias, tblObject.criterias);
            }
            competences.push(tblObject);
        });
    }

    gvm.updateCriteria = function(data, criteria) {
        $.each(data, function(i, item){
            var tblObject = {critid: item.id, critname: item.name};
            criteria.push(tblObject);
        });
    }

    gvm.getAssessMethod = function(wid) {
        $.getJSON('/api/worksheetdata/' + wid, function(data) {
            switch(data[0].assessment) {
                case 'A - E':
                    console.log('in A - E');
                    viewModel.assessMethod = ['A', 'B', 'C', 'D', 'E'];
                    break;
                case '1 - 10':
                    console.log('in 1 - 10');
                    viewModel.assessMethod = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
                    break;
                default:
                    //input field
                    break;
            }
        });
        console.log(viewModel.assessMethod());
    }
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;

        viewModel.courseId = $('#storage').attr('data-value');
        viewModel.updateModules(viewModel.courseId);

        var wid = $('#header').attr('data-value');
        viewModel.getAssessMethod(wid);
    });

    $('#date').datepicker();
}
<|endoftext|>


<commit_before>/*
 * grunt-doxer
 * https://github.com/kates/grunt-doxer
 *
 * Copyright (c) 2012 kates
 * Licensed under the MIT license.
 */

var fs = require('fs'),
	path = require('path'),
	rimraf = require('rimraf'),
	dox = require('dox'),
	markdown = require('github-flavored-markdown');

module.exports = function(grunt) {
	"use strict";
	var RE_PATH = /(.*)?\/.*?\.js$/,
		RE_EXT = /\.js$/,
		INDEX_TEMPLATE = "
API Docs

<% for(var i=0; i < toc.length; i++) { %>
<a href=\"<%= toc[i]['path'] %>\"><%= toc[i]['target'] %>
<% } %>
";

	// Please see the grunt documentation for more information regarding task and
	// helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md

	// ==========================================================================
	// TASKS
	// ==========================================================================

	var findIndex = function(fPath) {
		var paths = fPath.split("/");
		paths.pop();
		var up = [];
		for (var i = 0; i < paths.length - 1; i++) {
			up.push("..");
		}
		return up.join(path.sep
	}

	grunt.registerMultiTask('doxer', 'api doc generator', function() {
		var files = grunt.file.expandFiles(this.file.src),
			dest = this.file.dest,
			options = this.data.options,
			assetPath = path.resolve(__dirname, '..', 'assets'),
			tpl = fs.readFileSync(path.resolve(assetPath, options.format === 'html' ? 'html.tpl' : 'md.tpl')).toString(),
			title = options.title;

		// cleanup
		rimraf.sync(dest);
		var toc = [];

		grunt.utils.async.forEach(files, function(file, done) {
			var str = grunt.file.read(file, "utf-8").toString();

			grunt.helper('doxer', file, str, options, function(data) {
				var filePath = dest + path.sep  + file.replace(RE_EXT, "." + options.format);

				if (/md|html/.test(options.format)) {
					var out = grunt.template.process(tpl,{
							title: title,
							body: data,
							file: file,
							indexFile: findIndex(filePath) + path.sep + "index.html"
					});
					if (options.format === "html") {
						out = markdown.parse(out);
						toc.push({
							path: file.replace(RE_EXT, "." + options.format),
							target: file
						});
					}
					grunt.file.write(filePath, out);
				} else {
					grunt.file.write(filePath, data);
				}

				done(null);
			});
			if (options.format === "html") {
				grunt.file.write(path.resolve(dest, "index.html"),
					grunt.template.process(INDEX_TEMPLATE, {toc: toc}));
			}
		}, function(err) {});
	});

	// ==========================================================================
	// HELPERS
	// ==========================================================================

	grunt.registerHelper('doxer', function(file, str, options, callback) {
		var comments = dox.parseComments(str);

		if (/md|html/.test(options.format)) {
			callback(dox.api(comments));
		} else {
			callback(JSON.stringify(comments));
		}
	});
};
<commit_msg>fixed typo<commit_after>/*
 * grunt-doxer
 * https://github.com/kates/grunt-doxer
 *
 * Copyright (c) 2012 kates
 * Licensed under the MIT license.
 */

var fs = require('fs'),
	path = require('path'),
	rimraf = require('rimraf'),
	dox = require('dox'),
	markdown = require('github-flavored-markdown');

module.exports = function(grunt) {
	"use strict";
	var RE_PATH = /(.*)?\/.*?\.js$/,
		RE_EXT = /\.js$/,
		INDEX_TEMPLATE = "
API Docs

<% for(var i=0; i < toc.length; i++) { %>
<a href=\"<%= toc[i]['path'] %>\"><%= toc[i]['target'] %>
<% } %>
";

	// Please see the grunt documentation for more information regarding task and
	// helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md

	// ==========================================================================
	// TASKS
	// ==========================================================================

	var findIndex = function(fPath) {
		var paths = fPath.split("/");
		paths.pop();
		var up = [];
		for (var i = 0; i < paths.length - 1; i++) {
			up.push("..");
		}
		return up.join(path.sep);
	}

	grunt.registerMultiTask('doxer', 'api doc generator', function() {
		var files = grunt.file.expandFiles(this.file.src),
			dest = this.file.dest,
			options = this.data.options,
			assetPath = path.resolve(__dirname, '..', 'assets'),
			tpl = fs.readFileSync(path.resolve(assetPath, options.format === 'html' ? 'html.tpl' : 'md.tpl')).toString(),
			title = options.title;

		// cleanup
		rimraf.sync(dest);
		var toc = [];

		grunt.utils.async.forEach(files, function(file, done) {
			var str = grunt.file.read(file, "utf-8").toString();

			grunt.helper('doxer', file, str, options, function(data) {
				var filePath = dest + path.sep  + file.replace(RE_EXT, "." + options.format);

				if (/md|html/.test(options.format)) {
					var out = grunt.template.process(tpl,{
							title: title,
							body: data,
							file: file,
							indexFile: findIndex(filePath) + path.sep + "index.html"
					});
					if (options.format === "html") {
						out = markdown.parse(out);
						toc.push({
							path: file.replace(RE_EXT, "." + options.format),
							target: file
						});
					}
					grunt.file.write(filePath, out);
				} else {
					grunt.file.write(filePath, data);
				}

				done(null);
			});
			if (options.format === "html") {
				grunt.file.write(path.resolve(dest, "index.html"),
					grunt.template.process(INDEX_TEMPLATE, {toc: toc}));
			}
		}, function(err) {});
	});

	// ==========================================================================
	// HELPERS
	// ==========================================================================

	grunt.registerHelper('doxer', function(file, str, options, callback) {
		var comments = dox.parseComments(str);

		if (/md|html/.test(options.format)) {
			callback(dox.api(comments));
		} else {
			callback(JSON.stringify(comments));
		}
	});
};
<|endoftext|>


<commit_before>/*
 * grunt-grock
 * https://github.com/MarcBT/grunt-grock
 *
 * Copyright (c) 2014 Marc Beuret
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  var grock = require('grock').generator;

  grunt.registerMultiTask('grock', 'A simple grunt task to generate a project\'s documentation using Grock.', function() {
    var done = this.async(),
        options = this.options(),
        glob = (this.filesSrc && this.filesSrc.length > 0) ? this.filesSrc : 'lib/*.coffee';

    var args = {
      glob: glob,
      out: options.out || 'docs/',
      style: options.style || 'solarized',
      verbose: options.verbose || false,
      index: options.index ||'Readme.md',
      root: options.root || '.',
      github: options.github || false,
      start: process.hrtime()
    };

    grock(args);

  });

};
<commit_msg>Exiting task correctly - Thanks @Killercup<commit_after>/*
 * grunt-grock
 * https://github.com/MarcBT/grunt-grock
 *
 * Copyright (c) 2014 Marc Beuret
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  var grock = require('grock').generator;

  grunt.registerMultiTask('grock', 'A simple grunt task to generate a project\'s documentation using Grock.', function() {
    var done = this.async(),
        options = this.options(),
        glob = (this.filesSrc && this.filesSrc.length > 0) ? this.filesSrc : 'lib/*.coffee';

    var args = {
      glob: glob,
      out: options.out || 'docs/',
      style: options.style || 'solarized',
      verbose: options.verbose || false,
      index: options.index ||'Readme.md',
      root: options.root || '.',
      github: options.github || false,
      start: process.hrtime()
    };

    grock(args)
      .then(function () { done(); }) // doc generation successful
      .then(null, function () { done(false); }); // there was an error;

  });

};
<|endoftext|>


<commit_before>/*jshint asi: true */
module.exports = forge

var fu = require('fu')
var fs = require('fs')

function isFile(file) {
  return fs.existsSync(file)
}

function requireTransform(name) {
  try {
    return require(name)
  } catch (ex) {
    return null
  }
}

function forge(args) {
  var x = fu.foldl(function (obj, arg) {
    var item
    if (isFile(arg)) {
      obj.files.push(arg)
    } else if (item = requireTransform(arg)) {
      obj.transforms.push(item)
    }
    return obj
  }, args, { transforms: [], files: [] })

  return fu.map(function (file) {
    var stream = fs.createReadStream(file)
    return fu.foldl(function (stream, transform) {
      return stream.pipe(transform(file))
    }, x.transforms, stream).pipe(process.stdout)
  }, x.files)
}
<commit_msg>Allow input from stdin<commit_after>/*jshint asi: true */
module.exports = forge

var fu = require('fu')
var fs = require('fs')

function isFile(file) {
  return fs.existsSync(file)
}

function requireTransform(name) {
  try {
    return require(name)
  } catch (ex) {
    return null
  }
}

function transformFiles(transforms) {
  return function (file) {
    return addTransforms(fs.createReadStream(file), transforms, file)
  }
}

function transformStdin(transforms) {
  process.stdin.resume()
  return addTransforms(process.stdin, transforms, null)
}

function addTransforms(stream, transforms, fileName) {
  return fu.foldl(function (stream, transform) {
    return stream.pipe(transform(fileName))
  }, transforms, stream).pipe(process.stdout)
}

function append(obj, prop, x) {
  obj[prop].push(x)
  return obj
}

function forge(args) {
  var x = fu.foldl(function (obj, arg) {
    try {
      return isFile(arg)
        ? append(obj, 'files', arg)
        : append(obj, 'transforms', require(arg))
    } catch (ex) {
      return obj
    }
  }, args, { transforms: [], files: [] })

  return x.files.length
    ? fu.map(transformFiles(x.transforms), x.files)
    : transformStdin(x.transforms)
}
<|endoftext|>


<commit_before>/*
 * Sphinx Node.
 * Runs Minecraft Servers for Sphinx.
 */

var fs = require("fs");
var colors = require("colors");
var Server = require("./server.js");
var SphinxServer = require('./sphinxserver.js');

// Minecraft server data.
var serverdata = []

// Minecraft server instances.
var servers = [];

// Sphinx server object.
var sphinxserver;

/**
 * Load server data from disk.
 */
function loadServerData() {
	serverdata = JSON.parse(fs.readFileSync("serverdata.json", "utf-8"));
}

/**
 * Start websockets server to listen for requests from the Sphinx server.
 */
function startWebsocketServer() {
	console.log(("Starting websocket server...").cyan);
	sphinxserver = new SphinxServer(servers, "127.0.0.1", "127.0.0.1:8000");
	console.log(("Websocket server active.").cyan);
}

/**
 * Initialize all the servers directories ready to be used.
 */
function initServers() {
	for (var i = 0; i < serverdata.length; i++) {
		servers[i] = new Server(serverdata[i]);
		servers[i].init(); // initialize server

		servers[i].updateServerProperties(); // update server properties
		servers[i].updateServerLists(); // update server whitelist and ops list.
	}
}

function startServers() {
	for (var i = 0; i < servers.length; i++) {
		servers[i].start();
	}
}

/**
 * Stop all servers.
 */
function stopServers() {
	for (var i = 0; i < servers.length; i++) {
		servers[i].stop();
	}
}

/**
 * Are any servers running?
 */
function isServersRunning() {
	for (var i = 0; i < servers.length; i++) {
		if (servers[i].isRunning()) {
			return true; // a server is still running.
		}
	}

	return false;
}

function bindShutdownHandler() { // Thanks - http://stackoverflow.com/a/14861513 !
	if (process.platform === "win32") {
		var rl = require("readline").createInterface({
			input: process.stdin,
			output: process.stdout
		});

		rl.on("SIGINT", function () {
			process.emit("SIGINT");
		});
	}

	process.on("SIGINT", function () {
		// Gracefully shutdown servers.
		console.log(("Shutting down Minecraft servers...").cyan);
		stopServers();

		var shutdownPoller = setInterval(function () {
			// Check if servers have shutdown yet.
			if (!isServersRunning()) {
				console.log(("All servers shutdown. Exiting...").cyan);
				clearInterval(shutdownPoller);
				process.exit();
			}
		}, 100);
	});
}

/**
 * Start Sphinx node
 */
function init() {
	console.log(("Starting Sphinx Node...").cyan);

	loadServerData();

	startWebsocketServer();

	initServers();

	bindShutdownHandler();

	startServers();
}

// Start server.
init();

<commit_msg>Now displays IP and port the websocket server is listening on.<commit_after>/*
 * Sphinx Node.
 * Runs Minecraft Servers for Sphinx.
 */

var fs = require("fs");
var colors = require("colors");
var Server = require("./server.js");
var SphinxServer = require('./sphinxserver.js');

// Minecraft server data.
var serverdata = []

// Minecraft server instances.
var servers = [];

// Sphinx server object.
var sphinxserver;

/**
 * Load server data from disk.
 */
function loadServerData() {
	serverdata = JSON.parse(fs.readFileSync("serverdata.json", "utf-8"));
}

/**
 * Start websockets server to listen for requests from the Sphinx server.
 */
function startWebsocketServer() {
	console.log(("Starting websocket server...").cyan);
	sphinxserver = new SphinxServer(servers, "127.0.0.1", "127.0.0.1:8000");
	console.log(("Websocket server active on " + sphinxserver.bindip + ":" + sphinxserver.bindport).cyan);
}

/**
 * Initialize all the servers directories ready to be used.
 */
function initServers() {
	for (var i = 0; i < serverdata.length; i++) {
		servers[i] = new Server(serverdata[i]);
		servers[i].init(); // initialize server

		servers[i].updateServerProperties(); // update server properties
		servers[i].updateServerLists(); // update server whitelist and ops list.
	}
}

function startServers() {
	for (var i = 0; i < servers.length; i++) {
		servers[i].start();
	}
}

/**
 * Stop all servers.
 */
function stopServers() {
	for (var i = 0; i < servers.length; i++) {
		servers[i].stop();
	}
}

/**
 * Are any servers running?
 */
function isServersRunning() {
	for (var i = 0; i < servers.length; i++) {
		if (servers[i].isRunning()) {
			return true; // a server is still running.
		}
	}

	return false;
}

function bindShutdownHandler() { // Thanks - http://stackoverflow.com/a/14861513 !
	if (process.platform === "win32") {
		var rl = require("readline").createInterface({
			input: process.stdin,
			output: process.stdout
		});

		rl.on("SIGINT", function () {
			process.emit("SIGINT");
		});
	}

	process.on("SIGINT", function () {
		// Gracefully shutdown servers.
		console.log(("Shutting down Minecraft servers...").cyan);
		stopServers();

		var shutdownPoller = setInterval(function () {
			// Check if servers have shutdown yet.
			if (!isServersRunning()) {
				console.log(("All servers shutdown. Exiting...").cyan);
				clearInterval(shutdownPoller);
				process.exit();
			}
		}, 100);
	});
}

/**
 * Start Sphinx node
 */
function init() {
	console.log(("Starting Sphinx Node...").cyan);

	loadServerData();

	startWebsocketServer();

	initServers();

	bindShutdownHandler();

	startServers();
}

// Start server.
init();

<|endoftext|>