<commit_before>/*global config:true, task:true*/
module.exports = function( grunt ) {

grunt.loadNpmTasks( "grunt-git-authors" );

grunt.initConfig({
	pkg: '<json:package.json>',
	qunit: {
		// TODO include 'test/logs.html' as well
		qunit: 'test/index.html',
		addons: [
			'addons/canvas/canvas.html',
			'addons/close-enough/close-enough.html',
			'addons/composite/composite-demo-test.html'
		]
	},
	lint: {
		qunit: 'qunit/qunit.js',
		// addons: 'addons/**/*.js',
		grunt: 'grunt.js'
		// TODO need to figure out which warnings to fix and which to disable
		// tests: 'test/test.js'
	},
	jshint: {
		qunit: {
			options: {
				onevar: true,
				browser: true,
				bitwise: true,
				curly: true,
				trailing: true,
				immed: true,
				latedef: false,
				newcap: true,
				noarg: false,
				noempty: true,
				nonew: true,
				sub: true,
				undef: true,
				eqnull: true,
				proto: true,
				smarttabs: true
			},
			globals: {
				jQuery: true,
				exports: true
			}
		},
		addons: {
			options: {
				browser: true,
				curly: true,
				eqnull: true,
				eqeqeq: true,
				expr: true,
				evil: true,
				jquery: true,
				latedef: true,
				noarg: true,
				onevar: true,
				smarttabs: true,
				trailing: true,
				undef: true
			},
			globals: {
				module: true,
				test: true,
				asyncTest: true,
				expect: true,
				start: true,
				stop: true,
				QUnit: true
			}
		},
		tests: {
		}
	}
});

grunt.registerTask( "testswarm", function( commit, configFile ) {
	var testswarm = require( "testswarm" ),
		config = grunt.file.readJSON( configFile ).qunit;
	testswarm({
		url: config.swarmUrl,
		pollInterval: 10000,
		done: this.async()
	}, {
		authUsername: "qunit",
		authToken: config.authToken,
		jobName: 'QUnit commit #' + commit.substr( 0, 10 ) + '',
		runMax: config.runMax,
		"runNames[]": "QUnit",
		"runUrls[]": config.testUrl + commit + "/test/index.html",
		"browserSets[]": ["popular"]
	});
});

grunt.registerTask('default', 'lint qunit');

};
<commit_msg>Increasing testswarm timeout - other running jobs can make this take longer<commit_after>/*global config:true, task:true*/
module.exports = function( grunt ) {

grunt.loadNpmTasks( "grunt-git-authors" );

grunt.initConfig({
	pkg: '<json:package.json>',
	qunit: {
		// TODO include 'test/logs.html' as well
		qunit: 'test/index.html',
		addons: [
			'addons/canvas/canvas.html',
			'addons/close-enough/close-enough.html',
			'addons/composite/composite-demo-test.html'
		]
	},
	lint: {
		qunit: 'qunit/qunit.js',
		// addons: 'addons/**/*.js',
		grunt: 'grunt.js'
		// TODO need to figure out which warnings to fix and which to disable
		// tests: 'test/test.js'
	},
	jshint: {
		qunit: {
			options: {
				onevar: true,
				browser: true,
				bitwise: true,
				curly: true,
				trailing: true,
				immed: true,
				latedef: false,
				newcap: true,
				noarg: false,
				noempty: true,
				nonew: true,
				sub: true,
				undef: true,
				eqnull: true,
				proto: true,
				smarttabs: true
			},
			globals: {
				jQuery: true,
				exports: true
			}
		},
		addons: {
			options: {
				browser: true,
				curly: true,
				eqnull: true,
				eqeqeq: true,
				expr: true,
				evil: true,
				jquery: true,
				latedef: true,
				noarg: true,
				onevar: true,
				smarttabs: true,
				trailing: true,
				undef: true
			},
			globals: {
				module: true,
				test: true,
				asyncTest: true,
				expect: true,
				start: true,
				stop: true,
				QUnit: true
			}
		},
		tests: {
		}
	}
});

grunt.registerTask( "testswarm", function( commit, configFile ) {
	var testswarm = require( "testswarm" ),
		config = grunt.file.readJSON( configFile ).qunit;
	testswarm({
		url: config.swarmUrl,
		pollInterval: 10000,
		timeout: 1000 * 60 * 30,
		done: this.async()
	}, {
		authUsername: "qunit",
		authToken: config.authToken,
		jobName: 'QUnit commit #' + commit.substr( 0, 10 ) + '',
		runMax: config.runMax,
		"runNames[]": "QUnit",
		"runUrls[]": config.testUrl + commit + "/test/index.html",
		"browserSets[]": ["popular"]
	});
});

grunt.registerTask('default', 'lint qunit');

};
<|endoftext|>


<commit_before>
// eslint-disable-next-line
import React, { Component } from 'react';

import Autosuggest from 'react-autosuggest';

// eslint-disable-next-line
import 'element-theme-default';

import { ipcRenderer } from 'electron';

import './App.css';

import { BottomItem } from './components/helper';
import Caret from './components/caret';
import PastItems from './components/pastItems';

// const getPercentage = (start, end, base = 28800000) => Math.round(base / (new Date(end) - new Date(start)));

function putOngoing(obj) {
  window.localStorage.setItem('ongoing-item', JSON.stringify(obj));
}
function getOngoing() {
  const ongoing = window.localStorage.getItem('ongoing-item');
  if (ongoing) {
    return JSON.parse(ongoing);
  }
  return null;
}

function renderSuggestion(suggestion) {
  return (

      {suggestion.hint}
      {suggestion.description}

  );
}

const hrStyle = {
  display: 'block',
  height: '1px',
  border: 0,
  borderTop: '1px solid rgb(173, 173, 173)',
  margin: '0 0 -1px',
  padding: 0,
};

const slashHints = [{
  hint: '/hi',
  description: 'start working',
  id: 'hi',
  create: name => ({ k: `${Date.now()}hi`, name, created: new Date().toISOString(), type: 'hi' }),
}, {
  hint: '/bye',
  description: 'end working',
  id: 'bye',
  create: name => ({ k: `${Date.now()}bye`, name, created: new Date().toISOString(), type: 'bye' }),
}, {
  hint: '/break',
  description: 'take a break from working',
  id: 'break',
  create: name => ({ k: `${Date.now()}bye`, name, created: new Date().toISOString(), type: 'break' }),
}];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeInput: '',
      pastItems: [],
      hints: slashHints,
      interval: null,
      h: 0,
    };

    this.addTime = this.addTime.bind(this);
    this.onInputChange = this.onInputChange.bind(this);
    this.onSuggestionsClearRequested = this.onSuggestionsClearRequested.bind(this);
    this.stopIntervalUpdate = this.stopIntervalUpdate.bind(this);
    this.startIntervalUpdate = this.startIntervalUpdate.bind(this);
  }

  componentWillMount() {
    this.startIntervalUpdate();
  }

  componentDidMount() {
    if (this.inputField) {
      this.inputField.focus();
    }
    window.addEventListener('focus', () => this.inputField && this.inputField.focus());
    document.addEventListener('keydown', (event) => {
      // ESC
      if (event.keyCode === 27) {
        event.stopPropagation();
        event.preventDefault();
        ipcRenderer.send('hide-app');
      }
    });

    console.log('sending', 'get-entries');

    // load possible latest ongoing
    const ongoing = getOngoing();

    ipcRenderer.on('get-entries-resp', (event, data) => {
      console.log({ data });
      if (ongoing) {
        data.push(ongoing);
      }
      this.setState({
        pastItems: data,
      });
    });
    ipcRenderer.send('get-entries');

    ipcRenderer.on('app-isgoingto-hide', () => {
      console.log('received app-isgoingto-hide');
      if (this.state.interval) {
        this.stopIntervalUpdate();
      }
    });
    ipcRenderer.on('app-isgoingto-show', () => {
      console.log('received app-isgoingto-show');
      if (!this.state.interval) {
        this.startIntervalUpdate();
      }
    });
  }

  componentWillUnmount() {
    this.stopIntervalUpdate();
  }

  onInputChange(event, { newValue, method }) {
    console.log({ newValue, method });
    const changeHintList = method !== 'down' && method !== 'up';
    this.setState(prevState => ({
      ...prevState,
      hints: newValue && changeHintList ? slashHints.filter(hint => hint.hint.startsWith(newValue)) : prevState.hints,
      timeInput: newValue,
    }));
    // setTimeout(() => this.messagesEnd.scrollIntoView({behavior: 'smooth' }), 1000)
  }

  onSuggestionsClearRequested() {
    this.setState({
      hints: [],
    });
  }

  stopIntervalUpdate() {
    this.setState(prevState => ({
      interval: clearInterval(prevState.interval),
    }));
  }

  startIntervalUpdate() {
    this.setState(prevState => ({
      interval: setInterval(() => this.setState({ h: prevState.h + 1 }), 1000),
    }));
  }

  addTime(event) {
    event.preventDefault();
    event.stopPropagation();

    const text = this.state.timeInput;

    if (!text) {
      return;
    }

    this.setState((prevState) => {
      const now = new Date().toISOString();
      // ongoing item
      const last = prevState.pastItems.pop();

      if (last) {
        // finish it
        last.finished = now;
        ipcRenderer.send('new-entry', last);
      }

      // thats the new ongoing item
      let newItem = {};

      // check for special commands
      if (slashHints.some(hint => text.startsWith(hint.hint))) {
        newItem = slashHints.find(hint => text.startsWith(hint.hint)).create(text);
      } else {
        newItem = {
          // TODO: ID creation, rename variable
          k: prevState.pastItems.length + 2 + Date.now(),
          name: text,
          created: now,
        };
      }
      // add new ongoing
      putOngoing(newItem);

      setTimeout(() => this.messagesEnd.scrollIntoView({ behavior: 'smooth' }), 0);

      return {
        ...prevState,
        // put back the now completed ongoing and the new ongoing
        pastItems: [...prevState.pastItems, last, newItem],
        // reset hint list
        // hints: [],
        // reset text input
        timeInput: '',
      };
    });
  }

  render() {
    // Autosuggest will pass through all these props to the input.
    const inputProps = {
      placeholder: 'Type what you are doing...',
      value: this.state.timeInput,
      onChange: this.onInputChange,
    };
    return (

          <Caret />

        TIJD

        <PastItems
          bottomitem={<BottomItem inputRef={(input) => { this.messagesEnd = input; }} />}
          items={this.state.pastItems}
        />

        <form onSubmit={this.addTime} style={{ position: 'absolute', left: 0, bottom: 0, width: '100%' }}>

          <Autosuggest
            suggestions={this.state.hints}
            onSuggestionsFetchRequested={() => { }}
            onSuggestionsClearRequested={this.onSuggestionsClearRequested}
            getSuggestionValue={val => val.hint}
            renderSuggestion={renderSuggestion}
            ref={(value) => { this.inputField = value && value.input ? value.input : null; }}
            inputProps={inputProps}
            className="main-input"
          />
        </form>

    );
  }
}

