<commit_before>'use strict';

/**
 * Dependencies
 */
var fs = require('fs');
var del = require('del');
var gulp = require('gulp');
var karma = require('karma');
var git = require('gulp-git');
var bump = require('gulp-bump');
var sass = require('gulp-sass');
var csso = require('gulp-csso');
var jscs = require('gulp-jscs');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var jshint = require('gulp-jshint');
var cached = require('gulp-cached');
var filter = require('gulp-filter');
var replace = require('gulp-replace');
var wrapper = require('gulp-wrapper');
var stylish = require('gulp-jscs-stylish');
var sourcemaps = require('gulp-sourcemaps');
var ngAnnotate = require('gulp-ng-annotate');

/**
 * Package and configuration
 */
var pkg = require('./package.json');
var noop = function() {};

/*****************************************************************************
 * Helpers
 ***/

/**
 * Get package JSON directly from file system
 */
function packageJson() {
  return (pkg = JSON.parse(fs.readFileSync('./package.json', 'utf8')));
}

/**
 * Get package file name
 */
function packageFileName(filename, ext) {
  if (!ext) {
    ext = filename;
    filename = pkg.name;
  }
  return filename + (ext || '');
}

/**
 * Generate angular wrapper for module files
 */
function angularWrapper() {
  return {
    header: '(function(window, angular, undefined) {\'use strict\';\n',
    footer: '\n})(window, window.angular);\n'
  };
}

/**
 * Generate banner wrapper for compiled files
 */
function bannerWrapper() {

  //Refresh package JSON
  packageJson();

  //Get date and author
  var today = new Date();
  var date = today.getDate() + '-' + today.getMonth() + '-' + today.getFullYear();
  var author = pkg.author.name + ' <' + pkg.author.email + '>';

  //Format banner
  var banner =
    '/**\n' +
    ' * ' + pkg.name + ' - v' + pkg.version + ' - ' + date + '\n' +
    ' * ' + pkg.homepage + '\n' +
    ' *\n' +
    ' * Copyright (c) ' + today.getFullYear() + ' ' + author + '\n' +
    ' * License: MIT\n' +
    ' */\n';

  //Return wrapper
  return {
    header: banner,
    footer: ''
  };
}

/*****************************************************************************
 * Builders
 ***/

/**
 * Clean the release folder
 */
function clean() {
  return del('release');
}

/**
 * Build css
 */
function buildCss() {
  gulp.src('src/ngGo.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(csso())
    .pipe(rename(packageFileName('.css')))
    .pipe(gulp.dest('release'));
}

/**
 * Build release files
 */
function buildJs() {
  var jsFilter = filter(['*.js'], {
    restore: true
  });
  return gulp.src([
    'src/**/*.js'
  ]).pipe(ngAnnotate({
    single_quotes: true
  }))
    .pipe(wrapper(angularWrapper()))
    .pipe(sourcemaps.init())
      .pipe(concat(packageFileName('.js')))
      .pipe(wrapper(bannerWrapper()))
      .pipe(gulp.dest('release'))
      .pipe(rename(packageFileName('.min.js')))
      .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(jsFilter)
    .pipe(wrapper(bannerWrapper()))
    .pipe(jsFilter.restore)
    .pipe(gulp.dest('release'));
}

/*****************************************************************************
 * Linting, testing and watching
 ***/

/**
 * Lint only client code
 */
function lint() {
  return gulp.src([
    'src/**/*.js',
    'tests/**/*.spec.js'
  ]).pipe(cached('lint'))
    .pipe(jshint())
    .pipe(jscs())
    .on('error', noop)
    .pipe(stylish.combineWithHintResults())
    .pipe(jshint.reporter('jshint-stylish'));
}

/**
 * Run unit tests
 */
function test(done) {
  new karma.Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true,
    files: [
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/**/*.js',
      'tests/**/*.spec.js'
    ]
  }, done).start();
}

/**
 * Watch code and tests
 */
function watch() {
  gulp.watch([
    'src/**/*.js',
    'tests/**/*.spec.js'
  ], gulp.series(lint, test));
}

/*****************************************************************************
 * Bumpers
 ***/

/**
 * Bump version number (patch)
 */
function patchBump() {
  return gulp.src([
    './package.json',
    './bower.json'
  ]).pipe(bump({type: 'patch'}))
    .pipe(gulp.dest('./'));
}

/**
 * Bump version number (minor)
 */
function minorBump() {
  return gulp.src([
    './package.json',
    './bower.json'
  ]).pipe(bump({type: 'minor'}))
    .pipe(gulp.dest('./'));
}

/**
 * Bump version number (major)
 */
function majorBump() {
  return gulp.src([
    './package.json',
    './bower.json'
  ]).pipe(bump({type: 'major'}))
    .pipe(gulp.dest('./'));
}

/**
 * Update version in readme
 */
function updateReadmeVersion() {
  return gulp.src([
    './README.md'
  ]).pipe(replace(
    /([0-9]\.[0-9]+\.[0-9]+)/g, packageJson().version
  )).pipe(gulp.dest('./'));
}

/**
 * Update version in ngGo.js
 */
function updateSourceVersion() {
  return gulp.src([
    './src/ngGo.js'
  ]).pipe(replace(
    /'([0-9]\.[0-9]+\.[0-9]+)'/g, packageJson().version
  )).pipe(gulp.dest('./'));
}

/**
 * Commit the version bump
 */
function commitBump() {
  var version = packageJson().version;
  return gulp.src([
    './package.json',
    './bower.json',
    './release/*'
  ]).pipe(git.commit('Bump version to ' + version));
}

/**
 * Tag latest commit with current version
 */
function tagBump(cb) {
  var version = packageJson().version;
  git.tag(version, 'Tag version ' + version, function(error) {
    if (error) {
      return cb(error);
    }
    git.push('origin', 'master', {
      args: '--tags'
    }, cb);
  });
}

/*****************************************************************************
 * CLI exposed tasks
 ***/

/**
 * Build a release version
 */
gulp.task('release', gulp.series(
  clean, gulp.parallel(buildJs, buildCss)
));

/**
 * Testing, linting, watching and tagging
 */
gulp.task('test', test);
gulp.task('lint', lint);
gulp.task('watch', watch);

/**
 * Bump version numbers
 */
gulp.task('patch', gulp.series(
  patchBump, updateReadmeVersion, updateSourceVersion, 'release', commitBump, tagBump
));
gulp.task('minor', gulp.series(
  minorBump, updateReadmeVersion, updateSourceVersion, 'release', commitBump, tagBump
));
gulp.task('major', gulp.series(
  majorBump, updateReadmeVersion, updateSourceVersion, 'release', commitBump, tagBump
));

/**
 * Default task is to lint, test and release
 */
gulp.task('default', gulp.series(
  'lint', 'test', 'release'
));
<commit_msg>Remove bower.json reference<commit_after>'use strict';

/**
 * Dependencies
 */
var fs = require('fs');
var del = require('del');
var gulp = require('gulp');
var karma = require('karma');
var git = require('gulp-git');
var bump = require('gulp-bump');
var sass = require('gulp-sass');
var csso = require('gulp-csso');
var jscs = require('gulp-jscs');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var jshint = require('gulp-jshint');
var cached = require('gulp-cached');
var filter = require('gulp-filter');
var replace = require('gulp-replace');
var wrapper = require('gulp-wrapper');
var stylish = require('gulp-jscs-stylish');
var sourcemaps = require('gulp-sourcemaps');
var ngAnnotate = require('gulp-ng-annotate');

/**
 * Package and configuration
 */
var pkg = require('./package.json');
var noop = function() {};

/*****************************************************************************
 * Helpers
 ***/

/**
 * Get package JSON directly from file system
 */
function packageJson() {
  return (pkg = JSON.parse(fs.readFileSync('./package.json', 'utf8')));
}

/**
 * Get package file name
 */
function packageFileName(filename, ext) {
  if (!ext) {
    ext = filename;
    filename = pkg.name;
  }
  return filename + (ext || '');
}

/**
 * Generate angular wrapper for module files
 */
function angularWrapper() {
  return {
    header: '(function(window, angular, undefined) {\'use strict\';\n',
    footer: '\n})(window, window.angular);\n'
  };
}

/**
 * Generate banner wrapper for compiled files
 */
function bannerWrapper() {

  //Refresh package JSON
  packageJson();

  //Get date and author
  var today = new Date();
  var date = today.getDate() + '-' + today.getMonth() + '-' + today.getFullYear();
  var author = pkg.author.name + ' <' + pkg.author.email + '>';

  //Format banner
  var banner =
    '/**\n' +
    ' * ' + pkg.name + ' - v' + pkg.version + ' - ' + date + '\n' +
    ' * ' + pkg.homepage + '\n' +
    ' *\n' +
    ' * Copyright (c) ' + today.getFullYear() + ' ' + author + '\n' +
    ' * License: MIT\n' +
    ' */\n';

  //Return wrapper
  return {
    header: banner,
    footer: ''
  };
}

/*****************************************************************************
 * Builders
 ***/

/**
 * Clean the release folder
 */
function clean() {
  return del('release');
}

/**
 * Build css
 */
function buildCss() {
  gulp.src('src/ngGo.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(csso())
    .pipe(rename(packageFileName('.css')))
    .pipe(gulp.dest('release'));
}

/**
 * Build release files
 */
function buildJs() {
  var jsFilter = filter(['*.js'], {
    restore: true
  });
  return gulp.src([
    'src/**/*.js'
  ]).pipe(ngAnnotate({
    single_quotes: true
  }))
    .pipe(wrapper(angularWrapper()))
    .pipe(sourcemaps.init())
      .pipe(concat(packageFileName('.js')))
      .pipe(wrapper(bannerWrapper()))
      .pipe(gulp.dest('release'))
      .pipe(rename(packageFileName('.min.js')))
      .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(jsFilter)
    .pipe(wrapper(bannerWrapper()))
    .pipe(jsFilter.restore)
    .pipe(gulp.dest('release'));
}

/*****************************************************************************
 * Linting, testing and watching
 ***/

/**
 * Lint only client code
 */
function lint() {
  return gulp.src([
    'src/**/*.js',
    'tests/**/*.spec.js'
  ]).pipe(cached('lint'))
    .pipe(jshint())
    .pipe(jscs())
    .on('error', noop)
    .pipe(stylish.combineWithHintResults())
    .pipe(jshint.reporter('jshint-stylish'));
}

/**
 * Run unit tests
 */
function test(done) {
  new karma.Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true,
    files: [
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/**/*.js',
      'tests/**/*.spec.js'
    ]
  }, done).start();
}

