<commit_before>// SETTINGS
// ============================================
const gulp = require('gulp');
const del = require('del');
const riot = require('gulp-riot');
const concat = require('gulp-concat');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const sort = require('gulp-natural-sort')
const uglify = require('gulp-uglify');
const sequence = require('run-sequence');
const webserver = require('gulp-webserver-fast');
const plumber = require("gulp-plumber");
const rename = require('gulp-rename');
const eslint = require('gulp-eslint');
const htmlhint = require("gulp-htmlhint");
const escape = require('./gulp-code-escape');
const rimraf = require('rimraf');

const watch_target = [
  'tags/**/*',
  'index.js'
];
const demo_watch_target = [
  'docs/tags/**/*.tag'
]

// TASK
// ============================================
gulp.task('default', function () {
  return sequence(
    'webserver',
    'htmlhint',
    'eslint',
    'clean',
    'build',
    'demo_build',
    'watch',
    'demo_watch'
  );
});

gulp.task('clean', function () {
  return del([
    'dist/**/*'
  ]);
});

gulp.task('build', function () {
  return sequence(
    'compile',
    'concat',
    'compress',
    'demo_copy'
  );
});

gulp.task('compile', function () {
  return gulp.src('tags/**/*.tag')
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest('dist/'));
});

gulp.task('concat', function () {
  return gulp.src(['dist/**/*.js', '!dist/semantic-ui-riot.*js'])
    .pipe(sort())
    .pipe(concat('semantic-ui-riot.js'))
    .pipe(gulp.dest('dist/'));
});

gulp.task('compress', function (cb) {
  return gulp.src('dist/semantic-ui-riot.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(rename('semantic-ui-riot.min.js'))
    .pipe(gulp.dest('dist/'));
});

gulp.task('watch', function () {
  gulp.watch(watch_target, function () {
    sequence(
      'htmlhint',
      'eslint',
      'clean',
      'build'
    );
  });
});

gulp.task('eslint', function () {
  return gulp.src(['**/*.tag', 'test/spec/**/*.js', '!node_modules/**'])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('htmlhint', function () {
  return gulp.src(['**/*.tag', '!node_modules/**'])
    .pipe(plumber())
    .pipe(htmlhint('.htmlhintrc'))
    .pipe(htmlhint.failReporter())
})

// for demo
gulp.task('demo_watch', function () {
  gulp.watch(demo_watch_target, function () {
    sequence(
      'demo_build'
    );
  });
});

gulp.task('demo_build', function () {
  return sequence(
    'demo_escape',
    'demo_htmlhint',
    'demo_compile',
    'demo_concat',
    'demo_browserify',
    'demo_compress',
    'demo_clean'
  );
});

gulp.task('demo_escape', function () {
  return gulp.src('docs/tags/**/*.tag')
    .pipe(escape())
    .pipe(gulp.dest('docs/temp/'));
});

gulp.task('demo_htmlhint', function () {
  return gulp.src('docs/temp/**/*.tag')
    .pipe(plumber())
    .pipe(htmlhint('.htmlhintrc'))
    .pipe(htmlhint.failReporter())
})

gulp.task('demo_compile', function () {
  return gulp.src('docs/temp/**/*.tag')
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest('docs/temp/'));
});

gulp.task('demo_concat', function () {
  return gulp.src('docs/temp/**/*.js')
    .pipe(sort())
    .pipe(concat('temp.js'))
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_browserify', function () {
  browserify({
    entries: 'docs/temp.js'
  })
    .transform(babelify)
    .bundle()
    .pipe(source('build.js'))
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_compress', function (cb) {
  return gulp.src('docs/build.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_clean', function (cb) {
  return del([
    '**/temp.js'
    , 'docs/temp'
  ], cb);
});

gulp.task('demo_copy', function () {
  return gulp.src('dist/semantic-ui-riot.min.js')
    .pipe(gulp.dest('docs/'))
})

gulp.task('webserver', function () {
  const target = [
    'index.html',
    'build.js',
    'semantic-ui-riot.min.js'
  ]
  return gulp.src('./docs')
    .pipe(webserver({
      port: 3000,
      livereload: {
        enable: true,
        filter: function (fileName) {
          return target.indexOf(fileName) >= 0
        }
      },
      directoryListening: true,
      open: true
    }));
});<commit_msg>Refactor gulp task<commit_after>// SETTINGS
// ============================================
const gulp = require('gulp');
const del = require('del');
const riot = require('gulp-riot');
const concat = require('gulp-concat');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const sort = require('gulp-natural-sort')
const uglify = require('gulp-uglify');
const sequence = require('run-sequence');
const webserver = require('gulp-webserver-fast');
const plumber = require("gulp-plumber");
const rename = require('gulp-rename');
const eslint = require('gulp-eslint');
const htmlhint = require("gulp-htmlhint");
const escape = require('./gulp-code-escape');
const rimraf = require('rimraf');

const watch_target = [
  'tags/**/*',
  'index.js'
];
const demo_watch_target = [
  'docs/tags/**/*.tag'
]

// ===================================================================================
//                                                                             Default
//                                                                             =======
gulp.task('default', function () {
  return sequence(
    'webserver',
    'watch',
    'demo_watch'
  );
});

// ===================================================================================
//                                                                               Build
//                                                                               =====
gulp.task('watch', function () {
  gulp.watch(watch_target, function () {
    sequence(
      'build'
    );
  });
});

gulp.task('build', function () {
  return sequence(
    'clean',
    'htmlhint',
    'eslint',
    'compile',
    'concat',
    'compress',
    'demo_copy'
  );
});

gulp.task('clean', function () {
  return del([
    'dist/**/*'
  ]);
});

gulp.task('htmlhint', function () {
  return gulp.src(['**/*.tag', '!node_modules/**'])
    .pipe(plumber())
    .pipe(htmlhint('.htmlhintrc'))
    .pipe(htmlhint.failReporter())
});

gulp.task('eslint', function () {
  return gulp.src(['**/*.tag', 'test/spec/**/*.js', '!node_modules/**'])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('compile', function () {
  return gulp.src('tags/**/*.tag')
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest('dist/'));
});

gulp.task('concat', function () {
  return gulp.src(['dist/**/*.js', '!dist/semantic-ui-riot.*js'])
    .pipe(sort())
    .pipe(concat('semantic-ui-riot.js'))
    .pipe(gulp.dest('dist/'));
});

gulp.task('compress', function (cb) {
  return gulp.src('dist/semantic-ui-riot.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(rename('semantic-ui-riot.min.js'))
    .pipe(gulp.dest('dist/'));
});

// ===================================================================================
//                                                                          Demo Build
//                                                                          ==========
gulp.task('demo_watch', function () {
  gulp.watch(demo_watch_target, function () {
    sequence(
      'demo_build'
    );
  });
});

gulp.task('demo_build', function () {
  return sequence(
    'demo_clean',
    'demo_escape',
    'demo_htmlhint',
    'demo_compile',
    'demo_concat',
    'demo_browserify',
    'demo_compress',
    'demo_clean'
  );
});

gulp.task('demo_clean', function (cb) {
  return del([
    '**/temp.js'
    , 'docs/temp'
  ], cb);
});

gulp.task('demo_escape', function () {
  return gulp.src('docs/tags/**/*.tag')
    .pipe(escape())
    .pipe(gulp.dest('docs/temp/'));
});

gulp.task('demo_htmlhint', function () {
  return gulp.src('docs/temp/**/*.tag')
    .pipe(plumber())
    .pipe(htmlhint('.htmlhintrc'))
    .pipe(htmlhint.failReporter())
})

gulp.task('demo_compile', function () {
  return gulp.src('docs/temp/**/*.tag')
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest('docs/temp/'));
});

gulp.task('demo_concat', function () {
  return gulp.src('docs/temp/**/*.js')
    .pipe(sort())
    .pipe(concat('temp.js'))
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_browserify', function () {
  browserify({
    entries: 'docs/temp.js'
  })
    .transform(babelify)
    .bundle()
    .pipe(source('build.js'))
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_compress', function (cb) {
  return gulp.src('docs/build.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_copy', function () {
  return gulp.src('dist/semantic-ui-riot.min.js')
    .pipe(gulp.dest('docs/'))
})

// ===================================================================================
//                                                                          Web Server
//                                                                          ==========
gulp.task('webserver', function () {
  const target = [
    'index.html',
    'build.js',
    'semantic-ui-riot.min.js'
  ]
  return gulp.src('./docs')
    .pipe(webserver({
      port: 3000,
      livereload: {
        enable: true,
        filter: function (fileName) {
          return target.indexOf(fileName) >= 0
        }
      },
      directoryListening: true,
      open: true
    }));
});<|endoftext|>


<commit_before>/* ************* Gulp Task Runner File ********************************/

//********* Plugins ***************//
var gulp = require('gulp'); //gulp package
var del = require('del'); //used for deleting public folder before running build
var sass = require('gulp-sass'); //compile .scss files; used in sass task
var cleanCSS = require('gulp-clean-css'); //to minify css files; used in sass task
var concat = require('gulp-concat'); //concat files; used in concatAndMinifyJs task
var uglify = require('gulp-uglify'); //minify js; used in concatAndMinifyJs task
var imagemin = require('gulp-imagemin'); // optimize image files; used in imageMin task
var jshint = require('gulp-jshint'); //Lint js files; used in lintJs task
var bump = require('gulp-bump'); //Version plugin; used in bumpPackage task
var runSequence = require('run-sequence'); //run tasks in sequence; used in deploy task
var git = require('gulp-git'); //run git relatd tasks; used in deploy task.
var browserSync = require('browser-sync').create(); //browserSync for change watching; used in watch task.

//******* User Variables and Functions **********//
var gitMessage = "Add version bump task, bumpPackage,  to 'gulp deploy'. ";

function handleError (err) {
  console.log(err.toString());
  process.exit(-1);
}

//************* Gulp Tasks *************//

//delete generated folder
gulp.task('clean:public', function() {
  return del.sync('public');
});

gulp.task('concatAndMinifyJs', function() {
  gulp.src(['src/assets/js/jquery.js',
            'src/assets/js/jquery.easing.js',
            'src/assets/js/scrolling-nav.js',
            'src/assets/js/back-to-top.js',
            'src/assets/js/overlay.js',
            'src/assets/js/slider.js'])
      .pipe(concat('main.min.js'))
      .pipe(uglify())
      .on('error', handleError)
      .pipe(gulp.dest('./public/assets/js/'))
      .pipe(browserSync.reload({
        stream: true
      }));
});

//compile Sass and minify resulting css
gulp.task('sass', function() {
  gulp.src('src/stylesheets/main.scss')
      .pipe(sass().on('error', sass.logError))
      .pipe(cleanCSS())
      .on('error', handleError)
      .pipe(gulp.dest('public/assets/stylesheets/'))
      .pipe(browserSync.reload({
        stream: true
      }));
});

//Optimize images
gulp.task('imageMin', function() {
    return gulp.src('src/assets/images/*')
                .pipe(imagemin())
                .on('error', handleError)
                .pipe(gulp.dest('public/assets/images'))
                .pipe(browserSync.reload({
                  stream: true
                }));
});

//Lint javascript
gulp.task('lintJs', function() {
  gulp.src(['src/assets/js/scrolling-nav.js',
            'src/assets/js/back-to-top.js',
            'src/assets/js/overlay.js',
            'src/assets/js/slider.js'])
      .pipe(jshint())
      .pipe(jshint.reporter('default'))
      .pipe(jshint.reporter('fail'));
});

//Bump version of package.json -- defaults to patch
gulp.task('bumpPackage', function() {
  gulp.src('package.json')
      .pipe(bump())
      .on('error', handleError)
      .pipe(gulp.dest('./'));
});

gulp.task('watchIndex', function() {
  gulp.src('index.html')
  .pipe(browserSync.reload({
    stream: true
  }));
});

//*********Git Tasks************//
//git add all files in source
gulp.task('add', function(){
  return gulp.src('.')
    .pipe(git.add());
});

//git commit
gulp.task('commit', function(){
  return gulp.src('.')
    .pipe(git.commit(gitMessage));
});

//git push
gulp.task('push', function(){
  git.push('origin', 'master', function (err) {
    if (err) throw err;
  });
});

//********* Build,  Deploy, and Watch Tasks ************//
gulp.task('build', ['lintJs', 'imageMin', 'sass', 'concatAndMinifyJs']);

gulp.task('deploy', function(callback) {
  runSequence('build', 'bumpPackage', 'add', 'commit', 'push', callback);
});

gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: '.'
    }
  });
});

gulp.task('watch', ['browserSync', 'sass'], function() {
  gulp.watch('src/stylesheets/**/*.scss', ['sass']);

  gulp.watch('src/assets/js/*.js', ['lintJs', 'concatAndMinifyJs']);

  gulp.watch('./index.html', ['watchIndex']);

  gulp.watch('src/assets/images/*.+(png|jpg|jpeg)', ['imageMin']);

});
<commit_msg>Fix spacing based on eslint configuration recommendations.<commit_after>/* ************* Gulp Task Runner File ********************************/

//********* Plugins ***************//
var gulp = require('gulp'); //gulp package
var del = require('del'); //used for deleting public folder before running build
var sass = require('gulp-sass'); //compile .scss files; used in sass task
var cleanCSS = require('gulp-clean-css'); //to minify css files; used in sass task
var concat = require('gulp-concat'); //concat files; used in concatAndMinifyJs task
var uglify = require('gulp-uglify'); //minify js; used in concatAndMinifyJs task
var imagemin = require('gulp-imagemin'); // optimize image files; used in imageMin task
var jshint = require('gulp-jshint'); //Lint js files; used in lintJs task
var bump = require('gulp-bump'); //Version plugin; used in bumpPackage task
var runSequence = require('run-sequence'); //run tasks in sequence; used in deploy task
var git = require('gulp-git'); //run git relatd tasks; used in deploy task.
var browserSync = require('browser-sync').create(); //browserSync for change watching; used in watch task.

//******* User Variables and Functions **********//
var gitMessage = "Add version bump task, bumpPackage,  to 'gulp deploy'. ";

function handleError (err) {
  console.log(err.toString());
  process.exit(-1);
}

//************* Gulp Tasks *************//

//delete generated folder
gulp.task('clean:public', function() {
  return del.sync('public');
});

gulp.task('concatAndMinifyJs', function() {
  gulp.src([ 'src/assets/js/jquery.js',
            'src/assets/js/jquery.easing.js',
            'src/assets/js/scrolling-nav.js',
            'src/assets/js/back-to-top.js',
            'src/assets/js/overlay.js',
            'src/assets/js/slider.js' ])
      .pipe(concat('main.min.js'))
      .pipe(uglify())
      .on('error', handleError)
      .pipe(gulp.dest('./public/assets/js/'))
      .pipe(browserSync.reload({
        stream: true
      }));
});

//compile Sass and minify resulting css
gulp.task('sass', function() {
  gulp.src('src/stylesheets/main.scss')
      .pipe(sass().on('error', sass.logError))
      .pipe(cleanCSS())
      .on('error', handleError)
      .pipe(gulp.dest('public/assets/stylesheets/'))
      .pipe(browserSync.reload({
        stream: true
      }));
});

//Optimize images
gulp.task('imageMin', function() {
    return gulp.src('src/assets/images/*')
                .pipe(imagemin())
                .on('error', handleError)
                .pipe(gulp.dest('public/assets/images'))
                .pipe(browserSync.reload({
                  stream: true
                }));
});

//Lint javascript
gulp.task('lintJs', function() {
  gulp.src([ 'src/assets/js/scrolling-nav.js',
            'src/assets/js/back-to-top.js',
            'src/assets/js/overlay.js',
            'src/assets/js/slider.js' ])
      .pipe(jshint())
      .pipe(jshint.reporter('default'))
      .pipe(jshint.reporter('fail'));
});

//Bump version of package.json -- defaults to patch
gulp.task('bumpPackage', function() {
  gulp.src('package.json')
      .pipe(bump())
      .on('error', handleError)
      .pipe(gulp.dest('./'));
});

gulp.task('watchIndex', function() {
  gulp.src('index.html')
  .pipe(browserSync.reload({
    stream: true
  }));
});

//*********Git Tasks************//
//git add all files in source
gulp.task('add', function() {
  return gulp.src ('.')
    .pipe(git.add());
});

//git commit
gulp.task('commit', function() {
  return gulp.src('.')
    .pipe(git.commit(gitMessage));
});

//git push
gulp.task('push', function() {
  git.push('origin', 'master', function (err) {
    if (err) throw err;
  });
});

//********* Build,  Deploy, and Watch Tasks ************//
gulp.task('build', [ 'lintJs', 'imageMin', 'sass', 'concatAndMinifyJs' ]);

gulp.task('deploy', function(callback) {
  runSequence('build', 'bumpPackage', 'add', 'commit', 'push', callback);
});

gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: '.'
    }
  });
});