export default App;
<commit_msg>remove log<commit_after>
// eslint-disable-next-line
import React, { Component } from 'react';

import Autosuggest from 'react-autosuggest';

// eslint-disable-next-line
import 'element-theme-default';

import { ipcRenderer } from 'electron';

import './App.css';

import { BottomItem } from './components/helper';
import Caret from './components/caret';
import PastItems from './components/pastItems';

// const getPercentage = (start, end, base = 28800000) => Math.round(base / (new Date(end) - new Date(start)));

function putOngoing(obj) {
  window.localStorage.setItem('ongoing-item', JSON.stringify(obj));
}
function getOngoing() {
  const ongoing = window.localStorage.getItem('ongoing-item');
  if (ongoing) {
    return JSON.parse(ongoing);
  }
  return null;
}

function renderSuggestion(suggestion) {
  return (

      {suggestion.hint}
      {suggestion.description}

  );
}

const hrStyle = {
  display: 'block',
  height: '1px',
  border: 0,
  borderTop: '1px solid rgb(173, 173, 173)',
  margin: '0 0 -1px',
  padding: 0,
};

const slashHints = [{
  hint: '/hi',
  description: 'start working',
  id: 'hi',
  create: name => ({ k: `${Date.now()}hi`, name, created: new Date().toISOString(), type: 'hi' }),
}, {
  hint: '/bye',
  description: 'end working',
  id: 'bye',
  create: name => ({ k: `${Date.now()}bye`, name, created: new Date().toISOString(), type: 'bye' }),
}, {
  hint: '/break',
  description: 'take a break from working',
  id: 'break',
  create: name => ({ k: `${Date.now()}bye`, name, created: new Date().toISOString(), type: 'break' }),
}];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeInput: '',
      pastItems: [],
      hints: slashHints,
      interval: null,
      h: 0,
    };

    this.addTime = this.addTime.bind(this);
    this.onInputChange = this.onInputChange.bind(this);
    this.onSuggestionsClearRequested = this.onSuggestionsClearRequested.bind(this);
    this.stopIntervalUpdate = this.stopIntervalUpdate.bind(this);
    this.startIntervalUpdate = this.startIntervalUpdate.bind(this);
  }

  componentWillMount() {
    this.startIntervalUpdate();
  }

  componentDidMount() {
    if (this.inputField) {
      this.inputField.focus();
    }
    window.addEventListener('focus', () => this.inputField && this.inputField.focus());
    document.addEventListener('keydown', (event) => {
      // ESC
      if (event.keyCode === 27) {
        event.stopPropagation();
        event.preventDefault();
        ipcRenderer.send('hide-app');
      }
    });

    console.log('sending', 'get-entries');

    // load possible latest ongoing
    const ongoing = getOngoing();

    ipcRenderer.on('get-entries-resp', (event, data) => {
      console.log({ data });
      if (ongoing) {
        data.push(ongoing);
      }
      this.setState({
        pastItems: data,
      });
    });
    ipcRenderer.send('get-entries');

    ipcRenderer.on('app-isgoingto-hide', () => {
      console.log('received app-isgoingto-hide');
      if (this.state.interval) {
        this.stopIntervalUpdate();
      }
    });
    ipcRenderer.on('app-isgoingto-show', () => {
      console.log('received app-isgoingto-show');
      if (!this.state.interval) {
        this.startIntervalUpdate();
      }
    });
  }

  componentWillUnmount() {
    this.stopIntervalUpdate();
  }

  onInputChange(event, { newValue, method }) {
    const changeHintList = method !== 'down' && method !== 'up';
    this.setState(prevState => ({
      ...prevState,
      hints: newValue && changeHintList ? slashHints.filter(hint => hint.hint.startsWith(newValue)) : prevState.hints,
      timeInput: newValue,
    }));
    // setTimeout(() => this.messagesEnd.scrollIntoView({behavior: 'smooth' }), 1000)
  }

  onSuggestionsClearRequested() {
    this.setState({
      hints: [],
    });
  }

  stopIntervalUpdate() {
    this.setState(prevState => ({
      interval: clearInterval(prevState.interval),
    }));
  }

  startIntervalUpdate() {
    this.setState(prevState => ({
      interval: setInterval(() => this.setState({ h: prevState.h + 1 }), 1000),
    }));
  }

  addTime(event) {
    event.preventDefault();
    event.stopPropagation();

    const text = this.state.timeInput;

    if (!text) {
      return;
    }

    this.setState((prevState) => {
      const now = new Date().toISOString();
      // ongoing item
      const last = prevState.pastItems.pop();

      if (last) {
        // finish it
        last.finished = now;
        ipcRenderer.send('new-entry', last);
      }

      // thats the new ongoing item
      let newItem = {};

      // check for special commands
      if (slashHints.some(hint => text.startsWith(hint.hint))) {
        newItem = slashHints.find(hint => text.startsWith(hint.hint)).create(text);
      } else {
        newItem = {
          // TODO: ID creation, rename variable
          k: prevState.pastItems.length + 2 + Date.now(),
          name: text,
          created: now,
        };
      }
      // add new ongoing
      putOngoing(newItem);

      setTimeout(() => this.messagesEnd.scrollIntoView({ behavior: 'smooth' }), 0);

      return {
        ...prevState,
        // put back the now completed ongoing and the new ongoing
        pastItems: [...prevState.pastItems, last, newItem],
        // reset hint list
        // hints: [],
        // reset text input
        timeInput: '',
      };
    });
  }

  render() {
    // Autosuggest will pass through all these props to the input.
    const inputProps = {
      placeholder: 'Type what you are doing...',
      value: this.state.timeInput,
      onChange: this.onInputChange,
    };
    return (

          <Caret />

        TIJD

        <PastItems
          bottomitem={<BottomItem inputRef={(input) => { this.messagesEnd = input; }} />}
          items={this.state.pastItems}
        />

        <form onSubmit={this.addTime} style={{ position: 'absolute', left: 0, bottom: 0, width: '100%' }}>

          <Autosuggest
            suggestions={this.state.hints}
            onSuggestionsFetchRequested={() => { }}
            onSuggestionsClearRequested={this.onSuggestionsClearRequested}
            getSuggestionValue={val => val.hint}
            renderSuggestion={renderSuggestion}
            ref={(value) => { this.inputField = value && value.input ? value.input : null; }}
            inputProps={inputProps}
            className="main-input"
          />
        </form>

    );
  }
}

export default App;
<|endoftext|>