/**
 * Watch code and tests
 */
function watch() {
  gulp.watch([
    'src/**/*.js',
    'tests/**/*.spec.js'
  ], gulp.series(lint, test));
}

/*****************************************************************************
 * Bumpers
 ***/

/**
 * Bump version number (patch)
 */
function patchBump() {
  return gulp.src([
    './package.json'
  ]).pipe(bump({type: 'patch'}))
    .pipe(gulp.dest('./'));
}

/**
 * Bump version number (minor)
 */
function minorBump() {
  return gulp.src([
    './package.json'
  ]).pipe(bump({type: 'minor'}))
    .pipe(gulp.dest('./'));
}

/**
 * Bump version number (major)
 */
function majorBump() {
  return gulp.src([
    './package.json'
  ]).pipe(bump({type: 'major'}))
    .pipe(gulp.dest('./'));
}

/**
 * Update version in readme
 */
function updateReadmeVersion() {
  return gulp.src([
    './README.md'
  ]).pipe(replace(
    /([0-9]\.[0-9]+\.[0-9]+)/g, packageJson().version
  )).pipe(gulp.dest('./'));
}

/**
 * Update version in ngGo.js
 */
function updateSourceVersion() {
  return gulp.src([
    './src/ngGo.js'
  ]).pipe(replace(
    /'([0-9]\.[0-9]+\.[0-9]+)'/g, packageJson().version
  )).pipe(gulp.dest('./'));
}

/**
 * Commit the version bump
 */
function commitBump() {
  var version = packageJson().version;
  return gulp.src([
    './package.json',
    './release/*'
  ]).pipe(git.commit('Bump version to ' + version));
}

/**
 * Tag latest commit with current version
 */
function tagBump(cb) {
  var version = packageJson().version;
  git.tag(version, 'Tag version ' + version, function(error) {
    if (error) {
      return cb(error);
    }
    git.push('origin', 'master', {
      args: '--tags'
    }, cb);
  });
}

/*****************************************************************************
 * CLI exposed tasks
 ***/

/**
 * Build a release version
 */
gulp.task('release', gulp.series(
  clean, gulp.parallel(buildJs, buildCss)
));

/**
 * Testing, linting, watching and tagging
 */
gulp.task('test', test);
gulp.task('lint', lint);
gulp.task('watch', watch);

/**
 * Bump version numbers
 */
gulp.task('patch', gulp.series(
  patchBump, updateReadmeVersion, updateSourceVersion, 'release', commitBump, tagBump
));
gulp.task('minor', gulp.series(
  minorBump, updateReadmeVersion, updateSourceVersion, 'release', commitBump, tagBump
));
gulp.task('major', gulp.series(
  majorBump, updateReadmeVersion, updateSourceVersion, 'release', commitBump, tagBump
));

/**
 * Default task is to lint, test and release
 */
gulp.task('default', gulp.series(
  'lint', 'test', 'release'
));
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.use(express.static('public'));

var server = app.listen(3000, function () {
  console.log('started');
});
<commit_msg>Include socket io<commit_after>var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);

app.use(express.static('public'));

// io.on('connection', function (socket) {
//   socket.emit('news', { hello: 'world' });
//   socket.on('my other event', function (data) {
//     console.log(data);
//   });
// });
<|endoftext|>


<commit_before>'use strict';

var api = require('./modules/api'),
    index = require('./modules/index');

var custMiddleware = require('./middleware');

module.exports = function(app) {

    // Core
    app.use('/api/users', require('./modules/user').middleware); /*users*/
    app.use('/api/session', require('./modules/session').middleware); /*session*/
    app.use('/api/files', require('./modules/file').middleware); /*files*/

    // Settings
    app.use('/api/settings/broker', require('./modules/settings/broker').middleware); /*broker*/

    // All other routes to use Angular routing in app/scripts/app.js
    app.get('/modules/*', index.partials);
    app.get('/*', custMiddleware.setUserCookie, index.index);

    // All undefined api routes should return a 404
    app.get('/api/*', function(req, res) {
        res.send(404);
    });

};
<commit_msg>Updated broker routes<commit_after>'use strict';

var api = require('./modules/api'),
    index = require('./modules/index');

var custMiddleware = require('./middleware');

module.exports = function(app) {

    // Core
    app.use('/api/users', require('./modules/user').middleware); /*users*/
    app.use('/api/session', require('./modules/session').middleware); /*session*/
    app.use('/api/files', require('./modules/file').middleware); /*files*/

    // Settings
    app.use('/api/broker', require('./modules/settings/broker').middleware); /*broker*/

    // All other routes to use Angular routing in app/scripts/app.js
    app.get('/modules/*', index.partials);
    app.get('/*', custMiddleware.setUserCookie, index.index);

    // All undefined api routes should return a 404
    app.get('/api/*', function(req, res) {
        res.send(404);
    });

};
<|endoftext|>


<commit_before><commit_msg>Modify bawls file to use parent element's height as canvas height.<commit_after><|endoftext|>


<commit_before>const gulp = require('gulp');
var gutil = require('gulp-util');
const through = require('through2');

const strip = require('gulp-strip-code');
const rename = require('gulp-rename');
const gzip = require('gulp-gzip');

const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

const clone = require('gulp-clone');
const gulpMerge = require('gulp-merge');

const path = require('path');

/**
 * a gulp transformer that keeps the smallest file and discard the rest
 * @returns {*}
 */
const keepSmallest = () => {

    const files = [];

    function transform(file, encoding, callback) {
        files.push(file);
        callback();
    }

    function flush() {

        files.sort(function (a, b) {
            const sizeA = a.contents.byteLength;
            const sizeB = b.contents.byteLength;
            return (sizeA < sizeB) ? -1 : (sizeA > sizeB) ? 1 : 0;
        });

        files.forEach((file, index) => {
            const size = (index
                    ? gutil.colors.red(file.contents.byteLength)
                    : gutil.colors.green(file.contents.byteLength)
            );

            gutil.log(gutil.colors.magenta(path.basename(file.path)), size);
        });

        this.push(files[0]);
    }

    return through.obj(transform, flush);
};

const getBaseStream = () => {
    return gulp
        .src('src/dotdom.js')
        .pipe(strip({
            start_comment: 'BEGIN NPM-GLUE',
            end_comment: 'END NPM-GLUE'
        }));
};

gulp.task('build:js', () => {
    console.log('!!')
    const baseStream = getBaseStream();

    return gulpMerge(
        baseStream
            .pipe(clone())
            .pipe(uglify())
            .pipe(rename({
                suffix: '-uglify'
            })),
        baseStream
            .pipe(clone())
            .pipe(babel({
                presets: ['babili']
            }))
            .pipe(rename({
                suffix: '-babili'
            }))
    )
        .pipe(keepSmallest())
        .pipe(clone())
        .pipe(rename({
            basename: 'dotdom.min'
        }))
        .pipe(gulp.dest('./'));

});

gulp.task('build:gz', () => {

    const baseStream = getBaseStream();

    return gulpMerge(
        baseStream
            .pipe(clone())
            .pipe(uglify())
            .pipe(rename({
                suffix: '-uglify'
            }))
            .pipe(gzip({gzipOptions: {level: 9}})),
        baseStream
            .pipe(clone())
            .pipe(babel({
                presets: ['babili']
            }))
            .pipe(rename({
                suffix: '-babili'
            }))
            .pipe(gzip({gzipOptions: {level: 9}}))
    )
        .pipe(keepSmallest())
        .pipe(clone())
        .pipe(rename({
            basename: 'dotdom.min.js'
        }))
        .pipe(gulp.dest('./'));

});

gulp.task('build', ['build:js', 'build:gz']);

gulp.task('watch', () => {
    const watcher = gulp.watch('./src/**/*.js', ['build:js']);
    watcher.on('change', function (event) {
        gutil.log('File', gutil.colors.magenta(event.path), 'was', gutil.colors.cyan(event.type));
    });
    return watcher;
});

gulp.task('default', ['build', 'watch']);
<commit_msg>building with gulp and automatically picking smallest file<commit_after>const gulp = require('gulp');
var gutil = require('gulp-util');
const through = require('through2');

const strip = require('gulp-strip-code');
const rename = require('gulp-rename');
const gzip = require('gulp-gzip');

const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

const clone = require('gulp-clone');
const gulpMerge = require('gulp-merge');

const path = require('path');

/**
 * a gulp transformer that keeps the smallest file and discard the rest
 * @returns {*}
 */
const keepSmallest = () => {

    const files = [];

    function transform(file, encoding, callback) {
        files.push(file);
        callback();
    }

    function flush() {

        files.sort(function (a, b) {
            const sizeA = a.contents.byteLength;
            const sizeB = b.contents.byteLength;
            return (sizeA < sizeB) ? -1 : (sizeA > sizeB) ? 1 : 0;
        });

        files.forEach((file, index) => {
            const size = (index
                    ? gutil.colors.red(file.contents.byteLength)
                    : gutil.colors.green(file.contents.byteLength)
            );

            gutil.log(gutil.colors.magenta(path.basename(file.path)), size);
        });

        this.push(files[0]);
    }

    return through.obj(transform, flush);
};

const getBaseStream = () => {
    return gulp
        .src('src/dotdom.js')
        .pipe(strip({
            start_comment: 'BEGIN NPM-GLUE',
            end_comment: 'END NPM-GLUE'
        }));
};

gulp.task('build:js', () => {

    const baseStream = getBaseStream();

    return gulpMerge(
        baseStream
            .pipe(clone())
            .pipe(uglify())
            .pipe(rename({
                suffix: '-uglify'
            })),
        baseStream
            .pipe(clone())
            .pipe(babel({
                presets: ['babili']
            }))
            .pipe(rename({
                suffix: '-babili'
            }))
    )
        .pipe(keepSmallest())
        .pipe(clone())
        .pipe(rename({
            basename: 'dotdom.min'
        }))
        .pipe(gulp.dest('./'));

});