gulp.task('watch', [ 'browserSync', 'sass' ], function() {
  gulp.watch('src/stylesheets/**/*.scss', [ 'sass' ]);

  gulp.watch('src/assets/js/*.js', [ 'lintJs', 'concatAndMinifyJs' ]);

  gulp.watch('./index.html', [ 'watchIndex' ]);

  gulp.watch('src/assets/images/*.+(png|jpg|jpeg)', [ 'imageMin' ]);

});
<|endoftext|>


<commit_before>// Load plugins
var gulp         = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var cssshrink    = require('gulp-cssshrink');
var livereload   = require('gulp-livereload');
var minifyCSS    = require('gulp-minify-css');
var rename       = require('gulp-rename');
var sass         = require('gulp-ruby-sass');
var gutil        = require('gulp-util');

// Styles
gulp.task('styles', function () {
  return gulp.src('scss/**/*.scss')
    .pipe(sass({ style: 'compact', precision: 7, sourcemap: true }))
    .on('error', gutil.log)
    .pipe(autoprefixer('last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ios 6', 'android 4'))
    .on('error', gutil.log)
    .pipe(gulp.dest('dist'));
});

// Minify
gulp.task('minify', ['styles'], function () {
  return gulp.src('dist/avalanche.css')
    .pipe(minifyCSS())
    .pipe(cssshrink())
    .pipe(rename(function (path) {
      path.basename += '.min';
    }))
    .pipe(gulp.dest('dist'))
    .pipe(livereload());
});

// Watch
gulp.task('watch', function () {
  gulp.watch('src/**/*.scss', ['styles', 'minify']);
});

// Default
gulp.task('default', function () {
  gulp.start('watch');
});<commit_msg>fixed path in gulp styles task<commit_after>// Load plugins
var gulp         = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var cssshrink    = require('gulp-cssshrink');
var livereload   = require('gulp-livereload');
var minifyCSS    = require('gulp-minify-css');
var rename       = require('gulp-rename');
var sass         = require('gulp-ruby-sass');
var gutil        = require('gulp-util');

// Styles
gulp.task('styles', function () {
  return gulp.src('src/**/*.scss')
    .pipe(sass({ style: 'compact', precision: 7, sourcemap: true }))
    .on('error', gutil.log)
    .pipe(autoprefixer('last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ios 6', 'android 4'))
    .on('error', gutil.log)
    .pipe(gulp.dest('dist'));
});

// Minify
gulp.task('minify', ['styles'], function () {
  return gulp.src('dist/avalanche.css')
    .pipe(minifyCSS())
    .pipe(cssshrink())
    .pipe(rename(function (path) {
      path.basename += '.min';
    }))
    .pipe(gulp.dest('dist'))
    .pipe(livereload());
});

// Watch
gulp.task('watch', function () {
  gulp.watch('src/**/*.scss', ['styles', 'minify']);
});

// Default
gulp.task('default', function () {
  gulp.start('watch');
});<|endoftext|>


<commit_before>var gulp = require('gulp');

var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

     if(   jshint === stylish)    {

       3 + 42     }

       i = 2
  while(i++ <= 10)
  {
    17+42;

          }