<commit_before>/*global module:false, require:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    server: {
        port: 8085
    },
    concat: {
      dist: {
        src: ['<banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    min: {
      dist: {
        src: ['<banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    jade: {
      html: {
        src: ["docs/index.jade"],
        dest: "dist",
        options: {
          client: false
        }
      }
    },
    less: {
      index: {
        src: "docs/index.less",
        dest: "dist/index.css"
      }
    },
    qunit: {
      urls: ['1.9.0', '2.0.0b1'].map(function(version) {
        return 'http://localhost:<%= server.port %>/test/jquery.emailaddressmunging.html?jquery=' + version;
      })
    },
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint qunit'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'test dist');
  grunt.registerTask('test', 'server lint qunit');
  grunt.registerTask('dist', 'concat min jade less copy');

  grunt.loadNpmTasks('grunt-jade');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-beautify');

  grunt.registerTask('tidy', 'beautify');

  // TODO: create generic copy task
  grunt.registerTask('copy', 'Copy misc files to dist', function() {
    var files = [
      'CHANGES',
      'LICENSE',
      'README',
      'ext/bootstrap/bootstrap.min.css'
    ];

    files.forEach(function(f) {
      var name = f.split("/").pop();
      grunt.file.copy(f, "dist/" + name);
    });
  });
};
<commit_msg>add config for tidy<commit_after>/*global module:false, require:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    server: {
        port: 8085
    },
    concat: {
      dist: {
        src: ['<banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    min: {
      dist: {
        src: ['<banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    jade: {
      html: {
        src: ["docs/index.jade"],
        dest: "dist",
        options: {
          client: false
        }
      }
    },
    less: {
      index: {
        src: "docs/index.less",
        dest: "dist/index.css"
      }
    },
    qunit: {
      urls: ['1.9.0', '2.0.0b1'].map(function(version) {
        return 'http://localhost:<%= server.port %>/test/jquery.emailaddressmunging.html?jquery=' + version;
      })
    },
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']
    },
    beautify: {
      files: '<config:lint.files>'
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint qunit'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'test dist');
  grunt.registerTask('test', 'server lint qunit');
  grunt.registerTask('dist', 'concat min jade less copy');

  grunt.loadNpmTasks('grunt-jade');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-beautify');

  grunt.registerTask('tidy', 'beautify');

  // TODO: create generic copy task
  grunt.registerTask('copy', 'Copy misc files to dist', function() {
    var files = [
      'CHANGES',
      'LICENSE',
      'README',
      'ext/bootstrap/bootstrap.min.css'
    ];

    files.forEach(function(f) {
      var name = f.split("/").pop();
      grunt.file.copy(f, "dist/" + name);
    });
  });
};
<|endoftext|>


<commit_before>/*global module:false, require:false*/
module.exports = function (grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    concat: {
      dist: {
        src: ['<banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'],
        dest: 'dist/<%= pkg.name %>.js'
      },
      distcss: {
        src: ['<banner>', '<file_strip_banner:src/<%= pkg.name %>.css>'],
        dest: 'dist/<%= pkg.name %>.css'
      }
    },
    min: {
      dist: {
        src: ['<banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    cssmin: {
      dist: {
        src: ['<config:concat.distcss.dest>'],
        dest: 'dist/<%= pkg.name %>.min.css'
      },
      docs: {
        src: ['<config:less.index.dest>'],
        dest: 'dist/index.min.css'
      }
    },
    jade: {
      html: {
        src: ["src/index.jade"],
        dest: "dist",
        options: {
          client: false
        }
      }
    },
    less: {
      index: {
        src: "src/index.less",
        dest: "dist/index.css"
      }
    },
    qunit: {
      files: ['test/**/*.html']
    },
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']
    },
    beautify: {
      files: '<config:lint.files>'
    },
    csslint: {
      files: ['src/**/*.css']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint qunit'
    },
    copy: {
      dist: {
        options: {
          flatten: true
        },
        files: {
          'dist/': ['CHANGES', 'LICENSE', 'README', 'ext/bootstrap/bootstrap.min.css']
        }
      }
    },
    compress: {
      zip: {
        options: {
          mode: "zip",
          rootDir: "jquery-placeholder-plugin"
        },
        files: {
          "jquery-placeholder-plugin-<%= pkg.version %>.zip": ["dist/**"]
        }
      }
    },
    clean: ['dist'],
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'lint csslint qunit');

  grunt.registerTask('dist', 'default jade less concat min cssmin copy');

  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-compress');
  grunt.loadNpmTasks('grunt-bump');
  grunt.loadNpmTasks('grunt-css');
  grunt.loadNpmTasks('grunt-jade');
  grunt.loadNpmTasks('grunt-beautify');

  grunt.registerTask('tidy', 'beautify');
};<commit_msg>use all tasks<commit_after>/*global module:false, require:false*/
module.exports = function (grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    concat: {
      dist: {
        src: ['<banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'],
        dest: 'dist/<%= pkg.name %>.js'
      },
      distcss: {
        src: ['<banner>', '<file_strip_banner:src/<%= pkg.name %>.css>'],
        dest: 'dist/<%= pkg.name %>.css'
      }
    },
    min: {
      dist: {
        src: ['<banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    cssmin: {
      dist: {
        src: ['<config:concat.distcss.dest>'],
        dest: 'dist/<%= pkg.name %>.min.css'
      },
      docs: {
        src: ['<config:less.index.dest>'],
        dest: 'dist/index.min.css'
      }
    },
    jade: {
      html: {
        src: ["src/index.jade"],
        dest: "dist",
        options: {
          client: false
        }
      }
    },
    less: {
      index: {
        src: "src/index.less",
        dest: "dist/index.css"
      }
    },
    qunit: {
      files: ['test/**/*.html']
    },
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']
    },
    beautify: {
      files: '<config:lint.files>'
    },
    csslint: {
      files: ['src/**/*.css']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint qunit'
    },
    copy: {
      dist: {
        options: {
          flatten: true
        },
        files: {
          'dist/': ['CHANGES', 'LICENSE', 'README', 'ext/bootstrap/bootstrap.min.css']
        }
      }
    },
    compress: {
      zip: {
        options: {
          mode: "zip",
          rootDir: "jquery-placeholder-plugin"
        },
        files: {
          "jquery-placeholder-plugin-<%= pkg.version %>.zip": ["dist/**"]
        }
      }
    },
    clean: ['dist'],
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'lint csslint beautify qunit');

  grunt.registerTask('dist', 'default jade less concat min cssmin copy compress');

  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-compress');
  grunt.loadNpmTasks('grunt-bump');
  grunt.loadNpmTasks('grunt-css');
  grunt.loadNpmTasks('grunt-jade');
  grunt.loadNpmTasks('grunt-beautify');

  grunt.registerTask('tidy', 'beautify');
};<|endoftext|>


<commit_before>'use strict';

const debug = require('debug')('gameboy:cart:mbc1');
const Serializable = require('../../util/serializable');
const { ROM_SIZE, RAM_SIZE } = require('../headers');

const createMemory = (count, size, data = []) => new Array(count)
    .fill(null)
    .map((v, i) => {
        const offset = i * size;
        if (offset + size <= data.length) {
            return data.slice(offset, offset + size);
        }
        return new Uint8Array(size);
    });

const wrap = (array, i) => array[i & (array.length - 1)];

class MBC1 extends Serializable({ exclude: ['_rom'] }) {
    constructor (data, romSize, ramSize) {
        super();

        this._lbank = 1;
        this._hbank = 0;
        this._ramEnabled = false;
        this._mode = 0;

        this._rom = createMemory(ROM_SIZE[romSize], 0x4000, data);
        this._ram = createMemory(RAM_SIZE[ramSize], 0x2000);
        console.log('rom', this._rom, ROM_SIZE[romSize]);
        console.log('ram', this._ram, RAM_SIZE[ramSize]);
    }

    readByte (addr) {
        switch (addr >> 12) {
            case 0x0: case 0x1:
            case 0x2: case 0x3: {
                let bank = 0;
                if (this._mode == 1) bank = this._hbank << 5;
                return wrap(this._rom, bank)[addr];
            }
            case 0x4: case 0x5:
            case 0x6: case 0x7: {
                const bank = this._lbank | (this._hbank << 5);
                return wrap(this._rom, bank)[addr & 0x3fff];
            }
            case 0xa: case 0xb: {
                if (!this._ramEnabled) {
                    debug('cannot read ram while disabled');
                    return 0xff;
                } else if (this._ram.length == 0) {
                    throw new Error('cannot read ram if not created');
                }
                let bank = 0;
                if (this._mode == 1) bank = this._hbank;
                return wrap(this._ram, bank)[addr & 0x1fff];
            }
        }

        throw new Error(`unmapped address 0x${addr.toString(16)}`);
    }