gulp.task('build:gz', () => {

    const baseStream = getBaseStream();

    return gulpMerge(
        baseStream
            .pipe(clone())
            .pipe(uglify())
            .pipe(rename({
                suffix: '-uglify'
            }))
            .pipe(gzip({gzipOptions: {level: 9}})),
        baseStream
            .pipe(clone())
            .pipe(babel({
                presets: ['babili']
            }))
            .pipe(rename({
                suffix: '-babili'
            }))
            .pipe(gzip({gzipOptions: {level: 9}}))
    )
        .pipe(keepSmallest())
        .pipe(clone())
        .pipe(rename({
            basename: 'dotdom.min.js'
        }))
        .pipe(gulp.dest('./'));

});

gulp.task('build', ['build:js', 'build:gz']);

gulp.task('watch', () => {
    const watcher = gulp.watch('./src/**/*.js', ['build:js']);
    watcher.on('change', function (event) {
        gutil.log('File', gutil.colors.magenta(event.path), 'was', gutil.colors.cyan(event.type));
    });
    return watcher;
});

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


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  //  sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`resetinstagram\` - Delete Instagram account.
\`deleteoauth\` - Delete the customers oAuth Token .
\`tool\` - Provide link to the AuthentiPix oAuth tool.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp.message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// use a regex as well //
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// Return The AuthentiPix oAuth tool//
slapp.message('tool', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Here is the AuthentiPix Tool ',
    attachments: [{
      text: 'Check AuthentiPix Customers oAuth Status',
      title: 'AuthentiPix oAuth Tool',
      title_link: 'https://aptools.azurewebsites.net/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>added delete o auth command<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  //  sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`resetinstagram\` - Delete Instagram account.
\`deleteoauth\` - Delete the customers oAuth Token .
\`tool\` - Provide link to the AuthentiPix oAuth tool.
`

//*********************************************
// Handlers for Messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