gulp.task('lint', function () {
  return gulp.src('gulpfile.js')
    .pipe(jshint()) // '.jshintrc'
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('default', ['lint']);
<commit_msg>Fail on misstyling<commit_after>var gulp = require('gulp');

var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

     if(   jshint === stylish)    {

       3 + 42     }

       i = 2
  while(i++ <= 10)
  {
    17+42;

          }

gulp.task('lint', function () {
  return gulp.src('gulpfile.js')
    .pipe(jshint()) // '.jshintrc'
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('default', ['lint']);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var fs = require('fs');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
var minimist = require('minimist');
var opn = require('opn');

var getJson = function (filepath) {
  return JSON.parse(fs.readFileSync(filepath, 'utf8'));
};
var knownOptions = {
  string: 'bump',
  default: {
    bump: 'patch'
  }
};
var options = minimist(process.argv.slice(2), knownOptions);
var banner = [
  '/*!',
  ' * Dyframe',
  ' * @version <%= pkg.version %>',
  ' * @link <%= pkg.homepage %>',
  ' * @author <%= pkg.author %>',
  ' * @license <%= pkg.license.type %>',
  ' */',
  ''].join('\n');

gulp.task('jshint', function () {
  return gulp.src(['gulpfile.js', 'src/*.js', 'demo/*.js'])
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

gulp.task('scripts', function () {
  var pkg = getJson('package.json');
  return gulp.src('src/*.js')
    .pipe($.header(banner, {pkg: pkg}))
    .pipe(gulp.dest('.'))
    .pipe($.uglify({preserveComments: 'some'}))
    .pipe($.rename({suffix: '.min'}))
    .pipe(gulp.dest('.'));
});

gulp.task('serve', function () {
  browserSync({
    server: '.',
    notify: false,
    open: false
  });
  browserSync.emitter.once('init', function () {
    opn('http://localhost:3000/demo/');
  });
  gulp.watch([
    'demo/*',
    'src/*.js'
  ]).on('change', browserSync.reload);
  gulp.watch('src/*.js', ['jshint']);
});

gulp.task('readme', function () {
  var downloadBase = 'https://github.com/htanjo/dyframe/raw/';
  var pattern = new RegExp(downloadBase + '.*?[\/]', 'g');
  var version = getJson('package.json').version;
  var downloadDir = downloadBase + 'v' + version + '/';
  return gulp.src('README.md')
    .pipe($.replace(pattern, downloadDir))
    .pipe(gulp.dest('.'));
});

gulp.task('bump', function () {
  return gulp.src(['package.json', 'bower.json'])
    .pipe($.bump({type: options.bump}))
    .pipe(gulp.dest('.'));
});

gulp.task('commit', ['build', 'readme'], function () {
  var version = getJson('package.json').version;
  return gulp.src(['package.json', 'bower.json', '*.js', 'README.md'])
    .pipe($.git.commit('Release v' + version));
});

gulp.task('tag', function (callback) {
  var version = getJson('package.json').version;
  $.git.tag('v' + version, 'Release v' + version, callback);
});

gulp.task('test', ['jshint']);

gulp.task('build', ['scripts']);

gulp.task('release', function (callback) {
  runSequence('test', 'bump', 'commit', 'tag', callback);
});

gulp.task('default', ['test']);
<commit_msg>Add build task to default<commit_after>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var fs = require('fs');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
var minimist = require('minimist');
var opn = require('opn');

var getJson = function (filepath) {
  return JSON.parse(fs.readFileSync(filepath, 'utf8'));
};
var knownOptions = {
  string: 'bump',
  default: {
    bump: 'patch'
  }
};
var options = minimist(process.argv.slice(2), knownOptions);
var banner = [
  '/*!',
  ' * Dyframe',
  ' * @version <%= pkg.version %>',
  ' * @link <%= pkg.homepage %>',
  ' * @author <%= pkg.author %>',
  ' * @license <%= pkg.license.type %>',
  ' */',
  ''].join('\n');

gulp.task('jshint', function () {
  return gulp.src(['gulpfile.js', 'src/*.js', 'demo/*.js'])
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

gulp.task('scripts', function () {
  var pkg = getJson('package.json');
  return gulp.src('src/*.js')
    .pipe($.header(banner, {pkg: pkg}))
    .pipe(gulp.dest('.'))
    .pipe($.uglify({preserveComments: 'some'}))
    .pipe($.rename({suffix: '.min'}))
    .pipe(gulp.dest('.'));
});

gulp.task('serve', function () {
  browserSync({
    server: '.',
    notify: false,
    open: false
  });
  browserSync.emitter.once('init', function () {
    opn('http://localhost:3000/demo/');
  });
  gulp.watch([
    'demo/*',
    'src/*.js'
  ]).on('change', browserSync.reload);
  gulp.watch('src/*.js', ['jshint']);
});

gulp.task('readme', function () {
  var downloadBase = 'https://github.com/htanjo/dyframe/raw/';
  var pattern = new RegExp(downloadBase + '.*?[\/]', 'g');
  var version = getJson('package.json').version;
  var downloadDir = downloadBase + 'v' + version + '/';
  return gulp.src('README.md')
    .pipe($.replace(pattern, downloadDir))
    .pipe(gulp.dest('.'));
});

gulp.task('bump', function () {
  return gulp.src(['package.json', 'bower.json'])
    .pipe($.bump({type: options.bump}))
    .pipe(gulp.dest('.'));
});

gulp.task('commit', ['build', 'readme'], function () {
  var version = getJson('package.json').version;
  return gulp.src(['package.json', 'bower.json', '*.js', 'README.md'])
    .pipe($.git.commit('Release v' + version));
});

gulp.task('tag', function (callback) {
  var version = getJson('package.json').version;
  $.git.tag('v' + version, 'Release v' + version, callback);
});

gulp.task('test', ['jshint']);

gulp.task('build', ['scripts']);

gulp.task('release', function (callback) {
  runSequence('test', 'bump', 'commit', 'tag', callback);
});

gulp.task('default', ['test', 'build']);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
  batch  = require('gulp-batch'),
  concat = require('gulp-concat'),
  ignore = require('gulp-ignore'),
  watch  = require('gulp-watch'),
  path   = require('path');

var dist = 'dist/hypermedia.js';

gulp.task('default', function(){
  var distDir = path.dirname(dist);
  return gulp.src('src/*.js')
    .pipe(ignore.exclude('*.spec.js'))
    .pipe(concat(path.basename(dist)))
    .pipe(gulp.dest(distDir))
});

gulp.task('watch', function () {
  gulp.start('default');
  watch('src/**', batch(function (events, done) {
    gulp.start('default', done);
  }));
});
<commit_msg>Add missing semicolon<commit_after>'use strict';

var gulp = require('gulp'),
  batch  = require('gulp-batch'),
  concat = require('gulp-concat'),
  ignore = require('gulp-ignore'),
  watch  = require('gulp-watch'),
  path   = require('path');

var dist = 'dist/hypermedia.js';

gulp.task('default', function(){
  var distDir = path.dirname(dist);
  return gulp.src('src/*.js')
    .pipe(ignore.exclude('*.spec.js'))
    .pipe(concat(path.basename(dist)))
    .pipe(gulp.dest(distDir));
});

gulp.task('watch', function () {
  gulp.start('default');
  watch('src/**', batch(function (events, done) {
    gulp.start('default', done);
  }));
});
<|endoftext|>


<commit_before>'use strict';

var gulp          = require('gulp-help')(require('gulp'));
var jasmine       = require('gulp-jasmine');
var SpecReporter  = require('jasmine-spec-reporter');
var jshint        = require('gulp-jshint');
var jscs          = require('gulp-jscs');
var seq           = require('gulp-sequence');
var depcheck      = require('gulp-depcheck');

require('gulp-release-tasks')(gulp);

gulp.task('test', function () {
  return gulp.src(['test/**/*.spec.js'])
        .pipe(jasmine({
          reporter: new SpecReporter()
        }));
});

gulp.task('jscs', function() {
  return gulp.src(['./src/**/*.js', './test/**/*.js', './*.js'])
    .pipe(jscs())
    .pipe(jscs.reporter())
    .pipe(jscs.reporter('fail'));
});

gulp.task('jshint', function() {
  return gulp.src(['./src/**/*.js', './test/**/*.js', './*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter())
    .pipe(jshint.reporter('fail'));
});

gulp.task('lint', seq('jshint', 'jscs'));

gulp.task('ci', seq('depcheck', 'lint', 'test'));

gulp.task('depcheck', depcheck());<commit_msg>Exclude fixtures from linting<commit_after>'use strict';

var gulp          = require('gulp-help')(require('gulp'));
var jasmine       = require('gulp-jasmine');
var SpecReporter  = require('jasmine-spec-reporter');
var jshint        = require('gulp-jshint');
var jscs          = require('gulp-jscs');
var seq           = require('gulp-sequence');
var depcheck      = require('gulp-depcheck');

require('gulp-release-tasks')(gulp);

gulp.task('test', function () {
  return gulp.src(['test/**/*.spec.js'])
        .pipe(jasmine({
          reporter: new SpecReporter()
        }));
});

gulp.task('jscs', function() {
  return gulp.src(['./src/**/*.js', './test/**/*.js', '!./test/fixtures/**/*.js', './*.js'])
    .pipe(jscs())
    .pipe(jscs.reporter())
    .pipe(jscs.reporter('fail'));
});

gulp.task('jshint', function() {
  return gulp.src(['./src/**/*.js', './test/**/*.js', '!./test/fixtures/**/*.js', './*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter())
    .pipe(jshint.reporter('fail'));
});

gulp.task('lint', seq('jshint', 'jscs'));

gulp.task('ci', seq('depcheck', 'lint', 'test'));

gulp.task('depcheck', depcheck());
<|endoftext|>


<commit_before>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

gulp.task('default', function() {
  console.log("Building inferno.min.js to 'dist' directory");
  gulp.src('./dist/inferno.js')
      .pipe(uglify())
      .pipe(rename('inferno.min.js'))
      .pipe(gulp.dest('./dist'))
      .on('error', function (error) {
          console.error('' + error);
      });
});

gulp.task('watch', function() {
    gulp.start('default');
    gulp.watch('./dist/inferno.js', ['default']);
});
<commit_msg>Fixes gulp<commit_after>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

gulp.task('default', function() {
  console.log("Building inferno.min.js to 'dist' directory");
  gulp.src('./dist/inferno.js')
      .pipe(uglify())
      .pipe(gulp.dest('./dist'))
      .pipe(rename('inferno.min.js'))
      .pipe(gulp.dest('./dist'))
      .on('error', function (error) {
          console.error('' + error);
      });
});

gulp.task('watch', function() {
    gulp.start('default');
    gulp.watch('./dist/inferno.js', ['default']);
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

var paths = {
    js: ['./gulpfile.js', './test/**/*.js'],
    scss: ['./stylesheets/_sass-lib.scss'],
    test: ['./test/**/*.js']
};

var plumberOpts = {};

gulp.task('js-lint', function () {
    return gulp.src(paths.js)
        .pipe($.jshint('.jshintrc'))
        .pipe($.plumber(plumberOpts))
        .pipe($.jscs())
        .pipe($.jshint.reporter('jshint-stylish'));
});

gulp.task('scss-lint', function() {
    gulp.src(paths.scss)
        .pipe($.scssLint())
        .pipe($.plumber(plumberOpts));
});

gulp.task('test', function () {
    return gulp.src(paths.test, {read: false})
        .pipe($.plumber(plumberOpts))
        .pipe($.mocha({reporter: 'nyan'}));
});

gulp.task('lint', ['scss-lint', 'js-lint']);
gulp.task('test', ['lint']);

gulp.task('watch', ['test'], function () {
    gulp.watch(paths.js, ['js-lint']);
    gulp.watch(paths.scss, ['scss-lint']);
    gulp.watch(paths.test, ['test']);
});

gulp.task('default', ['scss-lint', 'js-lint', 'test']);
<commit_msg>Minor style fixes<commit_after>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

var paths = {
    js: ['./gulpfile.js', './test/**/*.js'],
    scss: ['./stylesheets/_sass-lib.scss'],
    test: './test/**/*.js'
};

var plumberOpts = {};

gulp.task('js-lint', function() {
    return gulp.src(paths.js)
        .pipe($.jshint('.jshintrc'))
        .pipe($.plumber(plumberOpts))
        .pipe($.jscs())
        .pipe($.jshint.reporter('jshint-stylish'));
});

gulp.task('scss-lint', function() {
    gulp.src(paths.scss)
        .pipe($.scssLint())
        .pipe($.plumber(plumberOpts));
});

gulp.task('test', function() {
    return gulp.src(paths.test, {read: false})
        .pipe($.plumber(plumberOpts))
        .pipe($.mocha({reporter: 'nyan'}));
});

gulp.task('lint', ['scss-lint', 'js-lint']);

gulp.task('watch', 'test', function() {
    gulp.watch(paths.js, 'js-lint');
    gulp.watch(paths.scss, 'scss-lint');
    gulp.watch(paths.test, 'test');
});

gulp.task('default', ['scss-lint', 'js-lint', 'test']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var to5 = require('6to5-browserify');
var nodemon = require('gulp-nodemon');
var livereload = require('gulp-livereload');
var uglify = require('gulp-uglifyjs');
var buffer = require('vinyl-buffer');

gulp.task('clientScripts', function() {
  watchify.args.debug = true;
  var bundler = watchify(browserify(watchify.args))
  .require(__dirname + '/scripts/client/main.js', {entry: true})
  .transform(to5)
  .on('update', rebundle)
  .on('log', function(log){console.log('[watchify] ' + log);});

  function rebundle() {
    return bundler.bundle()
    .on('error', function(error){console.error(error.message);})
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./public'))
    .pipe(livereload());
  }

  return rebundle();
});

gulp.task('prodClientScripts', function() {
  process.env["NODE_ENV"] = 'production';
  return browserify({
    entries: [__dirname + '/scripts/client/main.js'],
    debug: false
  })
  .transform(to5.configure({
    sourceMap: false
  }))
  .bundle()
  .pipe(source('bundle.js'))
  .pipe(buffer())
  .pipe(uglify())
  .pipe(gulp.dest('./public'));
});

gulp.task('serverScripts', function(){
  nodemon({ script: 'app.js', watch: ['scripts/server', 'scripts/shared']})
  .on('restart', function(){
    livereload.changed();
  })
});

gulp.task('stylesheets', function(){
  gulp.watch('stylesheets/**/*', ['reload']);
});

gulp.task('views', function(){
  gulp.watch('views/**/*', ['reload']);
});

gulp.task('reload', function(){
    livereload.changed();
});

gulp.task('dev', ['clientScripts', 'serverScripts', 'stylesheets', 'views']);

gulp.task('prod', ['prodClientScripts']);

gulp.task('default', ['dev']);
<commit_msg>Fix livereloading<commit_after>var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var to5 = require('6to5-browserify');
var nodemon = require('gulp-nodemon');
var livereload = require('gulp-livereload');
var uglify = require('gulp-uglifyjs');
var buffer = require('vinyl-buffer');

gulp.task('clientScripts', function() {
  watchify.args.debug = true;
  var bundler = watchify(browserify(watchify.args))
  .require(__dirname + '/scripts/client/main.js', {entry: true})
  .transform(to5)
  .on('update', rebundle)
  .on('log', function(log){console.log('[watchify] ' + log);});

  function rebundle() {
    return bundler.bundle()
    .on('error', function(error){console.error(error.message);})
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./public'))
    .pipe(livereload());
  }

  return rebundle();
});

gulp.task('prodClientScripts', function() {
  process.env["NODE_ENV"] = 'production';
  return browserify({
    entries: [__dirname + '/scripts/client/main.js'],
    debug: false
  })
  .transform(to5.configure({
    sourceMap: false
  }))
  .bundle()
  .pipe(source('bundle.js'))
  .pipe(buffer())
  .pipe(uglify())
  .pipe(gulp.dest('./public'));
});

gulp.task('serverScripts', function(){
  nodemon({ script: 'app.js', watch: ['scripts/server', 'scripts/shared']})
  .on('restart', function(){
    livereload.changed();
  })
});

gulp.task('stylesheets', function(){
  gulp.watch('stylesheets/**/*', ['reload']);
});

gulp.task('views', function(){
  gulp.watch('views/**/*', ['reload']);
});

gulp.task('reload', function(){
    livereload.changed();
});

gulp.task('dev', ['clientScripts', 'serverScripts', 'stylesheets', 'views'], function() {
  livereload.listen();
});

gulp.task('prod', ['prodClientScripts']);

gulp.task('default', ['dev']);
<|endoftext|>


<commit_before>/*
  Copyright 2014 Google Inc. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
'use strict';

var browserify = require('browserify');
var eslint = require('gulp-eslint');
var ghPages = require('gulp-gh-pages');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var temp = require('temp').track();
var spawn = require('child_process').spawn;
var mocha = require('gulp-mocha');

var buildSources = ['lib/**/*.js'];
var lintSources = buildSources.concat(['gulpfile.js', 'recipes/**/*.js']);

var testServer = null;

gulp.task('test:manual', function() {
  testServer = spawn('node', ['test/server/index.js'], {
    stdio: 'inherit'
  });
});

gulp.task('test:automated', ['test:manual'], function() {
  // This task requires you to have chrome driver in your path
  // You can do this with:
  // npm install -g chromedriver
  return gulp.src('test/automated-suite.js', {read: false})
    .pipe(mocha({
      timeout: 10000
    }))
    .once('error', () => {
      testServer.kill();
    })
    .once('end', () => {
      testServer.kill();
    });
});

gulp.task('build', function() {
  var bundler = browserify({
    entries: ['./lib/sw-toolbox.js'],
    standalone: 'toolbox',
    debug: true
  });

  bundler.plugin('browserify-header');
  bundler.plugin('minifyify', {
    map: 'sw-toolbox.map.json',
    output: 'sw-toolbox.map.json'
  });

  return bundler
    .bundle()
    .pipe(source('sw-toolbox.js'))
    .pipe(gulp.dest('./'));
});

gulp.task('lint', function() {
  return gulp.src(lintSources)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('watch', ['build'], function() {
  gulp.watch(buildSources, ['build']);
});

gulp.task('gh-pages', ['build'], function() {
  var tempDir = temp.mkdirSync();

  return gulp.src([
    'companion.js',
    'sw-toolbox.js',
    'sw-toolbox.map.json',
    'recipes/**/*'
  ], {base: __dirname})
    .pipe(ghPages({cacheDir: tempDir}));
});

gulp.task('default', ['lint', 'build']);
<commit_msg>Looks like travis needs more time per test<commit_after>/*
  Copyright 2014 Google Inc. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
'use strict';

var browserify = require('browserify');
var eslint = require('gulp-eslint');
var ghPages = require('gulp-gh-pages');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var temp = require('temp').track();
var spawn = require('child_process').spawn;
var mocha = require('gulp-mocha');

var buildSources = ['lib/**/*.js'];
var lintSources = buildSources.concat(['gulpfile.js', 'recipes/**/*.js']);

var testServer = null;

gulp.task('test:manual', function() {
  testServer = spawn('node', ['test/server/index.js'], {
    stdio: 'inherit'
  });
});

gulp.task('test:automated', ['test:manual'], function() {
  // This task requires you to have chrome driver in your path
  // You can do this with:
  // npm install -g chromedriver
  return gulp.src('test/automated-suite.js', {read: false})
    .pipe(mocha({
      timeout: 60000
    }))
    .once('error', () => {
      testServer.kill();
    })
    .once('end', () => {
      testServer.kill();
    });
});

gulp.task('build', function() {
  var bundler = browserify({
    entries: ['./lib/sw-toolbox.js'],
    standalone: 'toolbox',
    debug: true
  });

  bundler.plugin('browserify-header');
  bundler.plugin('minifyify', {
    map: 'sw-toolbox.map.json',
    output: 'sw-toolbox.map.json'
  });

  return bundler
    .bundle()
    .pipe(source('sw-toolbox.js'))
    .pipe(gulp.dest('./'));
});

gulp.task('lint', function() {
  return gulp.src(lintSources)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('watch', ['build'], function() {
  gulp.watch(buildSources, ['build']);
});

gulp.task('gh-pages', ['build'], function() {
  var tempDir = temp.mkdirSync();

  return gulp.src([
    'companion.js',
    'sw-toolbox.js',
    'sw-toolbox.map.json',
    'recipes/**/*'
  ], {base: __dirname})
    .pipe(ghPages({cacheDir: tempDir}));
});

gulp.task('default', ['lint', 'build']);
<|endoftext|>


<commit_before>'use strict';

require('dotenv').load();

var pkg = require('./package.json'),
    path = require('path');

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    inject = require('gulp-inject'),
    plumber = require('gulp-plumber'),
    pgbuild = require('gulp-phonegap-build'),
    bowerFiles = require('main-bower-files');

var dir = {
    out: path.join(__dirname, './out'),
    dist: path.join(__dirname, './dist'),
    assets: path.join(__dirname, './public'),
};

gulp.task('default', ['build'], function () {
    gutil.log('Building... This might take a while.');
});

gulp.task('build', function () {
    gulp.src(dir.assets + '/**')
        .pipe(plumber())
        .pipe(pgbuild({
            appId: process.env.PG_BUILD_APP_ID,
            download: {
                android: dir.out + '/onesquare-' + pkg.version + '.apk'
            },
            user: {
                token: process.env.PG_BUILD_AUTH_TOKEN
            }
        }));
});

gulp.task('inject', function () {
    var sources = [
        dir.assets + '/lib/**/*.html'
    ];

    return gulp.src(dir.assets + '/index.html')
        .pipe(inject(gulp.src(sources, {read: false})))
        .pipe(inject(gulp.src(bowerFiles(), {read: false}), {name: 'bower'}))
        .pipe(gulp.dest(dir.dist));
});
<commit_msg>Add Inject to default task.<commit_after>'use strict';

require('dotenv').load();

var pkg = require('./package.json'),
    path = require('path');

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    inject = require('gulp-inject'),
    plumber = require('gulp-plumber'),
    pgbuild = require('gulp-phonegap-build'),
    bowerFiles = require('main-bower-files');

var dir = {
    out: path.join(__dirname, './out'),
    dist: path.join(__dirname, './dist'),
    assets: path.join(__dirname, './public'),
};

gulp.task('default', ['inject', 'build'], function () {
    gutil.log('Building... This might take a while.');
});

gulp.task('build', function () {
    gulp.src(dir.assets + '/**')
        .pipe(plumber())
        .pipe(pgbuild({
            appId: process.env.PG_BUILD_APP_ID,
            download: {
                android: dir.out + '/onesquare-' + pkg.version + '.apk'
            },
            user: {
                token: process.env.PG_BUILD_AUTH_TOKEN
            }
        }));
});

gulp.task('inject', function () {
    var sources = [
        dir.assets + '/lib/**/*.html'
    ];

    return gulp.src(dir.assets + '/index.html')
        .pipe(inject(gulp.src(sources, {read: false})))
        .pipe(inject(gulp.src(bowerFiles(), {read: false}), {name: 'bower'}))
        .pipe(gulp.dest(dir.dist));
});
<|endoftext|>


<commit_before>module.exports = {
  main: (req, res) => {
    res.send('Hello World!');
  },
  message: (req, res) => {
    res.json(req.body);
  }
};
<commit_msg>change the response to the webhook<commit_after>module.exports = {
  main: (req, res) => {
    res.send('Hello World!');
  },
  message: (req, res) => {
    res.send(req.hub.challenge);
  }
};
<|endoftext|>


<commit_before>'use strict';

var request = require('request'),
    fs = require('fs'),
    Yeezus = require('./kingyeezus.js'),
    mentionBot = require('./tweetyeezus.js'),
    dotenv = require('dotenv');

dotenv.load();

var yeezusBot = new Yeezus();

var getReply = function (message, cb) {
  var postvals = {
    'message': message
  };

  request.post('http://ec2-54-191-116-132.us-west-2.compute.amazonaws.com:8088/yeezus',
    { form: postvals },
    function (error, response, body) {
      if (error) { console.log(error); }
      if (!error && response.statusCode === 200) {
        console.log('reply: ', JSON.parse(body).reply);
        cb(JSON.parse(body).reply);
      }
    });
};

exports.handlePost = function (req, res) {
  var message = req.body.message;
  var send = function (reply) {
    res.json({'reply': reply});
  };
  console.log('message:', message);
  getReply(message, send);
};

exports.sendTweet = function(req, res) {
  if(req.query && req.query.p === process.env.TWEET_WORD) { yeezusBot.tweet(); }
  res.json({'msg': 'Got my niggas in Paris and they going to carry it down to egypt.'});
};

exports.reply = function(req, res) {
  console.log(req.query);
  if(!req.query || req.query.p !== process.env.REPLY_WORD) {
    res.json({'msg': 'Got my niggas in Paris and they going to carry it down to egypt.'});
    return;
  }

  var type = req.query.t;

  switch(type) {
    case process.env.MENTIONS:
      mentionBot.y33zusMentions();
      res.json({'msg': 'Got my niggas in Paris and they going to carry it down to egypt.'});
      break;
    case process.env.MINIONS:
      mentionBot.kanyeMentions();
      res.json({'msg': 'Got my niggas in Paris and they going to carry it down to egypt.'});
      break;
  }
};
<commit_msg>updated handlers to use domain<commit_after>'use strict';

var request = require('request'),
    fs = require('fs'),
    Yeezus = require('./kingyeezus.js'),
    mentionBot = require('./tweetyeezus.js'),
    dotenv = require('dotenv');

dotenv.load();

var yeezusBot = new Yeezus();

var getReply = function (message, cb) {
  var postvals = {
    'message': message
  };

  request.post('http://www.digitalyeezus.com:8088/yeezus',
    { form: postvals },
    function (error, response, body) {
      if (error) { console.log(error); }
      if (!error && response.statusCode === 200) {
        console.log('reply: ', JSON.parse(body).reply);
        cb(JSON.parse(body).reply);
      }
    });
};

exports.handlePost = function (req, res) {
  var message = req.body.message;
  var send = function (reply) {
    res.json({'reply': reply});
  };
  console.log('message:', message);
  getReply(message, send);
};

exports.sendTweet = function(req, res) {
  if(req.query && req.query.p === process.env.TWEET_WORD) { yeezusBot.tweet(); }
  res.json({'msg': 'Got my niggas in Paris and they going to carry it down to egypt.'});
};

exports.reply = function(req, res) {
  console.log(req.query);
  if(!req.query || req.query.p !== process.env.REPLY_WORD) {
    res.json({'msg': 'Got my niggas in Paris and they going to carry it down to egypt.'});
    return;
  }

  var type = req.query.t;

  switch(type) {
    case process.env.MENTIONS:
      mentionBot.y33zusMentions();
      res.json({'msg': 'Got my niggas in Paris and they going to carry it down to egypt.'});
      break;
    case process.env.MINIONS:
      mentionBot.kanyeMentions();
      res.json({'msg': 'Got my niggas in Paris and they going to carry it down to egypt.'});
      break;
  }
};
<|endoftext|>


<commit_before>"use strict";

var $ = require("jquery");
var hogan = require("hogan");
var tmplSrc = require("raw!./disease-end-pane.html");
var tmpl = hogan.compile(tmplSrc);
var mUtil = require("../../myclinic-util");
var kanjidate = require("kanjidate");
var DateBinder = require("../../date-binder");
var moment = require("moment");
var task = require("../task");
var service = require("../service");
var conti = require("conti");

var diseaseCheckboxSelector = "> .list input[type=checkbox][name=disease]";
var endDateGengouSelector = "> .end-date select[mc-name=gengou]";
var endDateNenInputSelector = "> .end-date input[mc-name=nen]";
var endDateNenLabelSelector = "> .end-date [mc-name=nenLabel]";
var endDateMonthInputSelector = "> .end-date input[mc-name=month]";
var endDateMonthLabelSelector = "> .end-date [mc-name=monthLabel]"
var endDateDayInputSelector = "> .end-date input[mc-name=day]";
var endDateDayLabelSelector = "> .end-date [mc-name=dayLabel]";
var endDateWeekLinkSelector = "> .end-date [mc-name=weekLabel]";
var endDateTodayLinkSelector = "> .end-date [mc-name=todayLabel]";
var endDateMonthLastDayLinkSelector = "> .end-date [mc-name=monthLastDayLabel]";
var endDateLastMonthLastDayLinkSelector = "> .end-date [mc-name=lastMonthLastDayLabel]";
var reasonRadioSelector = "> [mc-name=end-reason-area] input[type=radio][name=end-reason]";
var enterLinkSelector = "> .commandbox [mc-name=enterLink]";

exports.create = function(diseases){
	var data = {
		diseases: diseasesData(diseases)
	};
	var dom = $(tmpl.render(data));
	var ctx = {
		dateBinder: setupDateBinder(dom),
	}
	ctx.dateBinder.setDate(moment());
	bindSelectionChange(dom, ctx);
	bindEnter(dom, ctx);
	return dom;
}

function diseasesData(diseases){
	return diseases.map(function(d){
		return {
			disease_id: d.disease_id,
			name_label: mUtil.diseaseFullName(d),
			start_date_label: kanjidate.format(kanjidate.f3, d.start_date),
			start_date: d.start_date
		}
	})
}

function setupDateBinder(dom){
	var map = {
		gengouSelect: dom.find(endDateGengouSelector),
		nenInput: dom.find(endDateNenInputSelector),
		nenLabel: dom.find(endDateNenLabelSelector),
		monthInput: dom.find(endDateMonthInputSelector),
		monthLabel: dom.find(endDateMonthLabelSelector),
		dayInput: dom.find(endDateDayInputSelector),
		dayLabel: dom.find(endDateDayLabelSelector),
		weekLink: dom.find(endDateWeekLinkSelector),
		todayLink: dom.find(endDateTodayLinkSelector),
		monthLastDayLink: dom.find(endDateMonthLastDayLinkSelector),
		lastMonthLastDayLink: dom.find(endDateLastMonthLastDayLinkSelector)
	}
	return DateBinder.bind(map);
}

function bindSelectionChange(dom, ctx){
	dom.on("change", diseaseCheckboxSelector, function(){
		var last = null;
		dom.find(diseaseCheckboxSelector + ":checked").each(function(){
			var startDate = $(this).data("start-date");
			if( !last || startDate > last ){
				last = startDate;
			}
		});
		if( last ){
			ctx.dateBinder.setDate(moment(last));
		} else {
			ctx.dateBinder.setDate(moment());
		}
	})
}

function bindEnter(dom, ctx){
	dom.on("click", enterLinkSelector, function(event){
		event.preventDefault();
		var diseaseIds = dom.find(diseaseCheckboxSelector + ":checked").map(function(){
			return +$(this).val();
		}).get();
		var dateOpt = ctx.dateBinder.getDate();
		if( !dateOpt.ok ){
			alert(dateOpt.error);
			return;
		}
		var endDate = dateOpt.sqlDate;
		var reason = dom.find(reasonRadioSelector + ":checked").val();
		var diseases = [], newDiseases = [];
		task.run([
			function(done){
				conti.forEach(diseaseIds, function(diseaseId, done){
					service.getDisease(diseaseId, function(err, result){
						if( err ){
							done(err);
							return;
						}
						diseases.push(result);
						done();
					})
				}, done);
			},
			function(done){
				diseases.forEach(function(disease){
					disease.end_reason = reason;
					disease.end_date = endDate;
				});
				service.batchUpdateDiseases(diseases, done);
			},
			function(done){
				conti.forEach(diseaseIds, function(diseaseId, done){
					service.getFullDisease(diseaseId, function(err, result){
						if( err ){
							done(err);
							return;
						}
						newDiseases.push(result);
						done();
					})
				}, done);
			}
		], function(err){
			if( err ){
				alert(err);
				return;
			}
			dom.trigger("gvr59xqp-modified", [newDiseases]);
		})
	})
}
<commit_msg>revised end disease<commit_after>"use strict";

var $ = require("jquery");
var hogan = require("hogan");
var tmplSrc = require("raw!./disease-end-pane.html");
var tmpl = hogan.compile(tmplSrc);
var mUtil = require("../../myclinic-util");
var kanjidate = require("kanjidate");
var DateBinder = require("../../date-binder");
var moment = require("moment");
var task = require("../task");
var service = require("../service");
var conti = require("conti");
var mConsts = require("myclinic-consts");

var diseaseCheckboxSelector = "> .list input[type=checkbox][name=disease]";
var endDateGengouSelector = "> .end-date select[mc-name=gengou]";
var endDateNenInputSelector = "> .end-date input[mc-name=nen]";
var endDateNenLabelSelector = "> .end-date [mc-name=nenLabel]";
var endDateMonthInputSelector = "> .end-date input[mc-name=month]";
var endDateMonthLabelSelector = "> .end-date [mc-name=monthLabel]"
var endDateDayInputSelector = "> .end-date input[mc-name=day]";
var endDateDayLabelSelector = "> .end-date [mc-name=dayLabel]";
var endDateWeekLinkSelector = "> .end-date [mc-name=weekLabel]";
var endDateTodayLinkSelector = "> .end-date [mc-name=todayLabel]";
var endDateMonthLastDayLinkSelector = "> .end-date [mc-name=monthLastDayLabel]";
var endDateLastMonthLastDayLinkSelector = "> .end-date [mc-name=lastMonthLastDayLabel]";
var reasonRadioSelector = "> [mc-name=end-reason-area] input[type=radio][name=end-reason]";
var enterLinkSelector = "> .commandbox [mc-name=enterLink]";

exports.create = function(diseases){
	var data = {
		diseases: diseasesData(diseases)
	};
	var dom = $(tmpl.render(data));
	var ctx = {
		dateBinder: setupDateBinder(dom),
	}
	ctx.dateBinder.setDate(moment());
	bindSelectionChange(dom, ctx);
	bindEnter(dom, ctx);
	return dom;
}

function diseasesData(diseases){
	return diseases.map(function(d){
		return {
			disease_id: d.disease_id,
			name_label: mUtil.diseaseFullName(d),
			start_date_label: kanjidate.format(kanjidate.f3, d.start_date),
			start_date: d.start_date
		}
	})
}

function setupDateBinder(dom){
	var map = {
		gengouSelect: dom.find(endDateGengouSelector),
		nenInput: dom.find(endDateNenInputSelector),
		nenLabel: dom.find(endDateNenLabelSelector),
		monthInput: dom.find(endDateMonthInputSelector),
		monthLabel: dom.find(endDateMonthLabelSelector),
		dayInput: dom.find(endDateDayInputSelector),
		dayLabel: dom.find(endDateDayLabelSelector),
		weekLink: dom.find(endDateWeekLinkSelector),
		todayLink: dom.find(endDateTodayLinkSelector),
		monthLastDayLink: dom.find(endDateMonthLastDayLinkSelector),
		lastMonthLastDayLink: dom.find(endDateLastMonthLastDayLinkSelector)
	}
	return DateBinder.bind(map);
}

function bindSelectionChange(dom, ctx){
	dom.on("change", diseaseCheckboxSelector, function(){
		var last = null;
		dom.find(diseaseCheckboxSelector + ":checked").each(function(){
			var startDate = $(this).data("start-date");
			if( !last || startDate > last ){
				last = startDate;
			}
		});
		if( last ){
			ctx.dateBinder.setDate(moment(last));
		} else {
			ctx.dateBinder.setDate(moment());
		}
	})
}

function hasSusp(fullDisease){
	return fullDisease.adj_list.some(function(adj){
		console.log(adj.name);
		return adj.name == "の疑い";
	})
}

function fixEndReason(fullDisease, proposedReason){
	if( proposedReason === mConsts.DiseaseEndReasonCured && hasSusp(fullDisease) ){
		return mConsts.DiseaseEndReasonStopped;
	}
	return proposedReason;
}

function bindEnter(dom, ctx){
	dom.on("click", enterLinkSelector, function(event){
		event.preventDefault();
		var diseaseIds = dom.find(diseaseCheckboxSelector + ":checked").map(function(){
			return +$(this).val();
		}).get();
		var dateOpt = ctx.dateBinder.getDate();
		if( !dateOpt.ok ){
			alert(dateOpt.error);
			return;
		}
		var endDate = dateOpt.sqlDate;
		var reason = dom.find(reasonRadioSelector + ":checked").val();
		var diseases = [], newDiseases = [];
		task.run([
			function(done){
				conti.forEach(diseaseIds, function(diseaseId, done){
					service.getFullDisease(diseaseId, function(err, result){
						if( err ){
							done(err);
							return;
						}
						diseases.push(result);
						done();
					})
				}, done);
			},
			function(done){
				diseases.forEach(function(disease){
					disease.end_reason = fixEndReason(disease, reason);
					disease.end_date = endDate;
				});
				service.batchUpdateDiseases(diseases, done);
			},
			function(done){
				conti.forEach(diseaseIds, function(diseaseId, done){
					service.getFullDisease(diseaseId, function(err, result){
						if( err ){
							done(err);
							return;
						}
						newDiseases.push(result);
						done();
					})
				}, done);
			}
		], function(err){
			if( err ){
				alert(err);
				return;
			}
			dom.trigger("gvr59xqp-modified", [newDiseases]);
		})
	})
}
<|endoftext|>


<commit_before>console.log("inject ubermap");

var pmUberMap = function(handler, arguments) {
	if (api.panels.ubermap_panel) {
		api.panels.ubermap_panel.message(handler, arguments);
	} else {
		setTimeout(function() {
			pmUberMap(handler, arguments);
		}, 500);
	}
};

(function() {
	var cursorKey = "info.nanodesu.defaultIconKey";
	var oldEngineCall = engine.call;
	engine.call = function() {
		if (arguments && arguments.length && arguments.length > 0 && arguments[0] === "pop_mouse_constraint_flag") {
			localStorage[cursorKey] = "coui://ui/main/game/live_game/img/cursors/cursor.png";
		}
		return oldEngineCall.apply(this, arguments);
	};

	var cursorTypeComputed = ko.computed(function() {
		var hasSelection = model.hasSelection();
		if ((model.mode() === "default" || model.mode() === "command_move") && hasSelection) {
			localStorage[cursorKey] ="coui://ui/main/game/live_game/img/cursors/icons_command_move.png";
		} else if (hasSelection && model.mode() === "command_patrol") {
			localStorage[cursorKey] ="coui://ui/main/game/live_game/img/cursors/icons_command_patrol.png";
		} else if (hasSelection && model.mode() === "command_attack") {
			localStorage[cursorKey] = "coui://ui/main/game/live_game/img/cursors/icons_command_attack.png";
		} else if (model.mode() === "command_ping") {
			localStorage[cursorKey] = "coui://ui/main/game/live_game/img/cursors/icons_command_ping.png";
		} else {
			localStorage[cursorKey] ="coui://ui/main/game/live_game/img/cursors/cursor.png";
		}
	});

	model.mode.subscribe(function(m) {
		if (m === "command_move" || m === "command_patrol" || m === "command_attack" || m === "command_ping") {
			pmUberMap('commandMode', m);
		} else {
			pmUberMap('commandMode', "default");
		}
	});

	handlers.quitCommandMode = model.endCommandMode;

	var oldShowAlertPreview = model.showAlertPreview;

	model.showAlertPreview = function(request) {
		var oldLookAt = api.camera.lookAt;
		api.camera.lookAt = function(target) {
			oldLookAt(target);
			// locks the poles for the alerts preview pip
			api.camera.alignToPole();
		};
		oldShowAlertPreview(request);
		api.camera.lookAt = oldLookAt;
	};

	handlers.queryViewportSize = function() {
		pmUberMap('setSize', [window.screen.width, window.screen.height]);
	};

	var oldOnResize = window.onresize;
	window.onresize = function(w) {
		if (typeof oldOnResize === "function") {
			oldOnResize(w);
		}

		handlers.queryViewportSize();
	};

	handlers.changeMinimapZ = function(payload) {
		$('#ubermap_panel').css('z-index', payload.z);
	};

	var commanderId = 0;
	handlers.runUnitCommand = function(payload) {
		var order = {};
		order.units = payload.units;

		if (payload.method === "moveSelected") {
			order.command = "move";
		} else if (payload.method === "patrolSelected") {
			order.command = "patrol";
		} else if (payload.method === "attackSelected") {
			order.command = "attack";
		} else if (payload.method === "ping") {
			order.command = "ping";
			order.units = [commanderId]; // PA verifies that the "ping" command has a unit given....
		} else {
			console.log("dunno method for order?! " + payload.method);
		}

		order.queue = payload.arguments[4];
		order.location = {
			planet: payload.arguments[3],
			pos: [payload.arguments[0], payload.arguments[1], payload.arguments[2]]
		};
		order.group = !payload.arguments[5];

		api.getWorldView(0).sendOrder(order).then(function(resp) {
//			console.log(resp);
		});
	};

	var colorByArmyId = {};
	var oldServerState = handlers.server_state;
	var selfArmyId = undefined;
	var selfArmyIndex = undefined;
	var armyIndexIdMap = {};
	handlers.server_state = function(msg) {
		console.log("server state");
		console.log(msg);
		oldServerState(msg);

		if (msg.data && msg.data.client && msg.data.client.commander) {
			commanderId = msg.data.client.commander.id;
		}

		if (msg.data.armies) {
			for (var i = 0; i < msg.data.armies.length; i++) {
				colorByArmyId[msg.data.armies[i].id] = msg.data.armies[i].color;
				armyIndexIdMap[i] = msg.data.armies[i].id;
			}
		}

		if (msg.data.client.army_id) {
			selfArmyId = msg.data.client.army_id;
		}

		if (msg.data.armies && msg.data.client) {
			var idToIndexMap = {};
			var armies = msg.data.armies;
			for (var i = 0; i < armies.length; i++) {
				idToIndexMap[armies[i].id] = i;
			}
			selfArmyIndex = idToIndexMap[msg.data.client.army_id];
		}

		handlers.queryArmyInfo();
	};

	handlers.queryArmyInfo = function() {
		console.log("query army info called...");
		var info = [colorByArmyId, selfArmyId, selfArmyIndex, armyIndexIdMap];
		console.log(info);
		pmUberMap("setArmyInfo", info);
	};

	model.showsUberMap = ko.observable(false);

	var holodeck = $('.primary');
	handlers.setUberMapState = function(visible) {
		model.showsUberMap(visible);

		var focusBefore = api.Holodeck.focused;
		api.holodecks[0].focus();
		api.camera.setAllowZoom(!visible);
		if (focusBefore) {
			focusBefore.focus();
		}

		if (visible) {
			holodeck.attr("style", "top: "+0+"px; left: "+0+"px; width: "+1+"px; height: "+1+"px");
		} else {
			holodeck.attr("style", "");
		}
	};

	model.showsUberMap.subscribe(function(v) {
		pmUberMap("setUberMapVisible", v);
	});

	var oldCelestial = handlers.celestial_data;
	var planetsIndexIdMap = {};
	var planetsIdIndexMap = {};
	handlers.celestial_data = function(payload) {
		oldCelestial(payload);
		_.forEach(payload.planets, function(planet) {
			planetsIndexIdMap[planet.index] = planet.id;
			planetsIdIndexMap[planet.id] = planet.index;
		});
	};

	setTimeout(function() {
		model.mainCameraLocation = api.camera.getFocus(model.holodeck.id).location;
		model.mainCameraPlanetIndex = api.camera.getFocus(model.holodeck.id).planet;
		model.mainCameraPlanet = ko.computed(function() {
			var index = model.mainCameraPlanetIndex();
			return planetsIndexIdMap[index];
		});
		model.mainCameraPosition = ko.computed(function() {
			var l = model.mainCameraLocation();
			return {planet: model.mainCameraPlanet(),
					x: l.x,
					y: l.y,
					z: l.z};
		});
		model.mainCameraPosition.extend({rateLimit: 50});
		model.mainCameraPosition.subscribe(function(v) {
			pmUberMap("camLoc", v);
		});
		var oldLookAt = api.camera.lookAt;
		api.camera.lookAt = function(t, s) {
			oldLookAt(t, s);
			if (model.holodeck.id === api.Holodeck.focused.id) {
				var catchPosition = function() {
					model.mainCameraLocation(t.location);
					model.mainCameraPlanetIndex(planetsIdIndexMap[t.planet_id]);
				};
				catchPosition();
				setTimeout(function() {
					catchPosition();
				}, 100);
			}
		};
	}, 3000);

	handlers.setMainCamera = function(target) {
		var focusBefore = api.Holodeck.focused;
		model.holodeck.focus();

		api.camera.lookAt(target, false);
		api.camera.alignToPole();

		if (focusBefore) {
			focusBefore.focus();
		}
	};
}());

$(document).ready(function() {
	// put a lot of things above the ubermap z index, as they should always be on top
	$('.div_sidebar_left').css("z-index", "99999");
	$('#chat').css("z-index", "99999");
	$('#message').css("z-index", "99999");
	$('.div_game_paused').css("z-index", "99998");
	$('#settings').css("z-index", "99999");
	$('.div_gamestats_panel').css("z-index", "99999");
	$('#game_over').css("z-index", "99999");
	$('#message').css("z-index", "99999");
	$('#player_guide').css("z-index", "99999");
	$('#popup').css('z-index', "99999");

	var $panel;
	var func = function(v) {
		if (!v) {
			$panel = $('<panel id="ubermap_panel"></panel>').css({
				visibility : 'visible',
				position : 'fixed',
				top : 30,
				left : 0,
				'z-index' : 9999
			}).attr({
				name : "ubermap_panel",
				src : "coui://ui/mods/ubermap/ubermap.html",
				'no-keyboard' : true,
				'yield-focus' : true,
				fit : "dock-top-left",
				class: "ignoreMouse",
			});
			$panel.appendTo($('body'));
			api.Panel.bindPanels();
		} else {
			$('#ubermap_panel').remove();
		}
	};

//	func(model.isSpectator());
//	model.isSpectator.subscribe(func);
	func(false);

	model.uber_map_toggle_uber_map = function() {
		if (!model.chatSelected()) {
			model.showsUberMap(!model.showsUberMap());
		}
	};

	model.uber_map_toggle_select_fighters = function() {
		pmUberMap('toggleByName', "selectsAllFighters");
	};
	model.uber_map_toggle_select_workers = function() {
		pmUberMap('toggleByName', "selectsAllWorkers");
	};
	model.uber_map_toggle_select_all = function() {
		pmUberMap('toggleByName', "selectsAll");
	};
	model.uber_map_toggle_select_orbital = function() {
		pmUberMap('toggleByName', "selectsAllOrbital");
	};
	model.uber_map_toggle_select_air = function() {
		pmUberMap('toggleByName', "selectsAllAir");
	};
	model.uber_map_toggle_select_land = function() {
		pmUberMap('toggleByName', "selectsAllLand");
	};
	model.uber_map_toggle_select_navy = function() {
		pmUberMap('toggleByName', "selectsAllNavy");
	};
	model.uber_map_toggle_select_navy_fighters = function() {
		pmUberMap('toggleByName', "selectsNavyFighters");
	};
	model.uber_map_toggle_select_navy_workers = function() {
		pmUberMap('toggleByName', "selectsNavyWorkers");
	};
	model.uber_map_toggle_select_land_fighters = function() {
		pmUberMap('toggleByName', "selectsLandFighters");
	};
	model.uber_map_toggle_select_land_workers = function() {
		pmUberMap('toggleByName', "selectsLandWorkers");
	};
	model.uber_map_toggle_select_air_fighters = function() {
		pmUberMap('toggleByName', "selectsAirFighters");
	};
	model.uber_map_toggle_select_air_workers = function() {
		pmUberMap('toggleByName', "selectsAirWorkers");
	};
	model.uber_map_toggle_select_orbital_fighters = function() {
		pmUberMap('toggleByName', "selectsOrbitalFighters");
	};
	model.uber_map_toggle_select_orbital_workers = function() {
		pmUberMap('toggleByName', "selectsOrbitalWorkers");
	};

	$(document).keydown(function (e) {
		 if (e.which === 16) {
			 pmUberMap("shiftState", true);
		 } else if (e.which === 17) {
			 pmUberMap("ctrlState", true);
		 }
	});

	$(document).keyup(function(e) {
		if (e.which === 16) {
			pmUberMap("shiftState", false);
		} else if (e.which === 17) {
			pmUberMap("ctrlState", false);
		}
	});

	$(document).bind('mousewheel', function(e) {
		 if (model.chatSelected())
			 return;

		if (e.originalEvent.wheelDelta > 0 && model.showsUberMap()) {
			pmUberMap("zoomIntoUberMap", [e.pageX - $panel.position().left, e.pageY - $panel.position().top]);
		}
	});
});<commit_msg>use planet index for orders as required<commit_after>console.log("inject ubermap");

var pmUberMap = function(handler, arguments) {
	if (api.panels.ubermap_panel) {
		api.panels.ubermap_panel.message(handler, arguments);
	} else {
		setTimeout(function() {
			pmUberMap(handler, arguments);
		}, 500);
	}
};

(function() {
	var oldCelestial = handlers.celestial_data;
	var planetsIndexIdMap = {};
	var planetsIdIndexMap = {};
	handlers.celestial_data = function(payload) {
		oldCelestial(payload);
		_.forEach(payload.planets, function(planet) {
			planetsIndexIdMap[planet.index] = planet.id;
			planetsIdIndexMap[planet.id] = planet.index;
		});
	};

	var cursorKey = "info.nanodesu.defaultIconKey";
	var oldEngineCall = engine.call;
	engine.call = function() {
		if (arguments && arguments.length && arguments.length > 0 && arguments[0] === "pop_mouse_constraint_flag") {
			localStorage[cursorKey] = "coui://ui/main/game/live_game/img/cursors/cursor.png";
		}
		return oldEngineCall.apply(this, arguments);
	};

	var cursorTypeComputed = ko.computed(function() {
		var hasSelection = model.hasSelection();
		if ((model.mode() === "default" || model.mode() === "command_move") && hasSelection) {
			localStorage[cursorKey] ="coui://ui/main/game/live_game/img/cursors/icons_command_move.png";
		} else if (hasSelection && model.mode() === "command_patrol") {
			localStorage[cursorKey] ="coui://ui/main/game/live_game/img/cursors/icons_command_patrol.png";
		} else if (hasSelection && model.mode() === "command_attack") {
			localStorage[cursorKey] = "coui://ui/main/game/live_game/img/cursors/icons_command_attack.png";
		} else if (model.mode() === "command_ping") {
			localStorage[cursorKey] = "coui://ui/main/game/live_game/img/cursors/icons_command_ping.png";
		} else {
			localStorage[cursorKey] ="coui://ui/main/game/live_game/img/cursors/cursor.png";
		}
	});

	model.mode.subscribe(function(m) {
		if (m === "command_move" || m === "command_patrol" || m === "command_attack" || m === "command_ping") {
			pmUberMap('commandMode', m);
		} else {
			pmUberMap('commandMode', "default");
		}
	});

	handlers.quitCommandMode = model.endCommandMode;

	var oldShowAlertPreview = model.showAlertPreview;

	model.showAlertPreview = function(request) {
		var oldLookAt = api.camera.lookAt;
		api.camera.lookAt = function(target) {
			oldLookAt(target);
			// locks the poles for the alerts preview pip
			api.camera.alignToPole();
		};
		oldShowAlertPreview(request);
		api.camera.lookAt = oldLookAt;
	};

	handlers.queryViewportSize = function() {
		pmUberMap('setSize', [window.screen.width, window.screen.height]);
	};

	var oldOnResize = window.onresize;
	window.onresize = function(w) {
		if (typeof oldOnResize === "function") {
			oldOnResize(w);
		}

		handlers.queryViewportSize();
	};

	handlers.changeMinimapZ = function(payload) {
		$('#ubermap_panel').css('z-index', payload.z);
	};

	var commanderId = 0;
	handlers.runUnitCommand = function(payload) {
		var order = {};
		order.units = payload.units;

		if (payload.method === "moveSelected") {
			order.command = "move";
		} else if (payload.method === "patrolSelected") {
			order.command = "patrol";
		} else if (payload.method === "attackSelected") {
			order.command = "attack";
		} else if (payload.method === "ping") {
			order.command = "ping";
			order.units = [commanderId]; // PA verifies that the "ping" command has a unit given....
		} else {
			console.log("dunno method for order?! " + payload.method);
		}

		order.queue = payload.arguments[4];
		order.location = {
			planet: planetsIdIndexMap[payload.arguments[3]],
			pos: [payload.arguments[0], payload.arguments[1], payload.arguments[2]]
		};
		order.group = !payload.arguments[5];

		api.getWorldView(0).sendOrder(order).then(function(resp) {
//			console.log(resp);
		});
	};

	var colorByArmyId = {};
	var oldServerState = handlers.server_state;
	var selfArmyId = undefined;
	var selfArmyIndex = undefined;
	var armyIndexIdMap = {};
	handlers.server_state = function(msg) {
		console.log("server state");
		console.log(msg);
		oldServerState(msg);

		if (msg.data && msg.data.client && msg.data.client.commander) {
			commanderId = msg.data.client.commander.id;
		}

		if (msg.data.armies) {
			for (var i = 0; i < msg.data.armies.length; i++) {
				colorByArmyId[msg.data.armies[i].id] = msg.data.armies[i].color;
				armyIndexIdMap[i] = msg.data.armies[i].id;
			}
		}

		if (msg.data.client.army_id) {
			selfArmyId = msg.data.client.army_id;
		}

		if (msg.data.armies && msg.data.client) {
			var idToIndexMap = {};
			var armies = msg.data.armies;
			for (var i = 0; i < armies.length; i++) {
				idToIndexMap[armies[i].id] = i;
			}
			selfArmyIndex = idToIndexMap[msg.data.client.army_id];
		}

		handlers.queryArmyInfo();
	};

	handlers.queryArmyInfo = function() {
		console.log("query army info called...");
		var info = [colorByArmyId, selfArmyId, selfArmyIndex, armyIndexIdMap];
		console.log(info);
		pmUberMap("setArmyInfo", info);
	};

	model.showsUberMap = ko.observable(false);

	var holodeck = $('.primary');
	handlers.setUberMapState = function(visible) {
		model.showsUberMap(visible);

		var focusBefore = api.Holodeck.focused;
		api.holodecks[0].focus();
		api.camera.setAllowZoom(!visible);
		if (focusBefore) {
			focusBefore.focus();
		}

		if (visible) {
			holodeck.attr("style", "top: "+0+"px; left: "+0+"px; width: "+1+"px; height: "+1+"px");
		} else {
			holodeck.attr("style", "");
		}
	};

	model.showsUberMap.subscribe(function(v) {
		pmUberMap("setUberMapVisible", v);
	});

	setTimeout(function() {
		model.mainCameraLocation = api.camera.getFocus(model.holodeck.id).location;
		model.mainCameraPlanetIndex = api.camera.getFocus(model.holodeck.id).planet;
		model.mainCameraPlanet = ko.computed(function() {
			var index = model.mainCameraPlanetIndex();
			return planetsIndexIdMap[index];
		});
		model.mainCameraPosition = ko.computed(function() {
			var l = model.mainCameraLocation();
			return {planet: model.mainCameraPlanet(),
					x: l.x,
					y: l.y,
					z: l.z};
		});
		model.mainCameraPosition.extend({rateLimit: 50});
		model.mainCameraPosition.subscribe(function(v) {
			pmUberMap("camLoc", v);
		});
		var oldLookAt = api.camera.lookAt;
		api.camera.lookAt = function(t, s) {
			oldLookAt(t, s);
			if (model.holodeck.id === api.Holodeck.focused.id) {
				var catchPosition = function() {
					model.mainCameraLocation(t.location);
					model.mainCameraPlanetIndex(planetsIdIndexMap[t.planet_id]);
				};
				catchPosition();
				setTimeout(function() {
					catchPosition();
				}, 100);
			}
		};
	}, 3000);

	handlers.setMainCamera = function(target) {
		var focusBefore = api.Holodeck.focused;
		model.holodeck.focus();

		api.camera.lookAt(target, false);
		api.camera.alignToPole();

		if (focusBefore) {
			focusBefore.focus();
		}
	};
}());

$(document).ready(function() {
	// put a lot of things above the ubermap z index, as they should always be on top
	$('.div_sidebar_left').css("z-index", "99999");
	$('#chat').css("z-index", "99999");
	$('#message').css("z-index", "99999");
	$('.div_game_paused').css("z-index", "99998");
	$('#settings').css("z-index", "99999");
	$('.div_gamestats_panel').css("z-index", "99999");
	$('#game_over').css("z-index", "99999");
	$('#message').css("z-index", "99999");
	$('#player_guide').css("z-index", "99999");
	$('#popup').css('z-index', "99999");

	var $panel;
	var func = function(v) {
		if (!v) {
			$panel = $('<panel id="ubermap_panel"></panel>').css({
				visibility : 'visible',
				position : 'fixed',
				top : 30,
				left : 0,
				'z-index' : 9999
			}).attr({
				name : "ubermap_panel",
				src : "coui://ui/mods/ubermap/ubermap.html",
				'no-keyboard' : true,
				'yield-focus' : true,
				fit : "dock-top-left",
				class: "ignoreMouse",
			});
			$panel.appendTo($('body'));
			api.Panel.bindPanels();
		} else {
			$('#ubermap_panel').remove();
		}
	};

//	func(model.isSpectator());
//	model.isSpectator.subscribe(func);
	func(false);

	model.uber_map_toggle_uber_map = function() {
		if (!model.chatSelected()) {
			model.showsUberMap(!model.showsUberMap());
		}
	};

	model.uber_map_toggle_select_fighters = function() {
		pmUberMap('toggleByName', "selectsAllFighters");
	};
	model.uber_map_toggle_select_workers = function() {
		pmUberMap('toggleByName', "selectsAllWorkers");
	};
	model.uber_map_toggle_select_all = function() {
		pmUberMap('toggleByName', "selectsAll");
	};
	model.uber_map_toggle_select_orbital = function() {
		pmUberMap('toggleByName', "selectsAllOrbital");
	};
	model.uber_map_toggle_select_air = function() {
		pmUberMap('toggleByName', "selectsAllAir");
	};
	model.uber_map_toggle_select_land = function() {
		pmUberMap('toggleByName', "selectsAllLand");
	};
	model.uber_map_toggle_select_navy = function() {
		pmUberMap('toggleByName', "selectsAllNavy");
	};
	model.uber_map_toggle_select_navy_fighters = function() {
		pmUberMap('toggleByName', "selectsNavyFighters");
	};
	model.uber_map_toggle_select_navy_workers = function() {
		pmUberMap('toggleByName', "selectsNavyWorkers");
	};
	model.uber_map_toggle_select_land_fighters = function() {
		pmUberMap('toggleByName', "selectsLandFighters");
	};
	model.uber_map_toggle_select_land_workers = function() {
		pmUberMap('toggleByName', "selectsLandWorkers");
	};
	model.uber_map_toggle_select_air_fighters = function() {
		pmUberMap('toggleByName', "selectsAirFighters");
	};
	model.uber_map_toggle_select_air_workers = function() {
		pmUberMap('toggleByName', "selectsAirWorkers");
	};
	model.uber_map_toggle_select_orbital_fighters = function() {
		pmUberMap('toggleByName', "selectsOrbitalFighters");
	};
	model.uber_map_toggle_select_orbital_workers = function() {
		pmUberMap('toggleByName', "selectsOrbitalWorkers");
	};

	$(document).keydown(function (e) {
		 if (e.which === 16) {
			 pmUberMap("shiftState", true);
		 } else if (e.which === 17) {
			 pmUberMap("ctrlState", true);
		 }
	});

	$(document).keyup(function(e) {
		if (e.which === 16) {
			pmUberMap("shiftState", false);
		} else if (e.which === 17) {
			pmUberMap("ctrlState", false);
		}
	});

	$(document).bind('mousewheel', function(e) {
		 if (model.chatSelected())
			 return;

		if (e.originalEvent.wheelDelta > 0 && model.showsUberMap()) {
			pmUberMap("zoomIntoUberMap", [e.pageX - $panel.position().left, e.pageY - $panel.position().top]);
		}
	});
});<|endoftext|>


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

function unixifyPath(filepath) {
	if (process.platform === 'win32') {
		return filepath.replace(/\\/g, '/');
	} else {
		return filepath;
	}
}

function formatTwoDigists(number) {
	if (number < 10) {
		return '0' + number;
	} else {
		return number.toString();
	}
}

function formatTimestamp(date) {
	var str = date.getFullYear() + '';
	str += formatTwoDigists(date.getMonth() + 1);
	str += formatTwoDigists(date.getDate());
	str += formatTwoDigists(date.getHours());
	str += formatTwoDigists(date.getMinutes());
	str += formatTwoDigists(date.getSeconds());
	return str;
}

function optionalValue(value, defaultValue) {
	defaultValue = defaultValue || '-';
	return value ? value : defaultValue;
}

function formatField(label, attr, separator) {
	separator = separator || ': ';
	var str = '';

	if (attr) {
		str = label + separator + attr + '\n';
	}
	return str;
}

function formatLabeledList(label, list) {
	list = list || [];
	var str = '';

	for(var i in list) {
		str += formatField(label, list[i]);
	}
	return str;
}

function formatFileList(options) {
	var str = '';

	if (options.files && options.files.length > 0) {
		str += '\n%files\n';
		if (options.defaultFilemode || options.defaultUsername || options.defaultGroupname || options.defaultDirmode) {
			str += '%defattr('
				+ optionalValue(options.defaultFilemode) + ','
				+ optionalValue(options.defaultUsername) + ','
				+ optionalValue(options.defaultGroupname) + ','
				+ optionalValue(options.defaultDirmode) + ')\n';
		}
		if (options.attributes) {
			for (var j in options.attributes) {
				var attr = options.attributes[j];
				var mode = attr.mode || '-';
				var username = attr.username || '-';
				var groupname = attr.groupname || '-';
				str += '%attr(' + mode + ',' + username + ','
					+ groupname + ') ' + attr.file + '\n';
			}
		}
		if (options.config) {
			for (var k in options.config) {
				var config = options.config[k];
				str += '%config ' + config + '\n';
			}
		}
		for (var i in options.files) {
			var rpmFile = options.files[i];
//			if (!rpmFile.noRecursion) {
				if (rpmFile.filemode || rpmFile.username || rpmFile.groupname) {
					str += '%attr('
						+ optionalValue(rpmFile.filemode) + ','
						+ optionalValue(rpmFile.username) + ','
						+ optionalValue(rpmFile.groupname) + ') ';
				}
				if (rpmFile.orig.expand) {
					str += '"' + unixifyPath(path.join(path.sep, rpmFile.dest)) + '"\n';
				} else {
					str += '"' + unixifyPath(path.join(path.sep, rpmFile.dest, rpmFile.path)) + '"\n';
				}
//			} else {
//				str += '%dir "' + unixifyPath(path.join(path.sep, rpmFile.dest + rpmFile.path)) + '"\n';
//			}
		}
	}

	return str;
}

function readScriptlet(label, scriptFile) {
	var src = '';
	if (scriptFile) {
		var options = {
			encoding: scriptFile.encoding || 'utf8'
		};
		var data = fs.readFileSync(scriptFile.src, options);
		src += label + '\n';
		src += data.trim() + '\n\n';
	}
	return src;
}

function skipBinariesInNoarchPackageError() {
	return '%define _binaries_in_noarch_packages_terminate_build   0\n\n';
}

/**
 * Provides utility methods to execute a command
 * @module exec
 */
module.exports = function(options, callback) {
//	grunt.verbose.writeln('Writing SPEC basic section...');

	// FIXME the following macro definition should not be needed if the --define command line parameter is taken into account by rpmbuild
	var src = '%define   _topdir ' + path.join(process.cwd(), options.destination) + '\n\n';

	src += skipBinariesInNoarchPackageError();

	src += formatField('Name', options.name);
	src += formatField('Version', options.version);
	src += 'Release: ';
        if (options.release === true) {
                src += '1\n';
        } else if (options.release) {
                src += options.release + '\n';
	} else {
		src += 'SNAPSHOT' + formatTimestamp(new Date()) + '\n';
	}

	src += formatField('URL', options.homepage);
	src += formatField('Summary', options.summary);
	src += formatField('License', optionalValue(options.license, options.licenses && options.licenses[0] && options.licenses[0].type));
	src += formatField('Distribution', options.distribution);
	src += formatField('Vendor', options.vendor);
	src += formatField('Group', options.group);
	src += formatField('Provides', options.provides);
	src += formatLabeledList('Requires', options.requires);
	src += formatField('autoprov', 'yes');
	src += formatField('autoreq', 'yes');
	src += formatField('\n%description', options.description, '\n');

//	grunt.verbose.writeln('Writing SPEC files section...');
	src += formatFileList(options);

//	grunt.verbose.writeln('Writing SPEC scriptlet section...');
	src += readScriptlet('\n%pre', options.preInstall);
	src += readScriptlet('\n%post', options.postInstall);
	src += readScriptlet('\n%preun', options.preUninstall);
	src += readScriptlet('\n%postun', options.postUninstall);

	fs.writeFile(options.specFilepath, src, callback);
};
<commit_msg>Adding support for custom directives<commit_after>
var path = require('path');
var fs = require('fs');

function unixifyPath(filepath) {
	if (process.platform === 'win32') {
		return filepath.replace(/\\/g, '/');
	} else {
		return filepath;
	}
}

function formatTwoDigists(number) {
	if (number < 10) {
		return '0' + number;
	} else {
		return number.toString();
	}
}

function formatTimestamp(date) {
	var str = date.getFullYear() + '';
	str += formatTwoDigists(date.getMonth() + 1);
	str += formatTwoDigists(date.getDate());
	str += formatTwoDigists(date.getHours());
	str += formatTwoDigists(date.getMinutes());
	str += formatTwoDigists(date.getSeconds());
	return str;
}

function optionalValue(value, defaultValue) {
	defaultValue = defaultValue || '-';
	return value ? value : defaultValue;
}

function formatField(label, attr, separator) {
	separator = separator || ': ';
	var str = '';

	if (attr) {
		str = label + separator + attr + '\n';
	}
	return str;
}

function formatLabeledList(label, list) {
	list = list || [];
	var str = '';

	for(var i in list) {
		str += formatField(label, list[i]);
	}
	return str;
}

function formatFileList(options) {
	var str = '';

	if (options.files && options.files.length > 0) {
		str += '\n%files\n';
		if (options.defaultFilemode || options.defaultUsername || options.defaultGroupname || options.defaultDirmode) {
			str += '%defattr('
				+ optionalValue(options.defaultFilemode) + ','
				+ optionalValue(options.defaultUsername) + ','
				+ optionalValue(options.defaultGroupname) + ','
				+ optionalValue(options.defaultDirmode) + ')\n';
		}
		if (options.attributes) {
			for (var j in options.attributes) {
				var attr = options.attributes[j];
				var mode = attr.mode || '-';
				var username = attr.username || '-';
				var groupname = attr.groupname || '-';
				str += '%attr(' + mode + ',' + username + ','
					+ groupname + ') ' + attr.file + '\n';
			}
		}
		if (options.config) {
			for (var k in options.config) {
				var config = options.config[k];
				str += '%config ' + config + '\n';
			}
		}

		if (options.directives) {
			for (var l in options.directives) {
				var d = options.directives[l];
				var directive = d.directive;
				var file = d.file;
				str += directive + ' ' + file + '\n';
			}
		}

		for (var i in options.files) {
			var rpmFile = options.files[i];
//			if (!rpmFile.noRecursion) {
				if (rpmFile.filemode || rpmFile.username || rpmFile.groupname) {
					str += '%attr('
						+ optionalValue(rpmFile.filemode) + ','
						+ optionalValue(rpmFile.username) + ','
						+ optionalValue(rpmFile.groupname) + ') ';
				}
				if (rpmFile.orig.expand) {
					str += '"' + unixifyPath(path.join(path.sep, rpmFile.dest)) + '"\n';
				} else {
					str += '"' + unixifyPath(path.join(path.sep, rpmFile.dest, rpmFile.path)) + '"\n';
				}
//			} else {
//				str += '%dir "' + unixifyPath(path.join(path.sep, rpmFile.dest + rpmFile.path)) + '"\n';
//			}
		}
	}

	return str;
}

function readScriptlet(label, scriptFile) {
	var src = '';
	if (scriptFile) {
		var options = {
			encoding: scriptFile.encoding || 'utf8'
		};
		var data = fs.readFileSync(scriptFile.src, options);
		src += label + '\n';
		src += data.trim() + '\n\n';
	}
	return src;
}

function skipBinariesInNoarchPackageError() {
	return '%define _binaries_in_noarch_packages_terminate_build   0\n\n';
}

/**
 * Provides utility methods to execute a command
 * @module exec
 */
module.exports = function(options, callback) {
//	grunt.verbose.writeln('Writing SPEC basic section...');

	// FIXME the following macro definition should not be needed if the --define command line parameter is taken into account by rpmbuild
	var src = '%define   _topdir ' + path.join(process.cwd(), options.destination) + '\n\n';

	src += skipBinariesInNoarchPackageError();

	src += formatField('Name', options.name);
	src += formatField('Version', options.version);
	src += 'Release: ';
        if (options.release === true) {
                src += '1\n';
        } else if (options.release) {
                src += options.release + '\n';
	} else {
		src += 'SNAPSHOT' + formatTimestamp(new Date()) + '\n';
	}

	src += formatField('URL', options.homepage);
	src += formatField('Summary', options.summary);
	src += formatField('License', optionalValue(options.license, options.licenses && options.licenses[0] && options.licenses[0].type));
	src += formatField('Distribution', options.distribution);
	src += formatField('Vendor', options.vendor);
	src += formatField('Group', options.group);
	src += formatField('Provides', options.provides);
	src += formatLabeledList('Requires', options.requires);
	src += formatField('autoprov', 'yes');
	src += formatField('autoreq', 'yes');
	src += formatField('\n%description', options.description, '\n');

//	grunt.verbose.writeln('Writing SPEC files section...');
	src += formatFileList(options);

//	grunt.verbose.writeln('Writing SPEC scriptlet section...');
	src += readScriptlet('\n%pre', options.preInstall);
	src += readScriptlet('\n%post', options.postInstall);
	src += readScriptlet('\n%preun', options.preUninstall);
	src += readScriptlet('\n%postun', options.postUninstall);

	fs.writeFile(options.specFilepath, src, callback);
};
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema=mongoose.Schema;
var envMonitorSchema= mongoose.Schema({
    name:String, /*name of the monitor, assigned by the user*/
    mainID:String, /*main RPi's ID from the server*/
    status: Boolean, /*true if connected to the main RPi*/
    lastConnection: Date, /*Last connection to the main RPi*/
    tempUnit:String, /*Assigned by the user, value can be either 'Celsius' or 'Fahrenheit'*/
    phCal4: Date, /*Last calibration at pH 4*/
    phCal7: Date, /*Last calibration at pH 7*/
    phCal10: Date, /*Last calibration at pH 10*/
    phStatus: Boolean, /*True if the sensor is plugged in and working*/
    ecStatus: Boolean,  /*True if the sensor is plugged in and working*/
    wTempStatus: Boolean, /*True if the sensor is plugged in and working*/
    usReaderStatus: Boolean, /*True if the sensor is plugged in and working*/
    phLast: {reading: Number, date: Date, compensated:Boolean}, /*última lectura del pH (ya sea manual o de rutina) y fecha de la última lectura*/
    ecLast: {reading: Number, date: Date, compensated:Boolean}, /*última lectura del ec (ya sea manual o de rutina) y fecha de la última lectura*/
    wTempLast: {reading: Number, date: Date}, /*last wTemp*/
    usReaderLast: {reading: Number, date: Date}, /*last distance reading*/
    resSize: {height: Number, area: Number}, /*height and area of reservoir, in order to estimate the level*/
    resLevelLast: Number, /* % of capacity */
});

module.exports=mongoose.model('EnvMonitor',envMonitorSchema);
<commit_msg>Update resMonitor.js<commit_after>var mongoose = require('mongoose');
var Schema=mongoose.Schema;
var resMonitorSchema= mongoose.Schema({
    name:String, /*name of the monitor, assigned by the user*/
    mainID:String, /*main RPi's ID from the server*/
    status: Boolean, /*true if connected to the main RPi*/
    lastConnection: Date, /*Last connection to the main RPi*/
    tempUnit:String, /*Assigned by the user, value can be either 'Celsius' or 'Fahrenheit'*/
    phCal4: Date, /*Last calibration at pH 4*/
    phCal7: Date, /*Last calibration at pH 7*/
    phCal10: Date, /*Last calibration at pH 10*/
    phStatus: Boolean, /*True if the sensor is plugged in and working*/
    ecStatus: Boolean,  /*True if the sensor is plugged in and working*/
    wTempStatus: Boolean, /*True if the sensor is plugged in and working*/
    usReaderStatus: Boolean, /*True if the sensor is plugged in and working*/
    phLast: {reading: Number, date: Date, compensated:Boolean}, /*última lectura del pH (ya sea manual o de rutina) y fecha de la última lectura*/
    ecLast: {reading: Number, date: Date, compensated:Boolean}, /*última lectura del ec (ya sea manual o de rutina) y fecha de la última lectura*/
    wTempLast: {reading: Number, date: Date}, /*last wTemp*/
    usReaderLast: {reading: Number, date: Date}, /*last distance reading*/
    resSize: {height: Number, area: Number}, /*height and area of reservoir, in order to estimate the level*/
    resLevelLast: Number, /* % of capacity */
});

module.exports=mongoose.model('ResMonitor',resMonitorSchema);
<|endoftext|>


<commit_before><commit_msg>minor changes<commit_after><|endoftext|>