    writeByte (addr, val) {
        switch (addr >> 12) {
            case 0x0: case 0x1:
                return this._ramEnabled = (val & 0xf) == 0xa;
            case 0x2: case 0x3:
                val &= 0x1f;
                if (val == 0) val = 1;
                return this._lbank = val;
            case 0x4: case 0x5:
                return this._hbank = val & 3;
            case 0x6: case 0x7:
                return this._mode = val & 1;
            case 0xa: case 0xb: {
                if (!this._ramEnabled) {
                    return debug('cannot write ram while disabled');
                } else if (this._ram.length == 0) {
                    throw new Error('cannot write ram if not created');
                }
                let bank = 0;
                if (this._mode == 1) bank = this._hbank;
                return wrap(this._ram, bank)[addr & 0x1fff] = val;
            }
        }

        throw new Error(`unmapped address 0x${addr.toString(16)}`);
    }
}

module.exports = MBC1;
<commit_msg>cleanup<commit_after>'use strict';

const debug = require('debug')('gameboy:cart:mbc1');
const Serializable = require('../../util/serializable');
const { ROM_SIZE, RAM_SIZE } = require('../headers');

const createMemory = (count, size, data = []) => new Array(count)
    .fill(null)
    .map((v, i) => {
        const offset = i * size;
        if (offset + size <= data.length) {
            return data.slice(offset, offset + size);
        }
        return new Uint8Array(size);
    });

const wrap = (array, i) => array[i & (array.length - 1)];

class MBC1 extends Serializable({ exclude: ['_rom'] }) {
    constructor (data, romSize, ramSize) {
        super();

        this._lbank = 1;
        this._hbank = 0;
        this._ramEnabled = false;
        this._mode = 0;

        this._rom = createMemory(ROM_SIZE[romSize], 0x4000, data);
        this._ram = createMemory(RAM_SIZE[ramSize], 0x2000);
    }

    readByte (addr) {
        switch (addr >> 12) {
            case 0x0: case 0x1:
            case 0x2: case 0x3: {
                let bank = 0;
                if (this._mode == 1) bank = this._hbank << 5;
                return wrap(this._rom, bank)[addr];
            }
            case 0x4: case 0x5:
            case 0x6: case 0x7: {
                const bank = this._lbank | (this._hbank << 5);
                return wrap(this._rom, bank)[addr & 0x3fff];
            }
            case 0xa: case 0xb: {
                if (!this._ramEnabled) {
                    debug('cannot read ram while disabled');
                    return 0xff;
                } else if (this._ram.length == 0) {
                    throw new Error('cannot read ram if not created');
                }
                let bank = 0;
                if (this._mode == 1) bank = this._hbank;
                return wrap(this._ram, bank)[addr & 0x1fff];
            }
        }

        throw new Error(`unmapped address 0x${addr.toString(16)}`);
    }

    writeByte (addr, val) {
        switch (addr >> 12) {
            case 0x0: case 0x1:
                return this._ramEnabled = (val & 0xf) == 0xa;
            case 0x2: case 0x3:
                val &= 0x1f;
                if (val == 0) val = 1;
                return this._lbank = val;
            case 0x4: case 0x5:
                return this._hbank = val & 3;
            case 0x6: case 0x7:
                return this._mode = val & 1;
            case 0xa: case 0xb: {
                if (!this._ramEnabled) {
                    return debug('cannot write ram while disabled');
                } else if (this._ram.length == 0) {
                    throw new Error('cannot write ram if not created');
                }
                let bank = 0;
                if (this._mode == 1) bank = this._hbank;
                return wrap(this._ram, bank)[addr & 0x1fff] = val;
            }
        }

        throw new Error(`unmapped address 0x${addr.toString(16)}`);
    }
}

module.exports = MBC1;
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    info: '<json:package.json>',
    meta: {
      banner: '/*!\n'+
              ' * <%= info.name %> - <%= info.description %>\n'+
              ' * v<%= info.version %>\n'+
              ' * <%= info.homepage %>\n'+
              ' * copyright <%= info.copyright %> <%= grunt.template.today("yyyy") %>\n'+
              ' * <%= info.license %> License\n'+
              '*/'
    },
    lint: {
      all: 'lib/monster.js'
    },
    concat: {
      dist: {
        src: ['<banner>', 'lib/monster.js'],
        dest: 'dist/monster.js'
      },
    },
    min: {
      dist: {
        src: ['<banner>', 'dist/monster.js'],
        dest: 'dist/monster.min.js'
      }
    },
    simplemocha: {
      all: {
        src: 'test/**/*.test.js',
        options: {
          ui: 'bdd',
          reporter: 'list',
          growl: true
        }
      }
    },
    watch: {
      js: {
        files: 'lib/monster.js',
        tasks: 'concat min'
      }
    },
    server:{
      port: 8000,
      base: '.'
    }
  });
  grunt.registerTask('default', 'lint concat min');
  grunt.registerTask('dev', 'server watch');
}
<commit_msg>watch test files<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    info: '<json:package.json>',
    meta: {
      banner: '/*!\n'+
              ' * <%= info.name %> - <%= info.description %>\n'+
              ' * v<%= info.version %>\n'+
              ' * <%= info.homepage %>\n'+
              ' * copyright <%= info.copyright %> <%= grunt.template.today("yyyy") %>\n'+
              ' * <%= info.license %> License\n'+
              '*/'
    },
    lint: {
      all: 'lib/monster.js'
    },
    concat: {
      dist: {
        src: ['<banner>', 'lib/monster.js'],
        dest: 'dist/monster.js'
      },
    },
    min: {
      dist: {
        src: ['<banner>', 'dist/monster.js'],
        dest: 'dist/monster.min.js'
      }
    },
    simplemocha: {
      all: {
        src: 'test/**/*.test.js',
        options: {
          ui: 'bdd',
          reporter: 'list',
          growl: true
        }
      }
    },
    watch: {
      js: {
        files: ['lib/monster.js', 'test/*'],
        tasks: 'concat min'
      }
    },
    server:{
      port: 8000,
      base: '.'
    }
  });
  grunt.registerTask('default', 'lint concat min');
  grunt.registerTask('dev', 'server watch');
}
<|endoftext|>


<commit_before>// production webserver
// August 2016 Benjamin Foote
//
/*  supporting the Docker infrastructure
 *  http://checkdesk-api.qa.checkdesk.org/api/me
 *
 */

var express = require('express'),
    serveStatic = require('serve-static'),
    app = express();

var port = process.env.SERVER_PORT || 8000;

// standard headers
app.use(function(req, res, next) {
   // CORS
   res.header("Access-Control-Allow-Origin", "*");
   res.header("X-Check-Web", "1");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

   // cacheing
   // s-maxage is for cloudflare
   // https://support.cloudflare.com/hc/en-us/articles/202775670-How-Do-I-Tell-CloudFlare-What-to-Cache-
   // cloudflare will cache for 15 minutes
   // browser will cache for 5 minutes
   // so the longest a user can go without getting a fresh item from this webserver is ~20 min (14:59 + 5:00)

   // there is a page rule set at Cloudflare to enforce cacheing index.html which is not a CF default
   // https://support.cloudflare.com/hc/en-us/articles/200172256

   res.header("Cache-Control", "public, s-maxage=900, max-age=300");

   next();
});

// static assets first
app.use(serveStatic('build/web', { 'index': ['index.html'] }))

// all other routes
app.use(function(req, res, next) {
   res.sendFile(process.cwd() + '/build/web/index.html');
});
console.log("starting server on :" + port);
app.listen(port);
<commit_msg>Ticket #5622: Removing unneeded header<commit_after>// production webserver
// August 2016 Benjamin Foote
//
/*  supporting the Docker infrastructure
 *  http://checkdesk-api.qa.checkdesk.org/api/me
 *
 */

var express = require('express'),
    serveStatic = require('serve-static'),
    app = express();

var port = process.env.SERVER_PORT || 8000;

// standard headers
app.use(function(req, res, next) {
   // CORS
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

   // cacheing
   // s-maxage is for cloudflare
   // https://support.cloudflare.com/hc/en-us/articles/202775670-How-Do-I-Tell-CloudFlare-What-to-Cache-
   // cloudflare will cache for 15 minutes
   // browser will cache for 5 minutes
   // so the longest a user can go without getting a fresh item from this webserver is ~20 min (14:59 + 5:00)

   // there is a page rule set at Cloudflare to enforce cacheing index.html which is not a CF default
   // https://support.cloudflare.com/hc/en-us/articles/200172256

   res.header("Cache-Control", "public, s-maxage=900, max-age=300");

   next();
});

// static assets first
app.use(serveStatic('build/web', { 'index': ['index.html'] }))