slapp.command('/deleteoauth', /^in/, (msg) => {
  // `respond` is used for actions or commands and uses the `response_url` provided by the
  // incoming request from Slack
  msg.respond(`Glad you are in ${match}!`)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp.message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// use a regex as well //
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// Return The AuthentiPix oAuth tool//
slapp.message('tool', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Here is the AuthentiPix Tool ',
    attachments: [{
      text: 'Check AuthentiPix Customers oAuth Status',
      title: 'AuthentiPix oAuth Tool',
      title_link: 'https://aptools.azurewebsites.net/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>(function () {

  var MzMap = function () {

    this.markers = [];

    this.init = function() {
      // Opera Mini
      if ( /Opera Mini/.test(navigator.userAgent) ) {
        $(".map-drilldown")
          .html('
' + this.toMessage("browser not supported") + '
');
        return;
      }

      this.createMap();
      this.addMessageControlToMap();
      this.maintainMapCenterOnResize();
      this.enableGeocoder();

      this.messageHolderHTMLLocation("ready to search");
    };

    this.createMap = function () {
      var self = this;
      var map_element = document.getElementById("map-drilldown-canvas");
      if (!map_element) return false;

      var myOptions = {

        // Choose a map type that is clear
        mapTypeId: google.maps.MapTypeId.TERRAIN,

        // no point letting users zoom in too far for the purposes of finding a
        // constituency - adds server load and is not helpful to them.
        maxZoom: 12,

        // Use default controls (ie show or hide depending on device) and then
        // switch off irrelevant ones.
        disableDefaultUI:   false,
        mapTypeControl:     true,
        scaleControl:       false,
        streetViewControl:  false,
        overviewMapControl: false

      };

      var map = this.map = new google.maps.Map(map_element, myOptions);

      // We want a single click/tap to position the map where it was tapped. Add
      // smarts to wait and be sure that we didn't just trigger on the start of a
      // double tap, used to zoom. Could instead handle the zoom on dblclick
      // ourselves, but that could get tricky...
      var clickTimeoutId = null;
      google.maps.event.addListener(
        map,
        'click',
        function (event) {
          clickTimeoutId = setTimeout(
            function () { self.clickEventHandler(event) },
            400 // max delay between two clicks
          );
        }
      );
      google.maps.event.addListener(
        map,
        'dblclick',
        function () {
          clearTimeout(clickTimeoutId);
        }
      );

      map.fitBounds( this.make_bounds() );

      return map;
    };

    this.addMessageControlToMap = function () {
      var map = this.map;
      var control = $('#map-drilldown-message').get(0);
      control.index = 1;
      map
        .controls[google.maps.ControlPosition.TOP_CENTER]
        .push(control);
      $(control).show();
    };

    this.toMessage = function ( key ) {
      return mapDrilldownSettings.i18n[key] || key;
    }

    this.messageHolderHTMLLocation = function (html) {
      $('#map-drilldown-message div.location').html( this.toMessage(html) );
    };

    this.make_bounds = function () {

        var bounds = {
          north: window.pombola_settings.map_bounds.north,
          east:  window.pombola_settings.map_bounds.east,
          south: window.pombola_settings.map_bounds.south,
          west:  window.pombola_settings.map_bounds.west
        };

        var sw = new google.maps.LatLng( bounds.south, bounds.west );
        var ne = new google.maps.LatLng( bounds.north, bounds.east );
        return new google.maps.LatLngBounds( sw, ne );
    };

    this.centerMapInWindow = function (loc) {
      var map = this.map;

      // Make the map the same height as the window, and then scroll to the top
      // of it to fill the window
      var $canvas = $('#map-drilldown-canvas');
      $canvas.height( $(window).height() );
      google.maps.event.trigger(map, 'resize');
      window.scrollTo( 0, $canvas.offset().top );

      if ( loc ) {
        map.setCenter( loc );
      }
    };

    this.maintainMapCenterOnResize = function () {
      var self = this;
      var map = this.map;

      this.centerMapInWindow();

      // Maintain the centre of the map in the same place when the window is
      // resized (includes changing screen orientation).
      // Adapted from http://stackoverflow.com/q/8792676/5349
      var currentMapCenter = null;

      // When the map is not moving store the current location. Use a timeout so rapid
      // changes do not get stored, which is what happens when the resize and
      // orientationchange events fire in succession on a mobile.
      google.maps.event.addListener(
        map,
        'idle',
        _.debounce(
          function () {
            var center = map.getCenter();
            currentMapCenter = new google.maps.LatLng( center.lat(), center.lng() );
          },
          400
        )
      );

      // Handle events - debounce these as well
      var eventHandler = _.debounce(
        function () {
          self.centerMapInWindow( currentMapCenter );
        },
        200
      );
      google.maps.event.addDomListener( window, 'resize',            eventHandler);
      google.maps.event.addDomListener( window, 'orientationchange', eventHandler);
    };

    // redirect to the location of the click
    this.clickEventHandler = function(event) {
      var loc = event.latLng;
      var path = "/place/latlon/" + loc.lat()  + "," + loc.lng() + "/";
      document.location = path;
    };

    this.enableGeocoder = function () {
      var self = this;
      var geocoder = new google.maps.Geocoder();

      var $search_form  = $('#map-drilldown-message form.search');
      var $search_input = $search_form.find('input[type="search"]');

      $search_form.submit(
        function (event) {

          // There is nowhere else for the form to submit to
          event.preventDefault();

          // Tell the user that we are searching, it's a remote call so may take
          // a while to come back
          self.messageHolderHTMLLocation("geocoder searching");

          // construct the search arguments, including country bounds.
          var geocoder_args = {
            address: $search_input.attr("value"),
            bounds: self.make_bounds()
          };

          // start the geocoding request
          geocoder.geocode(
            geocoder_args,
            function (results, status) {

              // filter out results that are not in the area we're interested in (we hint to
              // google where to search, but they sometimes ignore the hint).
              var desired_bounds = self.make_bounds();
              results = _.filter(results, function (result) {
                return desired_bounds.contains(result.geometry.location);
              });

              // found no matches (or no matches that are within our bounds)
              if (status == google.maps.GeocoderStatus.ZERO_RESULTS || (status == google.maps.GeocoderStatus.OK && results.length == 0) ) {
                self.messageHolderHTMLLocation( "zero geocoder results");
              }

              // found some matches
              else if (status == google.maps.GeocoderStatus.OK) {

                var map = self.map;

                // Remove all the existing markers from the map
                _.each(self.markers, function (marker) {
                  marker.setMap(null);
                });
                self.markers = [];

                // for each result...
                _.each( results, function (result) {

                  // ...create a marker and add it to the map
                  var marker = new google.maps.Marker({
                    map: map,
                    position: result.geometry.location,
                    title: result.formatted_address,
                  });

                  // ...set the click handler
                  google.maps.event.addListener(marker, "click", self.clickEventHandler);

                  // ...add to marker array for later reference
                  self.markers.push(marker);
                });

                // Once all the pins are on we want to make sure they are
                // visible on the map. Use a bounds to cover them all and then
                // fit the map to it. If there is only one result use the viewport
                // that the API provides (eg someone map have searched for their province)
                var marker_bounds = null;
                if (self.markers.length == 1) {
                  marker_bounds = results[0].geometry.viewport;
                } else {
                  marker_bounds = new google.maps.LatLngBounds();
                  _.each( self.markers, function (marker) {
                    marker_bounds.extend(marker.getPosition());
                  });
                }
                map.fitBounds(marker_bounds);

                // All done, display a message to the user
                self.messageHolderHTMLLocation( "geocoder results displayed");
              }

              // other (most likely an error)
              else {
                self.messageHolderHTMLLocation( "geocoder error");
              }

            }
          );
        }
      );

    };

  };

  pombola_run_when_document_ready(
      function () {
          google.load(
              'maps', '3',
              {
                  callback: function () {
                    var myMzMap = new MzMap();
                    myMzMap.init();
                  },
                  other_params:'sensor=true'
              }
          );
      }
  );

})();
<commit_msg>Limit the precision of the coords sent to the /place/latlon/ page<commit_after>(function () {

  var MzMap = function () {

    this.markers = [];

    this.init = function() {
      // Opera Mini
      if ( /Opera Mini/.test(navigator.userAgent) ) {
        $(".map-drilldown")
          .html('
' + this.toMessage("browser not supported") + '
');
        return;
      }

      this.createMap();
      this.addMessageControlToMap();
      this.maintainMapCenterOnResize();
      this.enableGeocoder();

      this.messageHolderHTMLLocation("ready to search");
    };

    this.createMap = function () {
      var self = this;
      var map_element = document.getElementById("map-drilldown-canvas");
      if (!map_element) return false;

      var myOptions = {

        // Choose a map type that is clear
        mapTypeId: google.maps.MapTypeId.TERRAIN,

        // no point letting users zoom in too far for the purposes of finding a
        // constituency - adds server load and is not helpful to them.
        maxZoom: 12,

        // Use default controls (ie show or hide depending on device) and then
        // switch off irrelevant ones.
        disableDefaultUI:   false,
        mapTypeControl:     true,
        scaleControl:       false,
        streetViewControl:  false,
        overviewMapControl: false

      };

      var map = this.map = new google.maps.Map(map_element, myOptions);

      // We want a single click/tap to position the map where it was tapped. Add
      // smarts to wait and be sure that we didn't just trigger on the start of a
      // double tap, used to zoom. Could instead handle the zoom on dblclick
      // ourselves, but that could get tricky...
      var clickTimeoutId = null;
      google.maps.event.addListener(
        map,
        'click',
        function (event) {
          clickTimeoutId = setTimeout(
            function () { self.clickEventHandler(event) },
            400 // max delay between two clicks
          );
        }
      );
      google.maps.event.addListener(
        map,
        'dblclick',
        function () {
          clearTimeout(clickTimeoutId);
        }
      );

      map.fitBounds( this.make_bounds() );

      return map;
    };

    this.addMessageControlToMap = function () {
      var map = this.map;
      var control = $('#map-drilldown-message').get(0);
      control.index = 1;
      map
        .controls[google.maps.ControlPosition.TOP_CENTER]
        .push(control);
      $(control).show();
    };

    this.toMessage = function ( key ) {
      return mapDrilldownSettings.i18n[key] || key;
    }

    this.messageHolderHTMLLocation = function (html) {
      $('#map-drilldown-message div.location').html( this.toMessage(html) );
    };

    this.make_bounds = function () {

        var bounds = {
          north: window.pombola_settings.map_bounds.north,
          east:  window.pombola_settings.map_bounds.east,
          south: window.pombola_settings.map_bounds.south,
          west:  window.pombola_settings.map_bounds.west
        };

        var sw = new google.maps.LatLng( bounds.south, bounds.west );
        var ne = new google.maps.LatLng( bounds.north, bounds.east );
        return new google.maps.LatLngBounds( sw, ne );
    };

    this.centerMapInWindow = function (loc) {
      var map = this.map;

      // Make the map the same height as the window, and then scroll to the top
      // of it to fill the window
      var $canvas = $('#map-drilldown-canvas');
      $canvas.height( $(window).height() );
      google.maps.event.trigger(map, 'resize');
      window.scrollTo( 0, $canvas.offset().top );

      if ( loc ) {
        map.setCenter( loc );
      }
    };

    this.maintainMapCenterOnResize = function () {
      var self = this;
      var map = this.map;

      this.centerMapInWindow();

      // Maintain the centre of the map in the same place when the window is
      // resized (includes changing screen orientation).
      // Adapted from http://stackoverflow.com/q/8792676/5349
      var currentMapCenter = null;

      // When the map is not moving store the current location. Use a timeout so rapid
      // changes do not get stored, which is what happens when the resize and
      // orientationchange events fire in succession on a mobile.
      google.maps.event.addListener(
        map,
        'idle',
        _.debounce(
          function () {
            var center = map.getCenter();
            currentMapCenter = new google.maps.LatLng( center.lat(), center.lng() );
          },
          400
        )
      );

      // Handle events - debounce these as well
      var eventHandler = _.debounce(
        function () {
          self.centerMapInWindow( currentMapCenter );
        },
        200
      );
      google.maps.event.addDomListener( window, 'resize',            eventHandler);
      google.maps.event.addDomListener( window, 'orientationchange', eventHandler);
    };

    // redirect to the location of the click
    this.clickEventHandler = function(event) {
      var precision = 3; // suitable for the max zoom we allow
      var path = "/place/latlon/" + event.latLng.toUrlValue(precision) + "/";
      document.location = path;
    };

    this.enableGeocoder = function () {
      var self = this;
      var geocoder = new google.maps.Geocoder();

      var $search_form  = $('#map-drilldown-message form.search');
      var $search_input = $search_form.find('input[type="search"]');

      $search_form.submit(
        function (event) {

          // There is nowhere else for the form to submit to
          event.preventDefault();

          // Tell the user that we are searching, it's a remote call so may take
          // a while to come back
          self.messageHolderHTMLLocation("geocoder searching");

          // construct the search arguments, including country bounds.
          var geocoder_args = {
            address: $search_input.attr("value"),
            bounds: self.make_bounds()
          };

          // start the geocoding request
          geocoder.geocode(
            geocoder_args,
            function (results, status) {

              // filter out results that are not in the area we're interested in (we hint to
              // google where to search, but they sometimes ignore the hint).
              var desired_bounds = self.make_bounds();
              results = _.filter(results, function (result) {
                return desired_bounds.contains(result.geometry.location);
              });

              // found no matches (or no matches that are within our bounds)
              if (status == google.maps.GeocoderStatus.ZERO_RESULTS || (status == google.maps.GeocoderStatus.OK && results.length == 0) ) {
                self.messageHolderHTMLLocation( "zero geocoder results");
              }

              // found some matches
              else if (status == google.maps.GeocoderStatus.OK) {

                var map = self.map;

                // Remove all the existing markers from the map
                _.each(self.markers, function (marker) {
                  marker.setMap(null);
                });
                self.markers = [];

                // for each result...
                _.each( results, function (result) {

                  // ...create a marker and add it to the map
                  var marker = new google.maps.Marker({
                    map: map,
                    position: result.geometry.location,
                    title: result.formatted_address,
                  });

                  // ...set the click handler
                  google.maps.event.addListener(marker, "click", self.clickEventHandler);

                  // ...add to marker array for later reference
                  self.markers.push(marker);
                });

                // Once all the pins are on we want to make sure they are
                // visible on the map. Use a bounds to cover them all and then
                // fit the map to it. If there is only one result use the viewport
                // that the API provides (eg someone map have searched for their province)
                var marker_bounds = null;
                if (self.markers.length == 1) {
                  marker_bounds = results[0].geometry.viewport;
                } else {
                  marker_bounds = new google.maps.LatLngBounds();
                  _.each( self.markers, function (marker) {
                    marker_bounds.extend(marker.getPosition());
                  });
                }
                map.fitBounds(marker_bounds);

                // All done, display a message to the user
                self.messageHolderHTMLLocation( "geocoder results displayed");
              }

              // other (most likely an error)
              else {
                self.messageHolderHTMLLocation( "geocoder error");
              }

            }
          );
        }
      );

    };

  };

  pombola_run_when_document_ready(
      function () {
          google.load(
              'maps', '3',
              {
                  callback: function () {
                    var myMzMap = new MzMap();
                    myMzMap.init();
                  },
                  other_params:'sensor=true'
              }
          );
      }
  );

})();
<|endoftext|>


<commit_before><commit_msg>Fix scrolling behavior with navbar<commit_after><|endoftext|>


<commit_before>'use strict';

const $ = require('gulp-load-plugins')();
const config = require('./build.json');
const gulp = require('gulp');

// Declare release task
$.release.register(gulp);

/**
 * Runs eslint linter on source code
 * and prints a report.
 *
 * `gulp eslint`
 */
gulp.task('eslint', function() {
  return gulp.src(config.paths.src)
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.if(config.eslint.failOnError, $.eslint.failOnError()));
});

/**
 * Runs unit tests and prints out
 * a report.
 *
 * `gulp test`
 */
gulp.task('test', function(cb) {
  gulp.src(config.paths.src)
    .pipe($.istanbul()) // Covering files
    .pipe($.istanbul.hookRequire()) // Force `require` to return covered files
    .on('finish', function() {
      gulp.src(config.paths.test)
        .pipe($.mocha())
        .pipe($.istanbul.writeReports()) // Creating the reports after tests ran
        .pipe($.istanbul.enforceThresholds({
          thresholds: {
            global: 80
          }
        })) // Enforce a coverage of at least 80%
        .on('end', cb);
    });
});

/**
 * Watches sources and runs linter on
 * changes.
 *
 * `gulp watch`
 */
gulp.task('watch', function() {
  gulp.watch(config.paths.src, ['eslint']);
});

/**
 * Lints source code and runs test suite.
 * Used as a pre-commit hook.
 *
 * `gulp validate`
 */
gulp.task('validate', ['eslint', 'test']);

/**
 * Alias for 'validate'.
 * Default task.
 *
 * `gulp [--debug|--debug-brk]`
 */
gulp.task('default', ['validate']);
<commit_msg>Use => functions on gulpfile<commit_after>'use strict';

const $ = require('gulp-load-plugins')();
const config = require('./build.json');
const gulp = require('gulp');

// Declare release task
$.release.register(gulp);

/**
 * Runs eslint linter on source code
 * and prints a report.
 *
 * `gulp eslint`
 */
gulp.task('eslint', () =>
  gulp.src(config.paths.src)
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.if(config.eslint.failOnError, $.eslint.failOnError()))
);

/**
 * Runs unit tests and prints out
 * a report.
 *
 * `gulp test`
 */
gulp.task('test', (cb) => {
  gulp.src(config.paths.src)
    .pipe($.istanbul()) // Covering files
    .pipe($.istanbul.hookRequire()) // Force `require` to return covered files
    .on('finish', function() {
      gulp.src(config.paths.test)
        .pipe($.mocha())
        .pipe($.istanbul.writeReports()) // Creating the reports after tests ran
        .pipe($.istanbul.enforceThresholds({
          thresholds: {
            global: 80
          }
        })) // Enforce a coverage of at least 80%
        .on('end', cb);
    });
});

/**
 * Watches sources and runs linter on
 * changes.
 *
 * `gulp watch`
 */
gulp.task('watch', () => gulp.watch(config.paths.src, ['eslint']));

/**
 * Lints source code and runs test suite.
 * Used as a pre-commit hook.
 *
 * `gulp validate`
 */
gulp.task('validate', ['eslint', 'test']);

/**
 * Alias for 'validate'.
 * Default task.
 *
 * `gulp [--debug|--debug-brk]`
 */
gulp.task('default', ['validate']);
<|endoftext|>


<commit_before>/*
** Server of the poker application - www.smartgames.tv
** Development contact: aimeric.seguin(at)gmail.com
** Project started: 20/08/2014.
** Last update: 13/10/2014.
** Copyright © 2014 Ngine Networks - All Rights Reserved.
*/

/*******************************************/
/*          	  MAJOR                    */
/*******************************************/
var		cfg = require("./conf.json");		       // Configuration file, mainly to use aliases/macros.
var		express = require("express");			   // Web application framework we use.
var		app = express();			   			   // Express server handle.
var		http = require("http").createServer(app);  // Web server object with express server as request listener.
var		io = require("socket.io")(http);		   // Socket interface, server side.
var		nsp = require("express-namespace");		   // Namespace utility.
var		shortId = require("shortid");			   // Universal short unique-ID generator.
var		table_name;		   	   					   // Common table name prefix.
var		table_id;								   // Unique table name suffix. (example: /pokertable-Zqc9qQWZf).
var		seat_nb;								   // Seat number (1 to 6 included).
var		fs = require("fs");						   // Files parsing utility.
var		device_client;							   // Identify client type.
var 	_ = require("underscore");				   // Required.
var 	texas = require("texas");				   // Poker Hands evaluator we use.

/*******************************************/
/*          	ROUTING                    */
/*******************************************/
var	tables_ids = new Array();					  // List of tables ID (in order to check the existence of a table).

app.get("/", function(request, response)
{
	table_id = shortId.generate(); // "pro" for test only.
	table_name = "pokertable-" + table_id;
	tables_ids.push(table_id);
	response.redirect(cfg.conf.host + ":" + cfg.conf.port + "/" + table_name);
});

var router = express.Router();					// Express router we use.

router.get("/pokertable-:name", function(request, response)
{
	table_id = request.params.name;	// Table ID is which indicates on the URL.
	if (tables_ids.indexOf(table_id) != -1)
	{
		device_client = false;
		response.sendFile("public/index.html", {root: __dirname });
	}
	else
	{
		response.status(404);
		response.sendFile("public/table_not_found.html", {root: __dirname });
	}
});

router.get("/seat-:name", function(request, response)
{
	if (tables_ids.indexOf(request.params.name.substr(5)) != -1)
	{
		device_client = true;
		seat_nb = +request.params.name[0];
		table_id = request.params.name.substr(5);	// Indicate we are not on a table.
		if (seat_nb <= 0 || seat_nb >= 7)
		{
			response.status(404);
			response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
		}
		response.sendFile("public/2nd_screen/login.html", {root: __dirname });
	}
	else if (request.params.name == "disconnected.html")
	{
		response.sendFile("public/2nd_screen/disconnected.html", {root: __dirname });
	}
	else
	{
		response.status(404);
		response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
	}
});

app.use('/', router);

/*******************************************/
/*          	PATH                   	   */
/*******************************************/
app.use(express.static(__dirname + '/public'));		// Serve files in ./public using the express.static() middleware.
app.use(express.static(__dirname + '/public/img'));
app.use(express.static(__dirname + '/public/styles'));
app.use(express.static(__dirname + '/public/2nd_screen'));
app.use(express.static(__dirname + '/public/2nd_screen/js2'));

/*******************************************/
/*            SPECIAL STATUS               */
/*******************************************/
// When Express has executed all middleware/routes, and found that none of them responded then...
app.use(function(request, response)
{
	response.status(404);
	response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
});

/********************************************/
/*          	PORT                        */
//*******************************************/
http.listen(cfg.conf.port, function(request, response)
{
	console.log("Running at " + cfg.conf.host + " from " + __dirname);
});

/*******************************************/
/*           SERVER INCLUDED OBJECTS       */
/*******************************************/
eval(fs.readFileSync("sv/objects.js").toString());
eval(fs.readFileSync("sv/new_table.js").toString());
eval(fs.readFileSync("sv/new_table_seats.js").toString());
eval(fs.readFileSync("sv/get_table.js").toString());
eval(fs.readFileSync("sv/get_private_id.js").toString());
eval(fs.readFileSync("sv/table_general_socket.js").toString());
eval(fs.readFileSync("sv/players_general_socket.js").toString());
eval(fs.readFileSync("sv/send_qrcodes.js").toString());
eval(fs.readFileSync("sv/send_seats_infos.js").toString());
eval(fs.readFileSync("sv/send_bets.js").toString());
eval(fs.readFileSync("sv/get_seat.js").toString());
eval(fs.readFileSync("sv/cash_game/fisher_shuffle.js").toString());
eval(fs.readFileSync("sv/cash_game/timer.js").toString());
eval(fs.readFileSync("sv/cash_game/check_blanks.js").toString());
eval(fs.readFileSync("sv/cash_game/new_cashgame.js").toString());
eval(fs.readFileSync("sv/cash_game/show_down.js").toString());
eval(fs.readFileSync("sv/cash_game/end_game.js").toString());
eval(fs.readFileSync("sv/cash_game/evalhand.js").toString());
eval(fs.readFileSync("sv/cash_game/deal_board.js").toString());
eval(fs.readFileSync("sv/cash_game/remove_last_actions.js").toString());
eval(fs.readFileSync("sv/cash_game/check_bets.js").toString());

/*******************************************/
/*          SOCKET INTERACTIONS            */
/*******************************************/
var		tables = new Array();			// Array of tables objects.
var		table;							// Current table handler.
var		private_channel;				// Device private channel.
var		clients = [];

io.on("connection", function(socket)
{
    var client_ip = socket.request.connection.remoteAddress;
    var	curgame;

   	if (typeof table_id === "undefined")
    	return ;
    console.log("New connection from " + client_ip);
    if ((table = get_table(table_id, tables)) == "not found" && !device_client)
    {
    	var		deck = new Array('2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'tc', 'jc', 'qc', 'kc', '1c',
								'2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'ts', 'js', 'qs', 'ks', '1s',
								'2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'td', 'jd', 'qd', 'kd', '1d',
								'2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'th', 'jh', 'qh', 'kh', '1h');
    	console.log("Creating a new table...\nTable ID: " + table_id);
    	curgame = new Game(deck, -1, -1, cfg.conf.small_blind, -1, cfg.conf.big_blind, 0, 0, 0, 0, "waiting", 0, new Array());
	    table = new_table(table_id, 0, "waiting", new Array(),
	    	    +cfg.conf.start_bankroll, new_table_seats(), curgame, new Array(), new Array()); // We're also calling a function.
	    tables.push(table);
	    socket.join(table.id);
   		send_qrcodes(table, table.seats);
   		table.game.turn_to = "joiners";

		io.to(table.id).emit('tableId', table.id, get_table(table.id, tables), get_table(table.id, tables).game);

		socket.on('get tableId and tableGame', function(id) {
			io.to(id).emit('give tableId and tableGame', get_table(id, tables), get_table(id, tables).game);
		});

		socket.on('re init', function(table, game) {
			show_down(table, game);
		});
	}
   	if (device_client)
   	{
   		console.log(table.private_ids);
   		private_channel = table_id + seat_nb;//shortId.generate() + seat_nb;
   		if (!get_private_id(table.private_ids, seat_nb))
   			table.private_ids.push(private_channel);
   		socket.on("get private channel", function()
   		{
   			socket.emit("private channel", private_channel, seat_nb);
   		});
   		socket.join(private_channel);
   		console.log("Joining private channel " + private_channel);
		hide_qr(table, seat_nb);
   	}
	socket.on("disconnect", function() {
		re_qr(table, seat_nb);
	});
		//io.to(table.id).emit("double blind", cfg.conf.small_blind, cfg.conf.big_blind);
	/*  socket.on("get qrcodes", function()
	{
		send_qrcodes(table, table.seats);
	});*/
	socket.on("ask buttons", function()
	{
			if (table.game.highlights_pos)
			{
				io.to(table.id).emit("place button", "sb", table.game.sb_pos);	// Respect this sending order.
				io.to(table.id).emit("place button", "dealer", table.game.d_pos);
				io.to(table.id).emit("place button", "bb", table.game.bb_pos);
			}
			io.to(table.id).emit("highlights", table.game.highlights_pos);
	});
	socket.on('get pot amount', function() {
		socket.emit('pot amount', table.game.pot_amount);
	});
	socket.on('need Id', function() {
		io.to(table.id).emit('give Idx', table_id);
	});
	io.to(table.id).emit("pot modification", table.game.pot_amount);
	send_bets(table); // Currents bets on the table.
	socket_listens_players(socket, table);
    socket_listens_global_settings(socket, table, table.seats);	// Event handler for major events.
});
<commit_msg>remove last action<commit_after>/*
** Server of the poker application - www.smartgames.tv
** Development contact: aimeric.seguin(at)gmail.com
** Project started: 20/08/2014.
** Last update: 13/10/2014.
** Copyright © 2014 Ngine Networks - All Rights Reserved.
*/

/*******************************************/
/*          	  MAJOR                    */
/*******************************************/
var		cfg = require("./conf.json");		       // Configuration file, mainly to use aliases/macros.
var		express = require("express");			   // Web application framework we use.
var		app = express();			   			   // Express server handle.
var		http = require("http").createServer(app);  // Web server object with express server as request listener.
var		io = require("socket.io")(http);		   // Socket interface, server side.
var		nsp = require("express-namespace");		   // Namespace utility.
var		shortId = require("shortid");			   // Universal short unique-ID generator.
var		table_name;		   	   					   // Common table name prefix.
var		table_id;								   // Unique table name suffix. (example: /pokertable-Zqc9qQWZf).
var		seat_nb;								   // Seat number (1 to 6 included).
var		fs = require("fs");						   // Files parsing utility.
var		device_client;							   // Identify client type.
var 	_ = require("underscore");				   // Required.
var 	texas = require("texas");				   // Poker Hands evaluator we use.

/*******************************************/
/*          	ROUTING                    */
/*******************************************/
var	tables_ids = new Array();					  // List of tables ID (in order to check the existence of a table).

app.get("/", function(request, response)
{
	table_id = shortId.generate(); // "pro" for test only.
	table_name = "pokertable-" + table_id;
	tables_ids.push(table_id);
	response.redirect(cfg.conf.host + ":" + cfg.conf.port + "/" + table_name);
});

var router = express.Router();					// Express router we use.

router.get("/pokertable-:name", function(request, response)
{
	table_id = request.params.name;	// Table ID is which indicates on the URL.
	if (tables_ids.indexOf(table_id) != -1)
	{
		device_client = false;
		response.sendFile("public/index.html", {root: __dirname });
	}
	else
	{
		response.status(404);
		response.sendFile("public/table_not_found.html", {root: __dirname });
	}
});

router.get("/seat-:name", function(request, response)
{
	if (tables_ids.indexOf(request.params.name.substr(5)) != -1)
	{
		device_client = true;
		seat_nb = +request.params.name[0];
		table_id = request.params.name.substr(5);	// Indicate we are not on a table.
		if (seat_nb <= 0 || seat_nb >= 7)
		{
			response.status(404);
			response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
		}
		response.sendFile("public/2nd_screen/login.html", {root: __dirname });
	}
	else if (request.params.name == "disconnected.html")
	{
		response.sendFile("public/2nd_screen/disconnected.html", {root: __dirname });
	}
	else
	{
		response.status(404);
		response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
	}
});

app.use('/', router);

/*******************************************/
/*          	PATH                   	   */
/*******************************************/
app.use(express.static(__dirname + '/public'));		// Serve files in ./public using the express.static() middleware.
app.use(express.static(__dirname + '/public/img'));
app.use(express.static(__dirname + '/public/styles'));
app.use(express.static(__dirname + '/public/2nd_screen'));
app.use(express.static(__dirname + '/public/2nd_screen/js2'));

/*******************************************/
/*            SPECIAL STATUS               */
/*******************************************/
// When Express has executed all middleware/routes, and found that none of them responded then...
app.use(function(request, response)
{
	response.status(404);
	response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
});

/********************************************/
/*          	PORT                        */
//*******************************************/
http.listen(cfg.conf.port, function(request, response)
{
	console.log("Running at " + cfg.conf.host + " from " + __dirname);
});

/*******************************************/
/*           SERVER INCLUDED OBJECTS       */
/*******************************************/
eval(fs.readFileSync("sv/objects.js").toString());
eval(fs.readFileSync("sv/new_table.js").toString());
eval(fs.readFileSync("sv/new_table_seats.js").toString());
eval(fs.readFileSync("sv/get_table.js").toString());
eval(fs.readFileSync("sv/get_private_id.js").toString());
eval(fs.readFileSync("sv/table_general_socket.js").toString());
eval(fs.readFileSync("sv/players_general_socket.js").toString());
eval(fs.readFileSync("sv/send_qrcodes.js").toString());
eval(fs.readFileSync("sv/send_seats_infos.js").toString());
eval(fs.readFileSync("sv/send_bets.js").toString());
eval(fs.readFileSync("sv/get_seat.js").toString());
eval(fs.readFileSync("sv/cash_game/fisher_shuffle.js").toString());
eval(fs.readFileSync("sv/cash_game/timer.js").toString());
eval(fs.readFileSync("sv/cash_game/check_blanks.js").toString());
eval(fs.readFileSync("sv/cash_game/new_cashgame.js").toString());
eval(fs.readFileSync("sv/cash_game/show_down.js").toString());
eval(fs.readFileSync("sv/cash_game/end_game.js").toString());
eval(fs.readFileSync("sv/cash_game/evalhand.js").toString());
eval(fs.readFileSync("sv/cash_game/deal_board.js").toString());
eval(fs.readFileSync("sv/cash_game/remove_last_actions.js").toString());
eval(fs.readFileSync("sv/cash_game/check_bets.js").toString());

/*******************************************/
/*          SOCKET INTERACTIONS            */
/*******************************************/
var		tables = new Array();			// Array of tables objects.
var		table;							// Current table handler.
var		private_channel;				// Device private channel.
var		clients = [];

io.on("connection", function(socket)
{
    var client_ip = socket.request.connection.remoteAddress;
    var	curgame;

   	if (typeof table_id === "undefined")
    	return ;
    console.log("New connection from " + client_ip);
    if ((table = get_table(table_id, tables)) == "not found" && !device_client)
    {
    	var		deck = new Array('2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'tc', 'jc', 'qc', 'kc', '1c',
								'2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'ts', 'js', 'qs', 'ks', '1s',
								'2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'td', 'jd', 'qd', 'kd', '1d',
								'2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'th', 'jh', 'qh', 'kh', '1h');
    	console.log("Creating a new table...\nTable ID: " + table_id);
    	curgame = new Game(deck, -1, -1, cfg.conf.small_blind, -1, cfg.conf.big_blind, 0, 0, 0, 0, "waiting", 0, new Array());
	    table = new_table(table_id, 0, "waiting", new Array(),
	    	    +cfg.conf.start_bankroll, new_table_seats(), curgame, new Array(), new Array()); // We're also calling a function.
	    tables.push(table);
	    socket.join(table.id);
   		send_qrcodes(table, table.seats);
   		table.game.turn_to = "joiners";

		io.to(table.id).emit('tableId', table.id, get_table(table.id, tables), get_table(table.id, tables).game);

		socket.on('get tableId and tableGame', function(id) {
			io.to(id).emit('give tableId and tableGame', get_table(id, tables), get_table(id, tables).game);
		});

		socket.on('re init', function(table, game) {
			remove_last_actions(table, 2);
			show_down(table, game);
		});
	}
   	if (device_client)
   	{
   		console.log(table.private_ids);
   		private_channel = table_id + seat_nb;//shortId.generate() + seat_nb;
   		if (!get_private_id(table.private_ids, seat_nb))
   			table.private_ids.push(private_channel);
   		socket.on("get private channel", function()
   		{
   			socket.emit("private channel", private_channel, seat_nb);
   		});
   		socket.join(private_channel);
   		console.log("Joining private channel " + private_channel);
		hide_qr(table, seat_nb);
   	}
	socket.on("disconnect", function() {
		re_qr(table, seat_nb);
	});
		//io.to(table.id).emit("double blind", cfg.conf.small_blind, cfg.conf.big_blind);
	/*  socket.on("get qrcodes", function()
	{
		send_qrcodes(table, table.seats);
	});*/
	socket.on("ask buttons", function()
	{
			if (table.game.highlights_pos)
			{
				io.to(table.id).emit("place button", "sb", table.game.sb_pos);	// Respect this sending order.
				io.to(table.id).emit("place button", "dealer", table.game.d_pos);
				io.to(table.id).emit("place button", "bb", table.game.bb_pos);
			}
			io.to(table.id).emit("highlights", table.game.highlights_pos);
	});
	socket.on('get pot amount', function() {
		socket.emit('pot amount', table.game.pot_amount);
	});
	socket.on('need Id', function() {
		io.to(table.id).emit('give Idx', table_id);
	});
	io.to(table.id).emit("pot modification", table.game.pot_amount);
	send_bets(table); // Currents bets on the table.
	socket_listens_players(socket, table);
    socket_listens_global_settings(socket, table, table.seats);	// Event handler for major events.
});
<|endoftext|>


<commit_before>'use strict'

/** @typedef {import('./index').Logger} Logger */

const chalk = require('chalk')
const Listr = require('listr')
const symbols = require('log-symbols')

const chunkFiles = require('./chunkFiles')
const generateTasks = require('./generateTasks')
const getStagedFiles = require('./getStagedFiles')
const GitWorkflow = require('./gitWorkflow')
const makeCmdTasks = require('./makeCmdTasks')
const resolveGitRepo = require('./resolveGitRepo')

const debugLog = require('debug')('lint-staged:run')

const getRenderer = ({ debug, quiet }) => {
  if (quiet) return 'silent'
  // Better support for dumb terminals: https://en.wikipedia.org/wiki/Computer_terminal#Dumb_terminals
  const isDumbTerminal = process.env.TERM === 'dumb'
  if (debug || isDumbTerminal) return 'verbose'
  return 'update'
}

const MESSAGES = {
  TASK_ERROR: 'Skipped because of errors from tasks.',
  GIT_ERROR: 'Skipped because of previous git error.'
}

const shouldSkipApplyModifications = ctx => {
  // Should be skipped in case of git errors
  if (ctx.gitError) {
    return MESSAGES.GIT_ERROR
  }
  // Should be skipped when tasks fail
  if (ctx.taskError) {
    return MESSAGES.TASK_ERROR
  }
}

const shouldSkipRevert = ctx => {
  // Should be skipped in case of unknown git errors
  if (ctx.gitError && !ctx.gitApplyEmptyCommitError && !ctx.gitRestoreUnstagedChangesError) {
    return MESSAGES.GIT_ERROR
  }
}

const shouldSkipCleanup = ctx => {
  // Should be skipped in case of unknown git errors
  if (ctx.gitError && !ctx.gitApplyEmptyCommitError && !ctx.gitRestoreUnstagedChangesError) {
    return MESSAGES.GIT_ERROR
  }
  // Should be skipped when reverting to original state fails
  if (ctx.gitRestoreOriginalStateError) {
    return MESSAGES.GIT_ERROR
  }
}

/**
 * Executes all tasks and either resolves or rejects the promise
 *
 * @param {object} options
 * @param {Object} [options.allowEmpty] - Allow empty commits when tasks revert all staged changes
 * @param {boolean | number} [options.concurrent] - The number of tasks to run concurrently, or false to run tasks serially
 * @param {Object} [options.config] - Task configuration
 * @param {Object} [options.cwd] - Current working directory
 * @param {boolean} [options.debug] - Enable debug mode
 * @param {number} [options.maxArgLength] - Maximum argument string length
 * @param {boolean} [options.quiet] - Disable lint-staged’s own console output
 * @param {boolean} [options.relative] - Pass relative filepaths to tasks
 * @param {boolean} [options.shell] - Skip parsing of tasks for better shell support
 * @param {boolean} [options.stash] - Enable the backup stash, and revert in case of errors
 * @param {Logger} logger
 * @returns {Promise}
 */
const runAll = async (
  {
    allowEmpty = false,
    concurrent = true,
    config,
    cwd = process.cwd(),
    debug = false,
    maxArgLength,
    quiet = false,
    relative = false,
    shell = false,
    stash = true
  },
  logger = console
) => {
  debugLog('Running all linter scripts')

  if (!stash) {
    logger.warn(
      `${symbols.warning} ${chalk.yellow('Skipping backup because `--no-stash` was used.')}`
    )
  }

  const { gitDir, gitConfigDir } = await resolveGitRepo(cwd)
  if (!gitDir) throw new Error('Current directory is not a git directory!')

  const files = await getStagedFiles({ cwd: gitDir })
  if (!files) throw new Error('Unable to get staged files!')
  debugLog('Loaded list of staged files in git:\n%O', files)

  // If there are no files avoid executing any lint-staged logic
  if (files.length === 0) {
    return logger.log(`${symbols.info} No staged files found.`)
  }

  const stagedFileChunks = chunkFiles({ files, gitDir, maxArgLength, relative })
  const chunkCount = stagedFileChunks.length
  if (chunkCount > 1) debugLog(`Chunked staged files into ${chunkCount} part`, chunkCount)

  // lint-staged 10 will automatically add modifications to index
  // Warn user when their command includes `git add`
  let hasDeprecatedGitAdd

  const listrOptions = {
    dateFormat: false,
    exitOnError: false,
    renderer: getRenderer({ debug, quiet })
  }

  const listrTasks = []

  for (const [index, files] of stagedFileChunks.entries()) {
    const chunkTasks = generateTasks({ config, cwd, gitDir, files, relative })
    const chunkListrTasks = []

    for (const task of chunkTasks) {
      const subTasks = await makeCmdTasks({
        commands: task.commands,
        files: task.fileList,
        gitDir,
        shell
      })

      hasDeprecatedGitAdd = subTasks.some(subTask => subTask.command === 'git add')

      chunkListrTasks.push({
        title: `Running tasks for ${task.pattern}`,
        task: async () =>
          new Listr(subTasks, {
            // In sub-tasks we don't want to run concurrently
            // and we want to abort on errors
            dateFormat: false,
            concurrent: false,
            exitOnError: true
          }),
        skip: () => {
          // Skip task when no files matched
          if (task.fileList.length === 0) {
            return `No staged files match ${task.pattern}`
          }
          return false
        }
      })
    }

    listrTasks.push({
      // No need to show number of task chunks when there's only one
      title:
        chunkCount > 1 ? `Running tasks (chunk ${index + 1}/${chunkCount})...` : 'Running tasks...',
      task: () => new Listr(chunkListrTasks, { ...listrOptions, concurrent }),
      skip: (ctx = {}) => {
        // Skip if the first step (backup) failed
        if (ctx.gitError) return MESSAGES.GIT_ERROR
        // Skip chunk when no every task is skipped (due to no matches)
        if (chunkListrTasks.every(task => task.skip())) return 'No tasks to run.'
        return false
      }
    })
  }

  if (hasDeprecatedGitAdd) {
    logger.warn(`${symbols.warning} ${chalk.yellow(
      `Some of your tasks use \`git add\` command. Please remove it from the config since all modifications made by tasks will be automatically added to the git commit index.`
    )}
`)
  }

  // If all of the configured tasks should be skipped
  // avoid executing any lint-staged logic
  if (listrTasks.every(task => task.skip())) {
    logger.log('No staged files match any of provided globs.')
    return 'No tasks to run.'
  }

  const git = new GitWorkflow({ allowEmpty, gitConfigDir, gitDir, stagedFileChunks })

  const runner = new Listr(
    [
      {
        title: 'Preparing...',
        task: ctx => git.prepare(ctx, stash)
      },
      {
        title: 'Hiding unstaged changes to partially staged files...',
        task: ctx => git.hideUnstagedChanges(ctx),
        enabled: ctx => ctx.hasPartiallyStagedFiles
      },
      ...listrTasks,
      {
        title: 'Applying modifications...',
        task: ctx => git.applyModifications(ctx),
        // Always apply back unstaged modifications when skipping backup
        skip: ctx => stash && shouldSkipApplyModifications(ctx)
      },
      {
        title: 'Restoring unstaged changes to partially staged files...',
        task: ctx => git.restoreUnstagedChanges(ctx),
        enabled: ctx => ctx.hasPartiallyStagedFiles,
        skip: shouldSkipApplyModifications
      },
      {
        title: 'Reverting to original state because of errors...',
        task: ctx => git.restoreOriginalState(ctx),
        enabled: ctx =>
          stash &&
          (ctx.taskError || ctx.gitApplyEmptyCommitError || ctx.gitRestoreUnstagedChangesError),
        skip: shouldSkipRevert
      },
      {
        title: 'Cleaning up...',
        task: ctx => git.cleanup(ctx),
        enabled: () => stash,
        skip: shouldSkipCleanup
      }
    ],
    listrOptions
  )

  try {
    await runner.run({})
  } catch (error) {
    if (error.context.gitApplyEmptyCommitError) {
      logger.warn(`
  ${symbols.warning} ${chalk.yellow(`lint-staged prevented an empty git commit.
    Use the --allow-empty option to continue, or check your task configuration`)}
`)
    } else if (error.context.gitError && !error.context.gitGetBackupStashError) {
      logger.error(`\n  ${symbols.error} ${chalk.red(`lint-staged failed due to a git error.`)}`)

      if (error.context.emptyGitRepo) {
        logger.error(
          `\n    The initial commit is needed for lint-staged to work.
    Please use the --no-verify flag to skip running lint-staged.`
        )
      } else if (stash) {
        // No sense to show this if the backup stash itself is missing.
        logger.error(`  Any lost modifications can be restored from a git stash:

    > git stash list
    stash@{0}: On master: automatic lint-staged backup
    > git stash pop stash@{0}\n`)
      }
    }

    throw error
  }
}

module.exports = runAll

module.exports.shouldSkip = {
  shouldSkipApplyModifications,
  shouldSkipRevert,
  shouldSkipCleanup
}
<commit_msg>refactor: prefer explicit default value<commit_after>'use strict'

/** @typedef {import('./index').Logger} Logger */

const chalk = require('chalk')
const Listr = require('listr')
const symbols = require('log-symbols')

const chunkFiles = require('./chunkFiles')
const generateTasks = require('./generateTasks')
const getStagedFiles = require('./getStagedFiles')
const GitWorkflow = require('./gitWorkflow')
const makeCmdTasks = require('./makeCmdTasks')
const resolveGitRepo = require('./resolveGitRepo')

const debugLog = require('debug')('lint-staged:run')

const getRenderer = ({ debug, quiet }) => {
  if (quiet) return 'silent'
  // Better support for dumb terminals: https://en.wikipedia.org/wiki/Computer_terminal#Dumb_terminals
  const isDumbTerminal = process.env.TERM === 'dumb'
  if (debug || isDumbTerminal) return 'verbose'
  return 'update'
}

const MESSAGES = {
  TASK_ERROR: 'Skipped because of errors from tasks.',
  GIT_ERROR: 'Skipped because of previous git error.'
}

const shouldSkipApplyModifications = ctx => {
  // Should be skipped in case of git errors
  if (ctx.gitError) {
    return MESSAGES.GIT_ERROR
  }
  // Should be skipped when tasks fail
  if (ctx.taskError) {
    return MESSAGES.TASK_ERROR
  }
}

const shouldSkipRevert = ctx => {
  // Should be skipped in case of unknown git errors
  if (ctx.gitError && !ctx.gitApplyEmptyCommitError && !ctx.gitRestoreUnstagedChangesError) {
    return MESSAGES.GIT_ERROR
  }
}

const shouldSkipCleanup = ctx => {
  // Should be skipped in case of unknown git errors
  if (ctx.gitError && !ctx.gitApplyEmptyCommitError && !ctx.gitRestoreUnstagedChangesError) {
    return MESSAGES.GIT_ERROR
  }
  // Should be skipped when reverting to original state fails
  if (ctx.gitRestoreOriginalStateError) {
    return MESSAGES.GIT_ERROR
  }
}

/**
 * Executes all tasks and either resolves or rejects the promise
 *
 * @param {object} options
 * @param {Object} [options.allowEmpty] - Allow empty commits when tasks revert all staged changes
 * @param {boolean | number} [options.concurrent] - The number of tasks to run concurrently, or false to run tasks serially
 * @param {Object} [options.config] - Task configuration
 * @param {Object} [options.cwd] - Current working directory
 * @param {boolean} [options.debug] - Enable debug mode
 * @param {number} [options.maxArgLength] - Maximum argument string length
 * @param {boolean} [options.quiet] - Disable lint-staged’s own console output
 * @param {boolean} [options.relative] - Pass relative filepaths to tasks
 * @param {boolean} [options.shell] - Skip parsing of tasks for better shell support
 * @param {boolean} [options.stash] - Enable the backup stash, and revert in case of errors
 * @param {Logger} logger
 * @returns {Promise}
 */
const runAll = async (
  {
    allowEmpty = false,
    concurrent = true,
    config,
    cwd = process.cwd(),
    debug = false,
    maxArgLength,
    quiet = false,
    relative = false,
    shell = false,
    stash = true
  },
  logger = console
) => {
  debugLog('Running all linter scripts')

  if (!stash) {
    logger.warn(
      `${symbols.warning} ${chalk.yellow('Skipping backup because `--no-stash` was used.')}`
    )
  }

  const { gitDir, gitConfigDir } = await resolveGitRepo(cwd)
  if (!gitDir) throw new Error('Current directory is not a git directory!')

  const files = await getStagedFiles({ cwd: gitDir })
  if (!files) throw new Error('Unable to get staged files!')
  debugLog('Loaded list of staged files in git:\n%O', files)

  // If there are no files avoid executing any lint-staged logic
  if (files.length === 0) {
    return logger.log(`${symbols.info} No staged files found.`)
  }

  const stagedFileChunks = chunkFiles({ files, gitDir, maxArgLength, relative })
  const chunkCount = stagedFileChunks.length
  if (chunkCount > 1) debugLog(`Chunked staged files into ${chunkCount} part`, chunkCount)

  // lint-staged 10 will automatically add modifications to index
  // Warn user when their command includes `git add`
  let hasDeprecatedGitAdd = false

  const listrOptions = {
    dateFormat: false,
    exitOnError: false,
    renderer: getRenderer({ debug, quiet })
  }

  const listrTasks = []

  for (const [index, files] of stagedFileChunks.entries()) {
    const chunkTasks = generateTasks({ config, cwd, gitDir, files, relative })
    const chunkListrTasks = []

    for (const task of chunkTasks) {
      const subTasks = await makeCmdTasks({
        commands: task.commands,
        files: task.fileList,
        gitDir,
        shell
      })

      hasDeprecatedGitAdd = subTasks.some(subTask => subTask.command === 'git add')

      chunkListrTasks.push({
        title: `Running tasks for ${task.pattern}`,
        task: async () =>
          new Listr(subTasks, {
            // In sub-tasks we don't want to run concurrently
            // and we want to abort on errors
            dateFormat: false,
            concurrent: false,
            exitOnError: true
          }),
        skip: () => {
          // Skip task when no files matched
          if (task.fileList.length === 0) {
            return `No staged files match ${task.pattern}`
          }
          return false
        }
      })
    }

    listrTasks.push({
      // No need to show number of task chunks when there's only one
      title:
        chunkCount > 1 ? `Running tasks (chunk ${index + 1}/${chunkCount})...` : 'Running tasks...',
      task: () => new Listr(chunkListrTasks, { ...listrOptions, concurrent }),
      skip: (ctx = {}) => {
        // Skip if the first step (backup) failed
        if (ctx.gitError) return MESSAGES.GIT_ERROR
        // Skip chunk when no every task is skipped (due to no matches)
        if (chunkListrTasks.every(task => task.skip())) return 'No tasks to run.'
        return false
      }
    })
  }

  if (hasDeprecatedGitAdd) {
    logger.warn(`${symbols.warning} ${chalk.yellow(
      `Some of your tasks use \`git add\` command. Please remove it from the config since all modifications made by tasks will be automatically added to the git commit index.`
    )}
`)
  }

  // If all of the configured tasks should be skipped
  // avoid executing any lint-staged logic
  if (listrTasks.every(task => task.skip())) {
    logger.log('No staged files match any of provided globs.')
    return 'No tasks to run.'
  }

  const git = new GitWorkflow({ allowEmpty, gitConfigDir, gitDir, stagedFileChunks })

  const runner = new Listr(
    [
      {
        title: 'Preparing...',
        task: ctx => git.prepare(ctx, stash)
      },
      {
        title: 'Hiding unstaged changes to partially staged files...',
        task: ctx => git.hideUnstagedChanges(ctx),
        enabled: ctx => ctx.hasPartiallyStagedFiles
      },
      ...listrTasks,
      {
        title: 'Applying modifications...',
        task: ctx => git.applyModifications(ctx),
        // Always apply back unstaged modifications when skipping backup
        skip: ctx => stash && shouldSkipApplyModifications(ctx)
      },
      {
        title: 'Restoring unstaged changes to partially staged files...',
        task: ctx => git.restoreUnstagedChanges(ctx),
        enabled: ctx => ctx.hasPartiallyStagedFiles,
        skip: shouldSkipApplyModifications
      },
      {
        title: 'Reverting to original state because of errors...',
        task: ctx => git.restoreOriginalState(ctx),
        enabled: ctx =>
          stash &&
          (ctx.taskError || ctx.gitApplyEmptyCommitError || ctx.gitRestoreUnstagedChangesError),
        skip: shouldSkipRevert
      },
      {
        title: 'Cleaning up...',
        task: ctx => git.cleanup(ctx),
        enabled: () => stash,
        skip: shouldSkipCleanup
      }
    ],
    listrOptions
  )

  try {
    await runner.run({})
  } catch (error) {
    if (error.context.gitApplyEmptyCommitError) {
      logger.warn(`
  ${symbols.warning} ${chalk.yellow(`lint-staged prevented an empty git commit.
    Use the --allow-empty option to continue, or check your task configuration`)}
`)
    } else if (error.context.gitError && !error.context.gitGetBackupStashError) {
      logger.error(`\n  ${symbols.error} ${chalk.red(`lint-staged failed due to a git error.`)}`)

      if (error.context.emptyGitRepo) {
        logger.error(
          `\n    The initial commit is needed for lint-staged to work.
    Please use the --no-verify flag to skip running lint-staged.`
        )
      } else if (stash) {
        // No sense to show this if the backup stash itself is missing.
        logger.error(`  Any lost modifications can be restored from a git stash:

    > git stash list
    stash@{0}: On master: automatic lint-staged backup
    > git stash pop stash@{0}\n`)
      }
    }

    throw error
  }
}

module.exports = runAll

module.exports.shouldSkip = {
  shouldSkipApplyModifications,
  shouldSkipRevert,
  shouldSkipCleanup
}
<|endoftext|>


<commit_before><commit_msg>Make go() function more reliable.<commit_after><|endoftext|>


<commit_before>var
  gulp = require('gulp'),
  sass = require('gulp-sass'),
  cached = require('gulp-cached'),
  autoprefixer = require('gulp-autoprefixer'),
  minify = require('gulp-minify-css'),
  sourcemaps = require('gulp-sourcemaps'),
  browserSync = require('browser-sync').create(),
  reload = browserSync.reload,
  webpack = require('gulp-webpack'),
  webpackServer = require('./webpack-server');

var cssPath = "lib/css/**/*.scss";
var cssOutPath = "public/assets/css";
var jsPath = "lib/js/**/*.js";
var jsOutPath = "public/assets/js";

gulp.task('webpack-hot', webpackServer);

gulp.task('browsersync', function() {
  browserSync.init({
    proxy: '0.0.0.0:8081',
    port: 8083
  });
  gulp.watch(cssPath, ['browsersync-build']);
  gulp.watch('public/**/*.html', reload);
});

gulp.task('browsersync-build', function() {
  return gulp.src(cssPath)
            .pipe(sass({errLogToConsole: true }))
            .pipe(autoprefixer({ browsers: ['last 2 versions']}))
            .pipe(gulp.dest(cssOutPath))
            .pipe(reload({stream: true}));
});

gulp.task('build_styles', function() {
  return gulp.src(cssPath)
            .pipe(sass({errLogToConsole: true }))
            .pipe(autoprefixer({ browsers: ['last 2 versions']}))
            .pipe(minify({compatibility: 'ie9'}))
            .pipe(gulp.dest(cssOutPath));
});

gulp.task('build_js', function() {
  return gulp.src(jsPath)
          .pipe(webpack(require('./webpack.config.js')))
          .pipe(gulp.dest(jsOutPath));
});

gulp.task('dev', ['browsersync', 'webpack-hot']);

gulp.task('default', ['build_js', 'build_styles']);
<commit_msg>gulpfile now caches stuff<commit_after>var
  gulp = require('gulp'),
  sass = require('gulp-sass'),
  cached = require('gulp-cached'),
  autoprefixer = require('gulp-autoprefixer'),
  minify = require('gulp-minify-css'),
  sourcemaps = require('gulp-sourcemaps'),
  browserSync = require('browser-sync').create(),
  reload = browserSync.reload,
  webpack = require('gulp-webpack'),
  webpackServer = require('./webpack-server');

var cssPath = "lib/css/**/*.scss";
var cssOutPath = "public/assets/css";
var jsPath = "lib/js/**/*.js";
var jsOutPath = "public/assets/js";

gulp.task('webpack-hot', webpackServer);

gulp.task('browsersync', function() {
  browserSync.init({
    proxy: '0.0.0.0:8081',
    port: 8083
  });
  gulp.watch(cssPath, ['browsersync-build']);
  gulp.watch('public/**/*.html', reload);
});

gulp.task('browsersync-build', function() {
  return gulp.src(cssPath)
            .pipe(sass({errLogToConsole: true }))
            .pipe(cached('styles'))
            .pipe(autoprefixer({ browsers: ['last 2 versions']}))
            .pipe(gulp.dest(cssOutPath))
            .pipe(reload({stream: true}));
});

gulp.task('build_styles', function() {
  return gulp.src(cssPath)
            .pipe(sass({errLogToConsole: true }))
            .pipe(autoprefixer({ browsers: ['last 2 versions']}))
            .pipe(minify({compatibility: 'ie9'}))
            .pipe(gulp.dest(cssOutPath));
});

gulp.task('build_js', function() {
  return gulp.src(jsPath)
          .pipe(webpack(require('./webpack.config.js')))
          .pipe(gulp.dest(jsOutPath));
});

gulp.task('dev', ['browsersync', 'webpack-hot']);

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


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import styles from 'part:@sanity/components/previews/default-style'
import MediaRender from './common/MediaRender.js'
import SvgPlaceholder from './common/SvgPlaceholder'

const PLACEHOLDER = (

    <SvgPlaceholder styles={styles} />

)

export default class DefaultPreview extends React.Component {
  static propTypes = {
    item: PropTypes.shape({
      title: PropTypes.string,
      subtitle: PropTypes.string,
      description: PropTypes.string,
      media: PropTypes.node,
      imageUrl: PropTypes.string,
      sanityImage: PropTypes.object
    }),
    assetSize: PropTypes.shape({
      width: PropTypes.number,
      height: PropTypes.number,
      fit: PropTypes.oneOf(['clip', 'crop', 'clamp'])
    }),
    emptyText: PropTypes.string,
    isPlaceholder: PropTypes.bool,
    children: PropTypes.node
  }

  static defaultProps = {
    emptyText: 'Untitled',
    assetSize: {width: 40, height: 40}
  }

  render() {
    const {item, assetSize, emptyText, children, isPlaceholder} = this.props

    const hasMedia = item.media || item.sanityImage || item.imageUrl

    if (!item || isPlaceholder) {
      return (

          {PLACEHOLDER}

      )
    }

    return (

        {
          hasMedia && (
            <div className={`${styles.media}`}>
              <MediaRender size={assetSize} item={item} />

          )
        }

            {item.title || emptyText}

          {
            item.subtitle &&

              {item.subtitle}

          }

        {
          children &&
{children}

        }

    )
  }
}
<commit_msg>[components] Fixing preview media bug<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import styles from 'part:@sanity/components/previews/default-style'
import MediaRender from './common/MediaRender.js'
import SvgPlaceholder from './common/SvgPlaceholder'

const PLACEHOLDER = (

    <SvgPlaceholder styles={styles} />

)

export default class DefaultPreview extends React.Component {
  static propTypes = {
    item: PropTypes.shape({
      title: PropTypes.string,
      subtitle: PropTypes.string,
      description: PropTypes.string,
      media: PropTypes.node,
      imageUrl: PropTypes.string,
      sanityImage: PropTypes.object
    }),
    assetSize: PropTypes.shape({
      width: PropTypes.number,
      height: PropTypes.number,
      fit: PropTypes.oneOf(['clip', 'crop', 'clamp'])
    }),
    emptyText: PropTypes.string,
    isPlaceholder: PropTypes.bool,
    children: PropTypes.node
  }

  static defaultProps = {
    emptyText: 'Untitled',
    assetSize: {width: 40, height: 40},
    item: {}
  }

  render() {
    const {item, assetSize, emptyText, children, isPlaceholder} = this.props

    if (!item || isPlaceholder) {
      return (

          {PLACEHOLDER}

      )
    }

    const hasMedia = item.media || item.sanityImage || item.imageUrl

    return (

        {
          hasMedia && (
            <div className={`${styles.media}`}>
              <MediaRender size={assetSize} item={item} />

          )
        }

            {item.title || emptyText}

          {
            item.subtitle &&

              {item.subtitle}

          }

        {
          children &&
{children}

        }

    )
  }
}
<|endoftext|>