// all other routes
app.use(function(req, res, next) {
   res.sendFile(process.cwd() + '/build/web/index.html');
});
console.log("starting server on :" + port);
app.listen(port);
<|endoftext|>


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

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("m/d/yyyy") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    concat: {
      dist: {
        src: ['<banner>', '<file_strip_banner:lib/<%= pkg.name %>.js>'],
        dest: 'dist/<%= pkg.name %>.js',
        process: true
      }
    },
    min: {
      dist: {
        src: ['<banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    mocha: {
      all: [ 'test/test.html' ]
    },
    lint: {
      files: ['grunt.js', 'lib/**/*.js', 'test/backbone.paginator*.js']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        // unfortunately JSHint can't enforce the indentation without also enforcing
        // Crockford's styleguide. see https://github.com/jshint/jshint/issues/655
        // This is already fixed in master: https://github.com/jshint/jshint/issues/667
        // As soon as it is released the following line can be uncommented
        //indent: 2,
        trailing: true
      },
      globals: {
        exports: true,
        module: false
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'lint mocha concat min');
  grunt.registerTask('test', 'lint mocha');

  // run `npm install grunt-mocha` in project root dir and uncomment this
  grunt.loadNpmTasks('grunt-mocha');
};
<commit_msg>Manually replace version in separate build step<commit_after>module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("m/d/yyyy") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    concat: {
      dist: {
        src: ['<banner>', '<file_strip_banner:lib/<%= pkg.name %>.js>'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    min: {
      dist: {
        src: ['<banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    mocha: {
      all: [ 'test/test.html' ]
    },
    lint: {
      files: ['grunt.js', 'lib/**/*.js', 'test/backbone.paginator*.js']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        // unfortunately JSHint can't enforce the indentation without also enforcing
        // Crockford's styleguide. see https://github.com/jshint/jshint/issues/655
        // This is already fixed in master: https://github.com/jshint/jshint/issues/667
        // As soon as it is released the following line can be uncommented
        //indent: 2,
        trailing: true
      },
      globals: {
        exports: true,
        module: false
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'lint mocha concat replace-version min');
  grunt.registerTask('test', 'lint mocha');

  // run `npm install grunt-mocha` in project root dir and uncomment this
  grunt.loadNpmTasks('grunt-mocha');

  grunt.registerTask('replace-version', 'replace the version placeholder in backbone.paginator.js', function() {
    var pkg = grunt.config.get('pkg');
    var filename = 'dist/' + pkg.name + '.js';
    var content = grunt.file.read(filename);
    var rendered = grunt.template.process(content, { pkg : pkg });
    grunt.file.write(filename, rendered);
  });
};
<|endoftext|>


<commit_before>var cleanCSS = require('clean-css');
var fs = require('fs');
var fsTools = require('fs-tools');
var grunt = require('grunt');
var path = require('path');
var rimraf = require('rimraf');
var util = require('util');

config.init({
  meta: {
    dist: {
      production: {
        directory: './dist/production/'
      },

      development: {
        directory: './dist/development/'
      }
    }
  },

  lint: {
    files: [
      'grunt.js',
      'src/**/*.js'
    ]
  },

  concat: {
    'dist/development/javascripts/libs.js': ['vendor/javascripts/*.js'],
    'dist/development/javascripts/app.js': ['src/werld.js', 'src/**/*.js'],
    'dist/development/stylesheets/index.css': [
      'vendor/stylesheets/*.css',
      'assets/stylesheets/webfonts.css',
      'assets/stylesheets/style.css'
    ],
    'dist/development/stylesheets/play.css': [
      'vendor/stylesheets/*.css',
      'assets/stylesheets/webfonts.css',
      'assets/stylesheets/canvas.css'
    ]
  },

  jst: {
    'dist/development/javascripts/templates.js': ['src/templates/*.html']
  },

  min: {
    'dist/production/javascripts/libs.js': ['dist/development/javascripts/libs.js'],
    'dist/production/javascripts/app.js': ['dist/development/javascripts/app.js'],
    'dist/production/javascripts/templates.js': ['dist/development/javascripts/templates.js']
  },

  mincss: {
    'dist/production/stylesheets/index.css': ['dist/development/stylesheets/index.css'],
    'dist/production/stylesheets/play.css': ['dist/development/stylesheets/play.css']
  },

  copyassets: {
    files: [
      'assets/index.html',
      'assets/play.html',
      'assets/favicon.ico',
      'assets/images/',
      'assets/sounds/',
      'assets/webfonts/'
    ]
  },

  watch: {
    files: ['assets/**/*', 'src/**/*'],
    tasks: 'clean lint:files concat jst copyassets',

    min: {
      files: ['assets/**/*', 'src/**/*'],
      tasks: 'default'
    }
  },

  clean: {
    folder: 'dist/'
  }
});

task.registerBasicTask('clean', 'Deletes out all contents in a directory', function(data, name) {
  var errorcount = fail.errorcount;
  var folder = path.resolve(data);

  // Delete all files inside the folder
  task.helper('clean', folder);
});

task.registerHelper('clean', function(folder) {
  rimraf.sync(folder);
});

task.registerBasicTask('jst', 'Compile underscore templates to JST file', function(data, name) {
  // If namespace is specified use that, otherwise fallback
  var namespace = config('jst.namespace') || 'JST';
  // If template settings are available use those
  var templateSettings = config('jst.templateSettings') || null;

  // Create JST file.
  var errorcount = fail.errorcount;
  var files = file.expand(data);
  file.write(name, task.helper('jst', files, namespace, templateSettings));

  // Fail task if there were errors.
  if (fail.errorcount > errorcount) { return(false); }

  // Otherwise, print a success message.
  log.writeln('File "' + name + '" created.');
});

task.registerHelper('jst', function(files, namespace, templateSettings) {
  // Pulled from underscore 1.2.4
  function underscoreTemplating(str) {
      // Merge in the templateSettings that may be passed
      var c  = _.extend({}, _.templateSettings, templateSettings) ||
        _.templateSettings;

      var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
        'with(obj||{}){__p.push(\'' +
        str.replace(/\\/g, '\\\\')
           .replace(/'/g, '\\\'')
           .replace(c.escape || noMatch, function(match, code) {
             return("',_.escape(" + code.replace(/\\'/g, "'") + "),'");
           })
           .replace(c.interpolate || noMatch, function(match, code) {
             return("'," + code.replace(/\\'/g, "'") + ",'");
           })
           .replace(c.evaluate || noMatch, function(match, code) {
             return("');" + code.replace(/\\'/g, "'")
                                .replace(/[\r\n\t]/g, ' ')
                                .replace(/\\\\/g, '\\') + ";__p.push('");
           })
           .replace(/\r/g, '\\r')
           .replace(/\n/g, '\\n')
           .replace(/\t/g, '\\t')
           + "');}return(__p.join(''));";

      return(new Function('obj', '_', tmpl).toString());
  };

  namespace = "this['" + namespace + "']";

  // Comes out looking like this["JST"] = this["JST"] || {};
  var contents = namespace + " = " + namespace + " || {};\n\n";

  // Compile the template and get the function source
  contents += files ? files.map(function(filepath) {
    var templateFunction = [
      "function(data) { ",
        "return ",
        underscoreTemplating(file.read(filepath)).replace("anonymous", ""),
        "(data, _)",
      "};"].join("");

    return(namespace + "['" + filepath + "'] = " + templateFunction);
  }).join("\n\n") : "";

  return(contents);
});

task.registerBasicTask('mincss', 'Compress down CSS files cleanly.', function(data, name) {
  // Minify CSS.
  var errorcount = fail.errorcount;
  var files = file.expand(data);
  file.write(name, task.helper('mincss', files));

  // Fail task if there were errors.
  if (fail.errorcount > errorcount) { return(false); }

  // Otherwise, print a success message.
  log.writeln('File \'' + name + '\' created.');
});

task.registerHelper('mincss', function(files) {
  // Minify and combine all CSS
  return(files ? files.map(function(filepath) {
    return(cleanCSS.process(file.read(filepath)));
  }).join('') : '');
});

task.registerBasicTask('copyassets', '', function(data, name) {
  var distProductionDirectory = config(['meta', 'dist', 'production', 'directory']);
  var distDevelopmentDirectory = config(['meta', 'dist', 'development', 'directory']);
  var errorCallback = function(error) {
    if (error) {
      console.log('Failed to copy ' + this.source + ' into ' + this.destination);
      console.error(error);
    } else {
      console.log('Copied ' + this.source + ' into ' + this.destination);
    }
  };

  var source;
  var destination;
  data.forEach(function(file) {
    source = file;
    destination = distDevelopmentDirectory + path.basename(file);
    fsTools.copy(file, destination, underscore.bind(errorCallback, { source: source, destination: destination }));
    destination = distProductionDirectory + path.basename(file);
    fsTools.copy(source, destination, underscore.bind(errorCallback, { source: source, destination: destination }));
  });
});

task.registerTask('default', 'clean lint:files concat jst min mincss copyassets');
<commit_msg>Set up order for concatenated libs.<commit_after>var cleanCSS = require('clean-css');
var fs = require('fs');
var fsTools = require('fs-tools');
var grunt = require('grunt');
var path = require('path');
var rimraf = require('rimraf');
var util = require('util');

config.init({
  meta: {
    dist: {
      production: {
        directory: './dist/production/'
      },

      development: {
        directory: './dist/development/'
      }
    }
  },

  lint: {
    files: [
      'grunt.js',
      'src/**/*.js'
    ]
  },

  concat: {
    'dist/development/javascripts/libs.js': [
      'vendor/javascripts/underscore-*.js',
      'vendor/javascripts/jquery-*.js',
      'vendor/javascripts/backbone-*.js',
      'vendor/javascripts/jquery.cross-slide-*.js'
    ],
    'dist/development/javascripts/app.js': ['src/werld.js', 'src/**/*.js'],
    'dist/development/stylesheets/index.css': [
      'vendor/stylesheets/*.css',
      'assets/stylesheets/webfonts.css',
      'assets/stylesheets/style.css'
    ],
    'dist/development/stylesheets/play.css': [
      'vendor/stylesheets/*.css',
      'assets/stylesheets/webfonts.css',
      'assets/stylesheets/canvas.css'
    ]
  },

  jst: {
    'dist/development/javascripts/templates.js': ['src/templates/*.html']
  },

  min: {
    'dist/production/javascripts/libs.js': ['dist/development/javascripts/libs.js'],
    'dist/production/javascripts/app.js': ['dist/development/javascripts/app.js'],
    'dist/production/javascripts/templates.js': ['dist/development/javascripts/templates.js']
  },

  mincss: {
    'dist/production/stylesheets/index.css': ['dist/development/stylesheets/index.css'],
    'dist/production/stylesheets/play.css': ['dist/development/stylesheets/play.css']
  },

  copyassets: {
    files: [
      'assets/index.html',
      'assets/play.html',
      'assets/favicon.ico',
      'assets/images/',
      'assets/sounds/',
      'assets/webfonts/'
    ]
  },

  watch: {
    files: ['assets/**/*', 'src/**/*'],
    tasks: 'clean lint:files concat jst copyassets',

    min: {
      files: ['assets/**/*', 'src/**/*'],
      tasks: 'default'
    }
  },

  clean: {
    folder: 'dist/'
  }
});

task.registerBasicTask('clean', 'Deletes out all contents in a directory', function(data, name) {
  var errorcount = fail.errorcount;
  var folder = path.resolve(data);

  // Delete all files inside the folder
  task.helper('clean', folder);
});

task.registerHelper('clean', function(folder) {
  rimraf.sync(folder);
});

task.registerBasicTask('jst', 'Compile underscore templates to JST file', function(data, name) {
  // If namespace is specified use that, otherwise fallback
  var namespace = config('jst.namespace') || 'JST';
  // If template settings are available use those
  var templateSettings = config('jst.templateSettings') || null;

  // Create JST file.
  var errorcount = fail.errorcount;
  var files = file.expand(data);
  file.write(name, task.helper('jst', files, namespace, templateSettings));

  // Fail task if there were errors.
  if (fail.errorcount > errorcount) { return(false); }

  // Otherwise, print a success message.
  log.writeln('File "' + name + '" created.');
});

task.registerHelper('jst', function(files, namespace, templateSettings) {
  // Pulled from underscore 1.2.4
  function underscoreTemplating(str) {
      // Merge in the templateSettings that may be passed
      var c  = _.extend({}, _.templateSettings, templateSettings) ||
        _.templateSettings;

      var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
        'with(obj||{}){__p.push(\'' +
        str.replace(/\\/g, '\\\\')
           .replace(/'/g, '\\\'')
           .replace(c.escape || noMatch, function(match, code) {
             return("',_.escape(" + code.replace(/\\'/g, "'") + "),'");
           })
           .replace(c.interpolate || noMatch, function(match, code) {
             return("'," + code.replace(/\\'/g, "'") + ",'");
           })
           .replace(c.evaluate || noMatch, function(match, code) {
             return("');" + code.replace(/\\'/g, "'")
                                .replace(/[\r\n\t]/g, ' ')
                                .replace(/\\\\/g, '\\') + ";__p.push('");
           })
           .replace(/\r/g, '\\r')
           .replace(/\n/g, '\\n')
           .replace(/\t/g, '\\t')
           + "');}return(__p.join(''));";

      return(new Function('obj', '_', tmpl).toString());
  };

  namespace = "this['" + namespace + "']";

  // Comes out looking like this["JST"] = this["JST"] || {};
  var contents = namespace + " = " + namespace + " || {};\n\n";

  // Compile the template and get the function source
  contents += files ? files.map(function(filepath) {
    var templateFunction = [
      "function(data) { ",
        "return ",
        underscoreTemplating(file.read(filepath)).replace("anonymous", ""),
        "(data, _)",
      "};"].join("");

    return(namespace + "['" + filepath + "'] = " + templateFunction);
  }).join("\n\n") : "";

  return(contents);
});

task.registerBasicTask('mincss', 'Compress down CSS files cleanly.', function(data, name) {
  // Minify CSS.
  var errorcount = fail.errorcount;
  var files = file.expand(data);
  file.write(name, task.helper('mincss', files));

  // Fail task if there were errors.
  if (fail.errorcount > errorcount) { return(false); }

  // Otherwise, print a success message.
  log.writeln('File \'' + name + '\' created.');
});

task.registerHelper('mincss', function(files) {
  // Minify and combine all CSS
  return(files ? files.map(function(filepath) {
    return(cleanCSS.process(file.read(filepath)));
  }).join('') : '');
});

task.registerBasicTask('copyassets', '', function(data, name) {
  var distProductionDirectory = config(['meta', 'dist', 'production', 'directory']);
  var distDevelopmentDirectory = config(['meta', 'dist', 'development', 'directory']);
  var errorCallback = function(error) {
    if (error) {
      console.log('Failed to copy ' + this.source + ' into ' + this.destination);
      console.error(error);
    } else {
      console.log('Copied ' + this.source + ' into ' + this.destination);
    }
  };

  var source;
  var destination;
  data.forEach(function(file) {
    source = file;
    destination = distDevelopmentDirectory + path.basename(file);
    fsTools.copy(file, destination, underscore.bind(errorCallback, { source: source, destination: destination }));
    destination = distProductionDirectory + path.basename(file);
    fsTools.copy(source, destination, underscore.bind(errorCallback, { source: source, destination: destination }));
  });
});

task.registerTask('default', 'clean lint:files concat jst min mincss copyassets');
<|endoftext|>


<commit_before>(function(root, definition) {
    if (typeof define === 'function' && define.amd) {
        define([], definition);
    } else {
        root.NotifyMe = definition();
    }
})(this, function() {
    var defaultOptions = {
        icon: 'http://i.istockimg.com/file_thumbview_approve/46749378/3/stock-illustration-46749378-cute-piglet-icon-animal-icons-series.jpg',
        lang: 'en-US'
    };

    function extend(base, extension) {
        var extended = {};
        for (var key in base) {
            extended[key] = base[key];
        }
        for (var key in extension) {
            if (extension.hasOwnProperty(key)) {
                if (extension[key].constructor === Object) {
                    base[key] = extend(base[key], extension[key]);
                } else {
                    base[key] = extension[key];
                }
            }
        }
        return extended;
    }

    function generateTag() {
        return Math.floor(Math.random() * 0x10000000).toString(16);
    }

    function NotifyMe(title, body, options) {
        if (!(this instanceof NotifyMe)) {
            return new NotifyMe(title, body, options);
        }
        this.title = title;
        this.options = extend(defaultOptions, options);
        this.options.body = body;
        this.options.tag = generateTag();
    }

    NotifyMe.permissionGranted = false;

    NotifyMe.requestPermission = function() {
        return new Promise(function(resolve, reject) {
            Notification.requestPermission(function(permission) {
                NotifyMe.permissionGranted = permission === 'granted';
                if (NotifyMe.permissionGranted) {
                    resolve();
                } else {
                    reject();
                }
            });
        });
    };

    NotifyMe.prototype.launch = function() {
        if (NotifyMe.permissionGranted) {
            this.notification = new Notification(this.title, this.options);
            this.notification.onclick = this.options.onclick;
            this.notification.onerror = this.options.onerror;
            this.notification.onclose = this.options.onclose;
            return Promise.resolve(this.notification);
        } else {
            return NotifyMe.requestPermission()
                .then(this.launch.bind(this))
                .catch(console.warn.bind(console));
        }
    };

    return NotifyMe;
});
<commit_msg>cut up url to fit within line length limit<commit_after>(function(root, definition) {
    if (typeof define === 'function' && define.amd) {
        define([], definition);
    } else {
        root.NotifyMe = definition();
    }
})(this, function() {
    var defaultOptions = {
        icon: 'http://i.istockimg.com/file_thumbview_approve/46749378/3/'
            + 'stock-illustration-46749378-cute-piglet-icon-animal-icons'
            + '-series.jpg',
        lang: 'en-US'
    };

    function extend(base, extension) {
        var extended = {};
        for (var key in base) {
            extended[key] = base[key];
        }
        for (var key in extension) {
            if (extension.hasOwnProperty(key)) {
                if (extension[key].constructor === Object) {
                    base[key] = extend(base[key], extension[key]);
                } else {
                    base[key] = extension[key];
                }
            }
        }
        return extended;
    }

    function generateTag() {
        return Math.floor(Math.random() * 0x10000000).toString(16);
    }

    function NotifyMe(title, body, options) {
        if (!(this instanceof NotifyMe)) {
            return new NotifyMe(title, body, options);
        }
        this.title = title;
        this.options = extend(defaultOptions, options);
        this.options.body = body;
        this.options.tag = generateTag();
    }

    NotifyMe.permissionGranted = false;

    NotifyMe.requestPermission = function() {
        return new Promise(function(resolve, reject) {
            Notification.requestPermission(function(permission) {
                NotifyMe.permissionGranted = permission === 'granted';
                if (NotifyMe.permissionGranted) {
                    resolve();
                } else {
                    reject();
                }
            });
        });
    };

    NotifyMe.prototype.launch = function() {
        if (NotifyMe.permissionGranted) {
            this.notification = new Notification(this.title, this.options);
            this.notification.onclick = this.options.onclick;
            this.notification.onerror = this.options.onerror;
            this.notification.onclose = this.options.onclose;
            return Promise.resolve(this.notification);
        } else {
            return NotifyMe.requestPermission()
                .then(this.launch.bind(this))
                .catch(console.warn.bind(console));
        }
    };

    return NotifyMe;
});
<|endoftext|>


<commit_before>'use strict';

var number = Math.floor(Math.random() * 22) + 1;
var timer1 = 0;
var timer2 = 0;

 function setSlide(noSlide) {
      clearTimeout(timer1);
      clearTimeout(timer2);
      number = noSlide - 1;
      hide();
      setTimeout("changeSlide()", 500);
 }

function hide() {
    $("#slider").fadeOut(500);
}

function changeSlide() {
    number++;
    if (number > 22) {
        number = 1;
    };
    var file = `<img src="../images/slides/slide${number}.jpg"/>`;
    document.getElementById("slider").innerHTML = file;
    $("#slider").fadeIn(500);
    timer1 = setTimeout("changeSlide()", 5000);
    timer2 = setTimeout("hide()", 4500);
}<commit_msg>#37 feature-37 (#42)<commit_after>'use strict';
var numberOfSlides = 22;
var number = Math.floor(Math.random() * numberOfSlides) + 1;
var timer1 = 0;
var timer2 = 0;

 function setSlide(noSlide) {
      clearTimeout(timer1);
      clearTimeout(timer2);
      number = noSlide - 1;
      hide();
      setTimeout("changeSlide()", 500);
 }

function hide() {
    $("#slider").fadeOut(500);
}

function changeSlide() {
    number++;
    if (number > numberOfSlides) {
        number = 1;
    };
    var file = `<img src="../images/slides/slide${number}.jpg"/>`;
    document.getElementById("slider").innerHTML = file;
    $("#slider").fadeIn(500);
    timer1 = setTimeout("changeSlide()", 5000);
    timer2 = setTimeout("hide()", 4500);
}<|endoftext|>


<commit_before>require('shelljs/global');
var inquirer = require('inquirer');

var q1 = {
  name: 'shortname',
  message: 'What is your component\'s short-name? (e.g., `rick-roll` for aframe-rick-roll-component, `<a-entity rick-roll="true">`)',
  type: 'input'
};

var q2 = {
  name: 'longname',
  message: 'What is your component\'s long-name? (e.g., `Rick Roll` for A-Frame Rick Roll Component)',
  type: 'input'
};

var q3 = {
  name: 'repo',
  message: 'Where is your component on Github? (e.g., yourusername/aframe-rick-roll-component)',
  type: 'input'
};

var q4 = {
  name: 'author',
  message: 'Who are you? (e.g., Jane John <jj@example.com>)',
  type: 'input'
};

ls('README.md').forEach(function (file) {
  sed('-i', '1,/## aframe-example-component/d', file);
});

inquirer.prompt([q1, q2], function (ans) {
  ls('index.js package.json README.md').forEach(function(file) {
    sed('-i', 'aframe-example-component', 'aframe-' + ans.shortname + '-component', file);
    sed('-i', 'Example Component', ans.longname + ' Component', file);
    sed('-i', "'example'", "'" + ans.shortname + "'", file);
  });

  ls('README.md').forEach(function (file) {
    sed('-i', 'example component', ans.longname + ' component', file);
    sed('-i', 'example=', ans.shortname + '=', file);
  });

  find('examples').filter(function (file) { return file.match(/\.html/); }).forEach(function (file) {
    sed('-i', 'Example Component', ans.longname + ' Component', file);
  });

  ls('package.json README.md').forEach(function (file) {
    sed('-i', 'ngokevin/aframe-component-boilerplate', ans.repo, file);
    sed('-i', 'Kevin Ngo <me@ngokevin.com>', ans.author, file);
  });
});
<commit_msg>update unboil<commit_after>require('shelljs/global');
var inquirer = require('inquirer');

var q1 = {
  name: 'shortname',
  message: 'What is your component\'s short-name? (e.g., `rick-roll` for aframe-rick-roll-component, `<a-entity rick-roll="true">`)',
  type: 'input'
};

var q2 = {
  name: 'longname',
  message: 'What is your component\'s long-name? (e.g., `Rick Roll` for A-Frame Rick Roll Component)',
  type: 'input'
};

var q3 = {
  name: 'repo',
  message: 'Where is your component on Github? (e.g., yourusername/aframe-rick-roll-component)',
  type: 'input'
};

var q4 = {
  name: 'author',
  message: 'Who are you? (e.g., Jane John <jj@example.com>)',
  type: 'input'
};

ls('README.md').forEach(function (file) {
  sed('-i', '1,/aframe-example-component/d', file);
});

inquirer.prompt([q1, q2, q3, q4], function (ans) {
  ls(['index.js', 'package.json', 'README.md']).forEach(function(file) {
    sed('-i', 'aframe-example-component', 'aframe-' + ans.shortname + '-component', file);
    sed('-i', 'Example Component', ans.longname + ' Component', file);
    sed('-i', 'Example component', ans.longname + ' component', file);
    sed('-i', "'example'", "'" + ans.shortname + "'", file);
  });

  ls('README.md').forEach(function (file) {
    sed('-i', 'example component', ans.longname + ' component', file);
    sed('-i', 'example=', ans.shortname + '=', file);
  });

  find('examples').filter(function (file) { return file.match(/\.html/); }).forEach(function (file) {
    sed('-i', 'Example Component', ans.longname + ' Component', file);
  });

  ls(['package.json', 'README.md']).forEach(function (file) {
    sed('-i', 'aframe-example-component', 'aframe-' + ans.shortname + '-component', file);
    sed('-i', 'ngokevin/aframe-component-boilerplate', ans.repo, file);
    sed('-i', 'Kevin Ngo <me@ngokevin.com>', ans.author, file);
  });
});
<|endoftext|>


<commit_before>/*
 * A widget to show and control the system volume.
 */
define(['jquery', './socket'], function ($, socket) {
  "use strict";

  var UID_RE = /Uid:\t(\d+)/;

  var VOLUME_RE = /set-sink-volume.+ ([^ \n]+)/;
  var MUTE_RE = /set-sink-mute.+ ([^ \n]+)/;

  var MAX_VOLUME = 0x10000;

  var WAVES = 5;

  function uid() {
    return $.ajax('/proc/self/status')
    .then(function (result) {
      return +UID_RE.exec(result)[1];
    });
  }

  uid().done(function (uid) {
    var pulseSocket = socket('/var/run/user/' + uid + '/pulse/cli');
    pulseSocket.recv.add(function (dump) {
      var mute = MUTE_RE.exec(dump)[1] === "on";
      var volume = parseInt(VOLUME_RE.exec(dump)[1], 16) / MAX_VOLUME;

      var widget = $('.widget-volume');
      widget.empty();

      var speaker = $('<div />').css({
        'float': 'left',
        'border-top': '4px solid transparent',
        'border-bottom': '4px solid transparent',
        'border-right': '5px solid black',
        'margin-top': 5,
        'margin-bottom': 5,
        'margin-right': 2
      }).append($('<div />').css({
        'background': 'black',
        'width': 4,
        'height': 5
      }));
      widget.append(speaker);

      var waves = $('<div />').css({
        'float': 'left',
        'height': '100%',
        'margin-top': 5,
        'margin-bottom': 5,
        'width': 12
      });
      if (mute) {
        waves.append('x');
      } else {
        for (var i = 0; i < volume * WAVES; i ++) {
          var waveSize = 6 + i * 2;
          var margin = 10 - waveSize / 2;
          var wave = $('<div />').css({
            'display': 'inline-block',
            'width': 1,
            'height': waveSize,
            'margin': 1,
            'background': 'black',
            'margin-bottom': margin
          });
          waves.append(wave);
        }
      }
      widget.append(waves);
    });

    function requestDump () {
      pulseSocket.send('dump\n');
    }

    requestDump();
    window.setInterval(requestDump, 1000);
  });
});
<commit_msg>Percentage<commit_after>/*
 * A widget to show and control the system volume.
 */
define(['jquery', './socket'], function ($, socket) {
  "use strict";

  var UID_RE = /Uid:\t(\d+)/;

  var VOLUME_RE = /set-sink-volume.+ ([^ \n]+)/;
  var MUTE_RE = /set-sink-mute.+ ([^ \n]+)/;

  var MAX_VOLUME = 0x10000;

  var WAVES = 5;

  function uid() {
    return $.ajax('/proc/self/status')
    .then(function (result) {
      return +UID_RE.exec(result)[1];
    });
  }

  uid().done(function (uid) {
    var pulseSocket = socket('/var/run/user/' + uid + '/pulse/cli');
    pulseSocket.recv.add(function (dump) {
      var mute = MUTE_RE.exec(dump)[1] === "on";
      var volume = parseInt(VOLUME_RE.exec(dump)[1], 16) / MAX_VOLUME;

      var widget = $('.widget-volume');
      widget.empty();

      var speaker = $('<div />').css({
        'float': 'left',
        'border-top': '4px solid transparent',
        'border-bottom': '4px solid transparent',
        'border-right': '5px solid black',
        'margin-top': 5,
        'margin-bottom': 5,
        'margin-right': 2
      }).append($('<div />').css({
        'background': 'black',
        'width': 4,
        'height': 5
      }));
      widget.append(speaker);

      var waves = $('<div />').css({
        'float': 'left',
        'height': '100%',
        'margin-top': 5,
        'margin-bottom': 5,
        'width': 12
      });
      if (mute) {
        waves.append('x');
      } else {
        for (var i = 0; i < volume * WAVES; i ++) {
          var waveSize = 6 + i * 2;
          var margin = 10 - waveSize / 2;
          var wave = $('<div />').css({
            'display': 'inline-block',
            'width': 1,
            'height': waveSize,
            'margin': 1,
            'background': 'black',
            'margin-bottom': margin
          });
          waves.append(wave);
        }
      }
      widget.append(waves);

      var percentage = volume.toFixed(2) * 100;
      widget.attr('title', percentage + '%');
    });

    function requestDump () {
      pulseSocket.send('dump\n');
    }

    requestDump();
    window.setInterval(requestDump, 1000);
  });
});
<|endoftext|>


<commit_before>/**
 * We.js default controller prototype
 *
 * All controllers is instance of this Controller prototype and have all actions defined here
 */
var _ = require('lodash');

/**
 * Constructor
 */
function Controller(attrs) {
  for(var attr in attrs) {
    if (attrs[attr].bind) {
      this[attr] = attrs[attr].bind(this);
    } else {
      this[attr] = attrs[attr];
    }
  }
}

/**
 * Default find action
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.find = function findAll(req, res, next) {
  return res.locals.Model.findAndCountAll(res.locals.query)
  .then(function (record) {
    if (!record) return next();

    res.locals.metadata.count = record.count;
    res.locals.data = record.rows;

    return res.ok();
  }).catch(res.queryError);
}

/**
 * Default findOne action
 *
 * Record is preloaded in context loader by default and is avaible as res.locals.data
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.findOne = function findOne(req, res, next) {
  if (!res.locals.data) return next();

  req.we.hooks.trigger('we:after:send:ok:response', {
    res: res, req: req
  }, function (err) {
    if (err) return res.serverError(err);
    return res.ok();
  });
};

/**
 * Create and create page actions
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.create = function create(req, res) {
  if (!res.locals.template) res.locals.template = res.locals.model + '/' + 'create';

  if (!res.locals.data) res.locals.data = {};

   _.merge(res.locals.data, req.query);

  if (req.method === 'POST') {
    if (req.isAuthenticated()) req.body.creatorId = req.user.id;

    // set temp record for use in validation errors
    res.locals.data = req.query;
    _.merge(res.locals.data, req.body);

    return res.locals.Model.create(req.body)
    .then(function (record) {
      res.locals.data = record;
      res.created();
    }).catch(res.queryError);
  } else {
    res.locals.data = req.query;
    res.ok();
  }
};

/**
 * Edit, edit page and update action
 *
 * Record is preloaded in context loader by default and is avaible as res.locals.data
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.edit = function edit(req, res) {
  if (!res.locals.template) res.locals.template = res.local.model + '/' + 'edit';

  var record = res.locals.data;

  if (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH') {
    if (!record) return res.notFound();

    record.updateAttributes(req.body)
    .then(function() {
      res.locals.data = record;
      return res.updated();
    }).catch(res.queryError);
  } else {
    res.ok();
  }
};

/**
 * Delete and delete action
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.delete = function deletePage(req, res) {
  if (!res.locals.template)
    res.locals.template = res.local.model + '/' + 'delete';

  var record = res.locals.data;
  if (!record) return res.notFound();

  res.locals.deleteMsg = res.locals.model+'.delete.confirm.msg';

  if (req.method === 'POST' || req.method === 'DELETE') {
    record.destroy().then(function() {
      res.locals.deleted = true;
      return res.deleted();
    }).catch(res.queryError);
  } else {
    return res.ok();
  }
}

// TODO
//
// Controller.prototype.getAttribute = function getAttribute(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.updateAttribute = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.deleteAttribute = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.addRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.removeRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.getRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

module.exports = Controller;
<commit_msg>update default find action<commit_after>/**
 * We.js default controller prototype
 *
 * All controllers is instance of this Controller prototype and have all actions defined here
 */
var _ = require('lodash');

/**
 * Constructor
 */
function Controller(attrs) {
  for(var attr in attrs) {
    if (attrs[attr].bind) {
      this[attr] = attrs[attr].bind(this);
    } else {
      this[attr] = attrs[attr];
    }
  }
}

/**
 * Default find action
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.find = function findAll(req, res) {
  return res.locals.Model.findAndCountAll(res.locals.query)
  .then(function (record) {
    res.locals.metadata.count = record.count;
    res.locals.data = record.rows;
    return res.ok();
  }).catch(res.queryError);
}

/**
 * Default findOne action
 *
 * Record is preloaded in context loader by default and is avaible as res.locals.data
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.findOne = function findOne(req, res, next) {
  if (!res.locals.data) return next();

  req.we.hooks.trigger('we:after:send:ok:response', {
    res: res, req: req
  }, function (err) {
    if (err) return res.serverError(err);
    return res.ok();
  });
};

/**
 * Create and create page actions
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.create = function create(req, res) {
  if (!res.locals.template) res.locals.template = res.locals.model + '/' + 'create';

  if (!res.locals.data) res.locals.data = {};

   _.merge(res.locals.data, req.query);

  if (req.method === 'POST') {
    if (req.isAuthenticated()) req.body.creatorId = req.user.id;

    // set temp record for use in validation errors
    res.locals.data = req.query;
    _.merge(res.locals.data, req.body);

    return res.locals.Model.create(req.body)
    .then(function (record) {
      res.locals.data = record;
      res.created();
    }).catch(res.queryError);
  } else {
    res.locals.data = req.query;
    res.ok();
  }
};

/**
 * Edit, edit page and update action
 *
 * Record is preloaded in context loader by default and is avaible as res.locals.data
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.edit = function edit(req, res) {
  if (!res.locals.template) res.locals.template = res.local.model + '/' + 'edit';

  var record = res.locals.data;

  if (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH') {
    if (!record) return res.notFound();

    record.updateAttributes(req.body)
    .then(function() {
      res.locals.data = record;
      return res.updated();
    }).catch(res.queryError);
  } else {
    res.ok();
  }
};

/**
 * Delete and delete action
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.delete = function deletePage(req, res) {
  if (!res.locals.template)
    res.locals.template = res.local.model + '/' + 'delete';

  var record = res.locals.data;
  if (!record) return res.notFound();

  res.locals.deleteMsg = res.locals.model+'.delete.confirm.msg';

  if (req.method === 'POST' || req.method === 'DELETE') {
    record.destroy().then(function() {
      res.locals.deleted = true;
      return res.deleted();
    }).catch(res.queryError);
  } else {
    return res.ok();
  }
}

// TODO
//
// Controller.prototype.getAttribute = function getAttribute(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.updateAttribute = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.deleteAttribute = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.addRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.removeRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.getRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

module.exports = Controller;
<|endoftext|>