<commit_before>const gulp = require('gulp'),
      multipipe = require('multipipe'),
      path = require('path'),
      browserify = require('browserify'),
      browserSync = require('browser-sync'),
      reload = browserSync.reload,
      source = require('vinyl-source-stream'),
      {
        autoprefixer,
        cached,
        clean,
        concat,
        jshint,
        less,
        lessReporter,
        minifyCss,
        minifyHtml,
        pipe,
        print,
        remember,
        sequence,
        sourcemaps,
        uglify,
        util
      } = require('gulp-load-plugins')();

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

gulp.task('build', sequence('clean-dist', ['js:debug', 'less:debug', 'html', 'images', 'fonts'], ['minify-css', 'minify-html', 'minify-js']));

gulp.task('dev', cb => {
  const {src} = paths;

  sequence('clean-dev', ['js:debug', 'less:debug', 'html'], 'browser-sync')(cb);

  gulp.watch(src.html, [reload]);
  gulp.watch(src.scripts, ['js:debug', reload]);
  gulp.watch(src.templates, ['js:debug', reload]);
  gulp.watch(src.less, ['less:debug'])
      .on('change', event => {
        if (event.type === 'deleted') {
          delete cached.caches['less'][event.path];
          remember.forget('less', event.path);
        }
      });
});

gulp.task('browser-sync', () => reload());

gulp.task('js:debug', ['jshint'],
  () => pipe([
    browserify({
      entries: [paths.src.app],
      debug: true
    }).bundle()
    ,source('app.js')
    ,print()
    ,gulp.dest(paths.dev.$)
  ]));

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

gulp.task('jshint',
  () => pipe([
    gulp.src(paths.src.scripts)
    ,cached('jshint')
    ,print()
    ,jshint()
    ,jshint.reporter('jshint-stylish')
    ,jshint.reporter('fail')
  ]));

gulp.task('less:debug',
  () => multipipe( // my gulp-pipe fails here because of the less().on [doesn't forward errors]
    gulp.src(paths.src.less)
    ,print()
    ,cached('less')
    ,sourcemaps.init()
    ,less()
      .on('error', lessReporter)
    ,autoprefixer()
    ,sourcemaps.write()
    ,remember('less')
    ,concat('app.css')
    ,print()
    ,gulp.dest(paths.dev.$)
    ,reload({stream: true})
  ));

gulp.task('minify-css',
  () => pipe([
    gulp.src([paths.dev.css])
    ,print()
    ,minifyCss()
    ,gulp.dest(paths.dist.$)
  ]));

gulp.task('minify-js',
  () => pipe([
    gulp.src([paths.dev.app])
    ,print()
    ,uglify()
    ,gulp.dest(paths.dist.$)
  ]));

gulp.task('minify-html',
  () => pipe([
    gulp.src([paths.dev.html])
    ,print()
    ,minifyHtml()
    ,gulp.dest(paths.dist.$)
  ]));

gulp.task('html',
  () => pipe([
    gulp.src(paths.src.html)
    ,print()
    ,gulp.dest(paths.dev.$)
  ]));

gulp.task('browser-sync',
  () => browserSync({
    server: {
      baseDir: paths.dev.$
    }
  }));

gulp.task('images');

gulp.task('fonts');

gulp.task('clean-dev',
  () => pipe([
    gulp.src(paths.dev.$, {read: false})
    ,clean()
  ]));

gulp.task('clean-dist',
  () => pipe([
    gulp.src(paths.dist.$, {read: false})
    ,clean()
  ]));

const paths = {
  src: {
    $: './src',
    app: ['./src/app.js'],
    less: ['./src/**/*.less'],
    html: ['./src/index.html'],
    scripts: ['./src/**/*.js'],
    templates: ['./src/modules/**/*.html']
  },
  dist: {
    $: './.dist',
    app: './.dist/app.js',
    css: './.dist/app.css',
    html: './.dist/index.html'
  },
  dev: {
    $: './.dev',
    app: './.dev/app.js',
    css: './.dev/app.css',
    html: './.dev/index.html'
  }
};<commit_msg>Fix to listen for new files.<commit_after>const gulp = require('gulp'),
      multipipe = require('multipipe'),
      path = require('path'),
      browserify = require('browserify'),
      browserSync = require('browser-sync'),
      reload = browserSync.reload,
      source = require('vinyl-source-stream'),
      {
        autoprefixer,
        cached,
        clean,
        concat,
        jshint,
        less,
        lessReporter,
        minifyCss,
        minifyHtml,
        pipe,
        print,
        remember,
        sequence,
        sourcemaps,
        uglify,
        util
      } = require('gulp-load-plugins')();

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

gulp.task('build', sequence('clean-dist', ['js:debug', 'less:debug', 'html', 'images', 'fonts'], ['minify-css', 'minify-html', 'minify-js']));

gulp.task('dev', cb => {
  const {src} = paths;

  sequence('clean-dev', ['js:debug', 'less:debug', 'html'], 'browser-sync')(cb);

  gulp.watch(src.html, [reload]);
  gulp.watch(src.scripts, ['js:debug', reload]);
  gulp.watch(src.templates, ['js:debug', reload]);
  gulp.watch(src.less, ['less:debug'])
      .on('change', event => {
        if (event.type === 'deleted') {
          delete cached.caches['less'][event.path];
          remember.forget('less', event.path);
        }
      });
});

gulp.task('browser-sync', () => reload());

gulp.task('js:debug', ['jshint'],
  () => pipe([
    browserify({
      entries: [paths.src.app],
      debug: true
    }).bundle()
    ,source('app.js')
    ,print()
    ,gulp.dest(paths.dev.$)
  ]));

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

gulp.task('jshint',
  () => pipe([
    gulp.src(paths.src.scripts)
    ,cached('jshint')
    ,print()
    ,jshint()
    ,jshint.reporter('jshint-stylish')
    ,jshint.reporter('fail')
  ]));

gulp.task('less:debug',
  () => multipipe( // my gulp-pipe fails here because of the less().on [doesn't forward errors]
    gulp.src(paths.src.less)
    ,cached('less')
    ,print()
    ,sourcemaps.init()
    ,less()
      .on('error', lessReporter)
    ,autoprefixer()
    ,sourcemaps.write()
    ,remember('less')
    ,concat('app.css')
    ,print()
    ,gulp.dest(paths.dev.$)
    ,reload({stream: true})
  ));

gulp.task('minify-css',
  () => pipe([
    gulp.src([paths.dev.css])
    ,print()
    ,minifyCss()
    ,gulp.dest(paths.dist.$)
  ]));

gulp.task('minify-js',
  () => pipe([
    gulp.src([paths.dev.app])
    ,print()
    ,uglify()
    ,gulp.dest(paths.dist.$)
  ]));

gulp.task('minify-html',
  () => pipe([
    gulp.src([paths.dev.html])
    ,print()
    ,minifyHtml()
    ,gulp.dest(paths.dist.$)
  ]));

gulp.task('html',
  () => pipe([
    gulp.src(paths.src.html)
    ,print()
    ,gulp.dest(paths.dev.$)
  ]));

gulp.task('browser-sync',
  () => browserSync({
    server: {
      baseDir: paths.dev.$
    }
  }));

gulp.task('images');

gulp.task('fonts');

gulp.task('clean-dev',
  () => pipe([
    gulp.src(paths.dev.$, {read: false})
    ,clean()
  ]));

gulp.task('clean-dist',
  () => pipe([
    gulp.src(paths.dist.$, {read: false})
    ,clean()
  ]));

const paths = {
  src: {
    $: './src',
    app: ['./src/app.js'],
    less: ['src/**/*.less'],
    html: ['./src/index.html'],
    scripts: ['src/**/*.js'],
    templates: ['src/modules/**/template.html']
  },
  dist: {
    $: './.dist',
    app: './.dist/app.js',
    css: './.dist/app.css',
    html: './.dist/index.html'
  },
  dev: {
    $: './.dev',
    app: './.dev/app.js',
    css: './.dev/app.css',
    html: './.dev/index.html'
  }
};<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.comics.v2',
  name: 'DataSummaryCard',
  extends: 'foam.u2.View',

  documentation: `
    A configurable view to to render a card with
    configurable contents and rich choice view dropdowns
  `,

  css:`
  `,

  requires: [
    'foam.u2.layout.Cols',
    'foam.u2.layout.Rows',
    'foam.u2.ControllerMode',
    'foam.u2.borders.CardBorder'
  ],
  exports: [
    'controllerMode'
  ],
  properties: [
    {
      class: 'FObjectProperty',
      name: 'data'
    },
    {
      name: 'controllerMode',
      factory: function() {
        return this.ControllerMode.VIEW;
      }
    },
    {
      class: 'FObjectArray',
      of: 'Reference',
      name: 'choices',
      factory: function() {
        return [];
      }
    },
    {
      class: 'foam.u2.ViewSpec',
      name: 'content',
    }
  ],

  methods: [
    function initE() {
      this.SUPER();
      this
        .addClass(this.myClass())
        .start(this.CardBorder)
          .start(this.Rows)
            .start(this.Cols).addClass(this.myClass('card-header'))
              .start().add().addClass().end()
              .forEach()
            .end()
          .end()
        .end()
    }
  ]
});
<commit_msg>Added changes RE kevin's comments<commit_after>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.comics.v2',
  name: 'DataSummaryCard',
  extends: 'foam.u2.View',

  documentation: `
    TODO: WORK IN PROGRESS:
    A configurable view to to render a card with
    configurable contents and rich choice view dropdowns
  `,

  css:`
  `,

  requires: [
    'foam.u2.layout.Cols',
    'foam.u2.layout.Rows',
    'foam.u2.ControllerMode',
    'foam.u2.borders.CardBorder'
  ],
  exports: [
    'controllerMode'
  ],
  properties: [
    {
      class: 'FObjectProperty',
      name: 'data'
    },
    {
      name: 'controllerMode',
      factory: function() {
        return this.ControllerMode.VIEW;
      }
    },
    {
      class: 'FObjectArray',
      of: 'Reference',
      name: 'choices',
    },
    {
      class: 'foam.u2.ViewSpec',
      name: 'content',
    }
  ],

  methods: [
    function initE() {
      this.SUPER();
      this
        .addClass(this.myClass())
        .start(this.CardBorder)
          .start(this.Rows)
            .start(this.Cols).addClass(this.myClass('card-header'))
              .start().add().addClass().end()
              .forEach()
            .end()
          .end()
        .end();
    }
  ]
});
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var gulp = require('gulp');
var replace = require('gulp-replace-task');
var fs = require('fs');
var g = require('gulp-load-plugins')({lazy: false});
var noop = g.util.noop;
var es = require('event-stream');
var Queue = require('streamqueue');
var lazypipe = require('lazypipe');
var stylish = require('jshint-stylish');
var bower = require('./bower');
var mainBowerFiles = require('main-bower-files');
var historyApiFallback = require('connect-history-api-fallback');
var isWatching = false;

var htmlminOpts = {
  removeComments: true,
  collapseWhitespace: true,
  removeEmptyAttributes: false,
  collapseBooleanAttributes: true,
  removeRedundantAttributes: true
};

var KONGA_BACKEND_URL = process.env.KONGA_BACKEND_URL || (process.env.HOST + ":" + process.env.PORT)

var settings;

// Try to read frontend configuration file, fallback to default file
try {
  settings = JSON.parse(fs.readFileSync('./config/config.json', 'utf8'));
} catch (error) {
  settings = JSON.parse(fs.readFileSync('./config/config_example.json', 'utf8'));
}

// Overwrite port if explicitly set in command
var argv = require('minimist')(process.argv.slice(2));
if(argv.p) {
    settings.frontend.ports.production = argv.p
    settings.frontend.ports.development = argv.p
}

/**
 * JS Hint
 */
gulp.task('jshint', function() {
  return gulp.src([
        './gulpfile.js',
        './src/app/**/*.js'
      ])
      .pipe(g.cached('jshint'))
      .pipe(jshint('./.jshintrc'))
      .pipe(livereload());
});

/**
 * CSS
 */
gulp.task('clean-css', function() {
  return gulp.src('./.tmp/css').pipe(g.clean());
});

gulp.task('styles', ['clean-css'], function() {
  return gulp.src([
        './src/app/**/*.scss',
        '!./src/app/**/_*.scss'
      ])
      .pipe(g.sass())
      .pipe(gulp.dest('./.tmp/css/'))
      .pipe(g.cached('built-css'))
      .pipe(livereload());
});

gulp.task('styles-dist', ['styles'], function() {
  return cssFiles().pipe(dist('css', bower.name));
});

gulp.task('csslint', ['styles'], function() {
  return cssFiles()
      .pipe(g.cached('csslint'))
      .pipe(g.csslint('./.csslintrc'))
      .pipe(g.csslint.reporter())
      ;
});

/**
 * Scripts
 */
gulp.task('scripts-dist', ['templates-dist'], function() {
  return appFiles().pipe(dist('js', bower.name, {ngAnnotate: true}));
});

/**
 * Templates
 */
gulp.task('templates', function() {
  return templateFiles().pipe(buildTemplates());
});

gulp.task('templates-dist', function() {
  return templateFiles({min: true}).pipe(buildTemplates());
});

/**
 * Vendors
 */
gulp.task('vendors', function() {
  var bowerStream = gulp.src(mainBowerFiles());

  return es.merge(
      bowerStream.pipe(g.filter('**/*.css')).pipe(dist('css', 'vendors')),
      bowerStream.pipe(g.filter('**/*.js')).pipe(dist('js', 'vendors'))
  );
});

/**
 * Index
 */
gulp.task('index', index);
gulp.task('build-all', ['styles', 'templates'], index);

function index() {
  var opt = {read: false};

  return gulp.src('./src/app/index.html')
      .pipe(g.inject(gulp.src(mainBowerFiles(opt)), {ignorePath: 'bower_components', starttag: '<!-- inject:vendor:{{ext}} -->'}))
      .pipe(g.inject(es.merge(appFiles(), cssFiles(opt)), {ignorePath: ['.tmp', 'src/app']}))
      .pipe(g.embedlr())
      .pipe(replace({
        patterns: [
            {
                match: 'backendUrl',
                replacement: KONGA_BACKEND_URL || settings.backendUrl
            },
            {
                match: 'enableLogs',
                replacement: process.env.KONGA_FRONTEND_LOGS || true
            }
        ]
      }))
      .pipe(gulp.dest('./.tmp/'))
      .pipe(livereload())
      ;
}

/**
 * Assets
 */
gulp.task('assets', function() {
  return gulp.src('./src/app/assets/**')
      .pipe(gulp.dest('./dist/assets'))
      ;
});

/**
 * Partials
 */
gulp.task('partials', function() {
  return gulp.src('./src/app/partials/**')
      .pipe(gulp.dest('./dist/partials'))
      ;
});

/**
 * Fonts
 */
//gulp.task('fonts', function() {
//  return gulp.src('./bower_components/fontawesome/fonts/**')
//      .pipe(gulp.dest('./dist/fonts'))
//      ;
//});

/**
 * Dist
 */
gulp.task('dist', ['vendors', 'assets', 'styles-dist', 'scripts-dist'], function() {
  return gulp.src('./src/app/index.html')
      .pipe(g.inject(gulp.src('./dist/vendors.min.{js,css}'), {
        ignorePath: 'dist',
        starttag: '<!-- inject:vendor:{{ext}} -->',
          addRootSlash:false
      }))
      .pipe(g.inject(gulp.src('./dist/' + bower.name + '.min.{js,css}'), {ignorePath: 'dist',addRootSlash:false}))
      .pipe(replace({
        patterns: [
            {
                match: 'backendUrl',
                replacement: KONGA_BACKEND_URL || settings.backendUrl
            },
            {
                match: 'enableLogs',
                replacement: process.env.KONGA_FRONTEND_LOGS || false
            }
        ]
      }))
      .pipe(g.htmlmin(htmlminOpts))
      .pipe(gulp.dest('./dist/'))
      ;
});

/**
 * Static file server
 */
gulp.task('statics', g.serve({
  port: process.env.KONGA_FRONTEND_PORT || settings.frontend.ports.development,
  root: ['./.tmp', './src/app', './bower_components'],
  middleware: historyApiFallback({})
}));

/**
 * Production file server, note remember to run 'gulp dist' first!
 */
gulp.task('production',g.serve({
    port: process.env.KONGA_FRONTEND_PORT || settings.frontend.ports.production,
    root: ['./dist'],
    middleware: historyApiFallback({})
}));

/**
 * Watch
 */
gulp.task('serve', ['watch']);

gulp.task('watch', ['statics', 'default'], function() {
  isWatching = true;

  // Initiate livereload server:
  g.livereload({
    start: true
  });

  gulp.watch('./src/app/**/*.js', ['jshint']).on('change', function(evt) {
    if (evt.type !== 'changed') {
      gulp.start('index');
    }
  });

  gulp.watch('./src/app/index.html', ['index']);
  gulp.watch(['./src/app/**/*.html', '!./src/app/index.html'], ['templates']);
  gulp.watch(['./src/app/**/*.scss'], ['csslint']).on('change', function(evt) {
    if (evt.type !== 'changed') {
      gulp.start('index');
    }
  });
});

/**
 * Default task
 */
gulp.task('default', ['lint', 'build-all']);

/**
 * Lint everything
 */
gulp.task('lint', ['jshint', 'csslint']);

/**
 * Test
 */
gulp.task('test', ['templates'], function() {
  return testFiles()
      .pipe(g.karma({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
      }))
      ;
});

/**
 * Inject all files for tests into karma.conf.js
 * to be able to run `karma` without gulp.
 */
gulp.task('karma-conf', ['templates'], function() {
  return gulp.src('./karma.conf.js')
      .pipe(g.inject(testFiles(), {
        starttag: 'files: [',
        endtag: ']',
        addRootSlash: false,
        transform: function(filepath, file, i, length) {
          return '  \'' + filepath + '\'' + (i + 1 < length ? ',' : '');
        }
      }))
      .pipe(gulp.dest('./'))
      ;
});

/**
 * Test files
 */
function testFiles() {
  return new Queue({objectMode: true})
      .Queue(gulp.src(mainBowerFiles()).pipe(g.filter('**/*.js')))
      .Queue(gulp.src('./bower_components/angular-mocks/angular-mocks.js'))
      .Queue(appFiles())
      .Queue(gulp.src('./src/app/**/*_test.js'))
      .done()
      ;
}

/**
 * All CSS files as a stream
 */
function cssFiles(opt) {
  return gulp.src('./.tmp/css/**/*.css', opt);
}

/**
 * All AngularJS application files as a stream
 */
function appFiles() {
  var files = [
    './.tmp/' + bower.name + '-templates.js',
    './src/app/**/*.js',
    '!./src/app/**/*_test.js'
  ];

  return gulp.src(files)
      .pipe(g.angularFilesort())
      ;
}

/**
 * All AngularJS templates/partials as a stream
 */
function templateFiles(opt) {
  return gulp.src([
        './src/app/**/*.html',
        './src/app/**/**/*.html',
        './src/app/**/**/**/*.html',
        '!./src/app/index.html'], opt)
      .pipe(opt && opt.min ? g.htmlmin(htmlminOpts) : noop())
      ;
}

/**
 * Build AngularJS templates/partials
 */
function buildTemplates() {
  return lazypipe()
      .pipe(g.ngHtml2js, {
        moduleName: bower.name + '-templates',
        prefix: '/' + bower.name + '/',
        stripPrefix: '/src/app'
      })
      .pipe(g.concat, bower.name + '-templates.js')
      .pipe(gulp.dest, './.tmp')
      .pipe(livereload)()
      ;
}

/**
 * Concat, rename, minify
 *
 * @param {String} ext
 * @param {String} name
 * @param {Object} opt
 */
function dist(ext, name, opt) {
  opt = opt || {};

  return lazypipe()
      .pipe(g.concat, name + '.' + ext)
      .pipe(gulp.dest, './dist')
      .pipe(opt.ngAnnotate ? g.ngAnnotate : noop)
      .pipe(opt.ngAnnotate ? g.rename : noop, name + '.annotated.' + ext)
      .pipe(opt.ngAnnotate ? gulp.dest : noop, './dist')
      .pipe(ext === 'js' ? g.uglify : g.minifyCss,ext === 'js' ? {} : {processImport: false})
      .pipe(g.rename, name + '.min.' + ext)
      .pipe(gulp.dest, './dist')()
      ;
}

/**
 * Livereload (or noop if not run by watch)
 */
function livereload() {
  return lazypipe()
      .pipe(isWatching ? g.livereload : noop)()
      ;
}

/**
 * Jshint with stylish reporter
 */
function jshint(jshintfile) {
  // Read JSHint settings, for some reason jshint-stylish won't work on initial load of files
  var jshintSettings = JSON.parse(fs.readFileSync(jshintfile, 'utf8'));

  return lazypipe()
      .pipe(g.jshint, jshintSettings)
      .pipe(g.jshint.reporter, stylish)()
      ;
}<commit_msg>Introduced KONGA_BACKEND_URL env var<commit_after>/* jshint node: true */
'use strict';

var gulp = require('gulp');
var replace = require('gulp-replace-task');
var fs = require('fs');
var g = require('gulp-load-plugins')({lazy: false});
var noop = g.util.noop;
var es = require('event-stream');
var Queue = require('streamqueue');
var lazypipe = require('lazypipe');
var stylish = require('jshint-stylish');
var bower = require('./bower');
var mainBowerFiles = require('main-bower-files');
var historyApiFallback = require('connect-history-api-fallback');
var isWatching = false;

var htmlminOpts = {
  removeComments: true,
  collapseWhitespace: true,
  removeEmptyAttributes: false,
  collapseBooleanAttributes: true,
  removeRedundantAttributes: true
};

var settings;

// Try to read frontend configuration file, fallback to default file
try {
  settings = JSON.parse(fs.readFileSync('./config/config.json', 'utf8'));
} catch (error) {
  settings = JSON.parse(fs.readFileSync('./config/config_example.json', 'utf8'));
}

var KONGA_BACKEND_URL = process.env.KONGA_BACKEND_URL || settings.backendUrl

// Overwrite port if explicitly set in command
var argv = require('minimist')(process.argv.slice(2));
if(argv.p) {
    settings.frontend.ports.production = argv.p
    settings.frontend.ports.development = argv.p
}

/**
 * JS Hint
 */
gulp.task('jshint', function() {
  return gulp.src([
        './gulpfile.js',
        './src/app/**/*.js'
      ])
      .pipe(g.cached('jshint'))
      .pipe(jshint('./.jshintrc'))
      .pipe(livereload());
});

/**
 * CSS
 */
gulp.task('clean-css', function() {
  return gulp.src('./.tmp/css').pipe(g.clean());
});

gulp.task('styles', ['clean-css'], function() {
  return gulp.src([
        './src/app/**/*.scss',
        '!./src/app/**/_*.scss'
      ])
      .pipe(g.sass())
      .pipe(gulp.dest('./.tmp/css/'))
      .pipe(g.cached('built-css'))
      .pipe(livereload());
});

gulp.task('styles-dist', ['styles'], function() {
  return cssFiles().pipe(dist('css', bower.name));
});

gulp.task('csslint', ['styles'], function() {
  return cssFiles()
      .pipe(g.cached('csslint'))
      .pipe(g.csslint('./.csslintrc'))
      .pipe(g.csslint.reporter())
      ;
});

/**
 * Scripts
 */
gulp.task('scripts-dist', ['templates-dist'], function() {
  return appFiles().pipe(dist('js', bower.name, {ngAnnotate: true}));
});

/**
 * Templates
 */
gulp.task('templates', function() {
  return templateFiles().pipe(buildTemplates());
});

gulp.task('templates-dist', function() {
  return templateFiles({min: true}).pipe(buildTemplates());
});

/**
 * Vendors
 */
gulp.task('vendors', function() {
  var bowerStream = gulp.src(mainBowerFiles());

  return es.merge(
      bowerStream.pipe(g.filter('**/*.css')).pipe(dist('css', 'vendors')),
      bowerStream.pipe(g.filter('**/*.js')).pipe(dist('js', 'vendors'))
  );
});

/**
 * Index
 */
gulp.task('index', index);
gulp.task('build-all', ['styles', 'templates'], index);

function index() {
  var opt = {read: false};

  return gulp.src('./src/app/index.html')
      .pipe(g.inject(gulp.src(mainBowerFiles(opt)), {ignorePath: 'bower_components', starttag: '<!-- inject:vendor:{{ext}} -->'}))
      .pipe(g.inject(es.merge(appFiles(), cssFiles(opt)), {ignorePath: ['.tmp', 'src/app']}))
      .pipe(g.embedlr())
      .pipe(replace({
        patterns: [
            {
                match: 'backendUrl',
                replacement: KONGA_BACKEND_URL || settings.backendUrl
            },
            {
                match: 'enableLogs',
                replacement: process.env.KONGA_FRONTEND_LOGS || true
            }
        ]
      }))
      .pipe(gulp.dest('./.tmp/'))
      .pipe(livereload())
      ;
}

/**
 * Assets
 */
gulp.task('assets', function() {
  return gulp.src('./src/app/assets/**')
      .pipe(gulp.dest('./dist/assets'))
      ;
});

/**
 * Partials
 */
gulp.task('partials', function() {
  return gulp.src('./src/app/partials/**')
      .pipe(gulp.dest('./dist/partials'))
      ;
});

/**
 * Fonts
 */
//gulp.task('fonts', function() {
//  return gulp.src('./bower_components/fontawesome/fonts/**')
//      .pipe(gulp.dest('./dist/fonts'))
//      ;
//});

/**
 * Dist
 */
gulp.task('dist', ['vendors', 'assets', 'styles-dist', 'scripts-dist'], function() {
  return gulp.src('./src/app/index.html')
      .pipe(g.inject(gulp.src('./dist/vendors.min.{js,css}'), {
        ignorePath: 'dist',
        starttag: '<!-- inject:vendor:{{ext}} -->',
          addRootSlash:false
      }))
      .pipe(g.inject(gulp.src('./dist/' + bower.name + '.min.{js,css}'), {ignorePath: 'dist',addRootSlash:false}))
      .pipe(replace({
        patterns: [
            {
                match: 'backendUrl',
                replacement: KONGA_BACKEND_URL || settings.backendUrl
            },
            {
                match: 'enableLogs',
                replacement: process.env.KONGA_FRONTEND_LOGS || false
            }
        ]
      }))
      .pipe(g.htmlmin(htmlminOpts))
      .pipe(gulp.dest('./dist/'))
      ;
});

/**
 * Static file server
 */
gulp.task('statics', g.serve({
  port: process.env.KONGA_FRONTEND_PORT || settings.frontend.ports.development,
  root: ['./.tmp', './src/app', './bower_components'],
  middleware: historyApiFallback({})
}));

/**
 * Production file server, note remember to run 'gulp dist' first!
 */
gulp.task('production',g.serve({
    port: process.env.KONGA_FRONTEND_PORT || settings.frontend.ports.production,
    root: ['./dist'],
    middleware: historyApiFallback({})
}));

/**
 * Watch
 */
gulp.task('serve', ['watch']);

gulp.task('watch', ['statics', 'default'], function() {
  isWatching = true;

  // Initiate livereload server:
  g.livereload({
    start: true
  });

  gulp.watch('./src/app/**/*.js', ['jshint']).on('change', function(evt) {
    if (evt.type !== 'changed') {
      gulp.start('index');
    }
  });

  gulp.watch('./src/app/index.html', ['index']);
  gulp.watch(['./src/app/**/*.html', '!./src/app/index.html'], ['templates']);
  gulp.watch(['./src/app/**/*.scss'], ['csslint']).on('change', function(evt) {
    if (evt.type !== 'changed') {
      gulp.start('index');
    }
  });
});

/**
 * Default task
 */
gulp.task('default', ['lint', 'build-all']);

/**
 * Lint everything
 */
gulp.task('lint', ['jshint', 'csslint']);

/**
 * Test
 */
gulp.task('test', ['templates'], function() {
  return testFiles()
      .pipe(g.karma({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
      }))
      ;
});

/**
 * Inject all files for tests into karma.conf.js
 * to be able to run `karma` without gulp.
 */
gulp.task('karma-conf', ['templates'], function() {
  return gulp.src('./karma.conf.js')
      .pipe(g.inject(testFiles(), {
        starttag: 'files: [',
        endtag: ']',
        addRootSlash: false,
        transform: function(filepath, file, i, length) {
          return '  \'' + filepath + '\'' + (i + 1 < length ? ',' : '');
        }
      }))
      .pipe(gulp.dest('./'))
      ;
});

/**
 * Test files
 */
function testFiles() {
  return new Queue({objectMode: true})
      .Queue(gulp.src(mainBowerFiles()).pipe(g.filter('**/*.js')))
      .Queue(gulp.src('./bower_components/angular-mocks/angular-mocks.js'))
      .Queue(appFiles())
      .Queue(gulp.src('./src/app/**/*_test.js'))
      .done()
      ;
}

/**
 * All CSS files as a stream
 */
function cssFiles(opt) {
  return gulp.src('./.tmp/css/**/*.css', opt);
}

/**
 * All AngularJS application files as a stream
 */
function appFiles() {
  var files = [
    './.tmp/' + bower.name + '-templates.js',
    './src/app/**/*.js',
    '!./src/app/**/*_test.js'
  ];

  return gulp.src(files)
      .pipe(g.angularFilesort())
      ;
}

/**
 * All AngularJS templates/partials as a stream
 */
function templateFiles(opt) {
  return gulp.src([
        './src/app/**/*.html',
        './src/app/**/**/*.html',
        './src/app/**/**/**/*.html',
        '!./src/app/index.html'], opt)
      .pipe(opt && opt.min ? g.htmlmin(htmlminOpts) : noop())
      ;
}

/**
 * Build AngularJS templates/partials
 */
function buildTemplates() {
  return lazypipe()
      .pipe(g.ngHtml2js, {
        moduleName: bower.name + '-templates',
        prefix: '/' + bower.name + '/',
        stripPrefix: '/src/app'
      })
      .pipe(g.concat, bower.name + '-templates.js')
      .pipe(gulp.dest, './.tmp')
      .pipe(livereload)()
      ;
}

/**
 * Concat, rename, minify
 *
 * @param {String} ext
 * @param {String} name
 * @param {Object} opt
 */
function dist(ext, name, opt) {
  opt = opt || {};

  return lazypipe()
      .pipe(g.concat, name + '.' + ext)
      .pipe(gulp.dest, './dist')
      .pipe(opt.ngAnnotate ? g.ngAnnotate : noop)
      .pipe(opt.ngAnnotate ? g.rename : noop, name + '.annotated.' + ext)
      .pipe(opt.ngAnnotate ? gulp.dest : noop, './dist')
      .pipe(ext === 'js' ? g.uglify : g.minifyCss,ext === 'js' ? {} : {processImport: false})
      .pipe(g.rename, name + '.min.' + ext)
      .pipe(gulp.dest, './dist')()
      ;
}

/**
 * Livereload (or noop if not run by watch)
 */
function livereload() {
  return lazypipe()
      .pipe(isWatching ? g.livereload : noop)()
      ;
}

/**
 * Jshint with stylish reporter
 */
function jshint(jshintfile) {
  // Read JSHint settings, for some reason jshint-stylish won't work on initial load of files
  var jshintSettings = JSON.parse(fs.readFileSync(jshintfile, 'utf8'));

  return lazypipe()
      .pipe(g.jshint, jshintSettings)
      .pipe(g.jshint.reporter, stylish)()
      ;
}<|endoftext|>


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

// Add move function
Array.prototype.move = function (from, to) {
  this.splice(to, 0, this.splice(from, 1)[0]);
};

/*************************
* Window manager module
**************************/

var windowMgr = (function(){
  $(document).on('click', '#closeBtn', function(){
    ipc.sendSync('close-window-msg');
  });

  $(document).on('click', '#minimizeBtn', function(){
    ipc.sendSync('minimize-window-msg');
  });

  $(document).on('submit', '#editCheatForm', function(event){
    $('#editCheatModal').modal('hide');
  });

  $('#cheatsUl').delegate('a.cheat-action-edit', 'click', function(event){
    $('#editCheatModal').modal('show');
  });

  ipc.on('new-cheat-window-msg', function(event){
    $('#addBtn').click();
  });

  $('.modal').on('hidden.bs.modal', function(){
    $(this).find('#editCheatForm')[0].reset();
  });

  var remote = require('remote');
  var Menu = remote.require('menu');
  var MenuItem = remote.require('menu-item');

  var menu = new Menu();
  menu.append(new MenuItem({ label: 'Cut', selector: 'cut:', accelerator: 'CmdOrCtrl+X' }));
  menu.append(new MenuItem({ label: 'Copy', selector: 'copy:', accelerator: 'CmdOrCtrl+C' }));
  menu.append(new MenuItem({ label: 'Paste', selector: 'paste:', accelerator: 'CmdOrCtrl+V' }));
  menu.append(new MenuItem({ label: 'Select All', selector: 'selectAll:', accelerator: 'CmdOrCtrl+A' }));

  window.addEventListener('contextmenu', function (e) {
    e.preventDefault();
    menu.popup(remote.getCurrentWindow());
  }, false);

})();

/*************************
* Cheat manager module
**************************/

(function(){
  // initialize
  var cheatList = ipc.sendSync('load-cheats-msg');

  //cache DOM
  var $editCheatForm = $('#editCheatForm');
  var $cheatsView = $('#cheatsView');
  var $cheatsUl = $('#cheatsUl');
  var $tagListUl = $('#tagList');
  var cheatListTemplate = $cheatsView.find('#cheats-template').html();
  var tagListTemplate = $('#tags-template').html();

  // bind events
  $editCheatForm.on('submit', saveEdits);
  $cheatsUl.delegate('a.cheat-action-edit', 'click', loadCheatToEditForm);
  $cheatsUl.delegate('a.cheat-action-delete', 'click', deleteCheat);
  $tagListUl.delegate('a', 'click', filterCheatList);

  _render();

  function _render () {
    // render cheats
    $cheatsUl.html(Mustache.render(cheatListTemplate, cheatList));
    _enableDragAndDrop();

    // render tags
    var tagList = [];
    cheatList.cheats.forEach(function(cheat){
      if (cheat.tags)
      {
        cheat.tags.forEach(function(tag){
          if (tagList.indexOf(tag) === -1)
            tagList.push(tag);
        });
      }
    });
    $tagListUl.html(Mustache.render(tagListTemplate, {"tagList":tagList}));

    _renderTagSelection();
  }

  function _enableDragAndDrop()
  {
    $('.sortable').sortable({
      forcePlaceholderSize: true,
      handle: '.sort-handle'
    })
    .bind('sortupdate', function(e, ui) {
      cheatList.cheats.move(ui.oldElementIndex, ui.elementIndex);
      ipc.send('reorder-cheatlist-msg', {from: ui.oldElementIndex, to: ui.elementIndex});
    });
  }

  function _renderTagSelection()
  {
    $tagListUl.find('li').each(function(i, li){
      var tagItem = $(li);
      if (!tagItem.hasClass('selectedTag'))
        tagItem.find('span').css('visibility', 'hidden');
      else
        tagItem.find('span').css('visibility', 'visible');
    });
  }

  function loadCheatToEditForm(event) {
    var $cheat = $(event.target).closest('li');

    $("#inputId").val($cheat.find('.panel-body .cheatId').text().trim());
    $("#inputTitle").val($cheat.find('.panel-body .cheatTitle').text());
    $("#inputNotes").val($cheat.find('.panel-body .cheatNotes').text().trim());
    $("#inputCode").val($cheat.find('.panel-body .cheatCode').text());

    var tagString = $cheat.find('.panel-body .cheatTags').map(function () {
          return $(this).text();
      }).get().join();
    $("#inputTags").val(tagString);
  }

  function saveEdits(event) {
    var $cheatId = $("#inputId").val().trim();
    var sep = /\s*,\s*/;

    if ($cheatId === "") //We have a brand new cheat
    {
      var newCheat = {
        'id': Date.now(),
        'title': $("#inputTitle").val(),
        'notes' : $("#inputNotes").val(),
        'code' : $("#inputCode").val(),
        'tags' : $("#inputTags").val().split(sep)
      };

      if (newCheat.tags.length === 1 && newCheat.tags[0] === '') // no tags
        newCheat.tags = null;

      cheatList.cheats.unshift(newCheat);
      ipc.send('add-cheat-msg', newCheat);
    }
    else // We are editing an existing cheat
    {
      var editedCheat = {
        'id': $cheatId,
        'title': $("#inputTitle").val(),
        'notes' : $("#inputNotes").val(),
        'code' : $("#inputCode").val(),
        'tags' : $("#inputTags").val().split(sep)
      };

      if (editedCheat.tags.length === 1 && editedCheat.tags[0] === '') // no tags
        editedCheat.tags = null;

      var cheatSearchResult = $.grep(cheatList.cheats, function(c){ return c.id == $cheatId; });
      if (cheatSearchResult.length > 0)
      {
        cheatSearchResult[0].title = editedCheat.title;
        cheatSearchResult[0].notes = editedCheat.notes;
        cheatSearchResult[0].code = editedCheat.code;
        cheatSearchResult[0].tags = editedCheat.tags;
      }
      ipc.send('edit-cheat-msg', editedCheat);
    }

    event.preventDefault();
    _render();
  }

  function deleteCheat(event) {
    var cont = confirm("Confirm deletion");
    if (cont === false)
      return;

    var $cheat = $(event.target).closest('li');
    var cheatId = $cheat.find('.panel-body .cheatId').text().trim();

    cheatList.cheats = cheatList.cheats.filter(function (cheat) {
                          return cheat.id != cheatId;
                         });

    ipc.send('delete-cheat-msg', cheatId);

    _render();
  }

  function filterCheatList(event) {

    $tagListUl.find('li').removeClass('selectedTag');
    var $selectedTag = $(event.target).closest('li');
    $selectedTag.addClass('selectedTag');
    _renderTagSelection();

    var selectedTagText = $selectedTag.text();
    if (selectedTagText === 'All')
    {
      $cheatsUl.find('li').each(function (index, listItem){
        $(listItem).show();
      });
    }
    else {
      $cheatsUl.find('li').each(function (index, listItem){
        $tagSpans = $(listItem).find('span.cheatTags');
        if (!$tagSpans.text().includes(selectedTagText))
        {
          $(listItem).hide();
        }
        else {
          $(listItem).show();
        }
      });
    }

  }

})();
<commit_msg>make context menu crossplatform and add refresh<commit_after>var ipc = require('ipc');

// Add move function
Array.prototype.move = function (from, to) {
  this.splice(to, 0, this.splice(from, 1)[0]);
};

/*************************
* Window manager module
**************************/

var windowMgr = (function(){
  $(document).on('click', '#closeBtn', function(){
    ipc.sendSync('close-window-msg');
  });

  $(document).on('click', '#minimizeBtn', function(){
    ipc.sendSync('minimize-window-msg');
  });

  $(document).on('submit', '#editCheatForm', function(event){
    $('#editCheatModal').modal('hide');
  });

  $('#cheatsUl').delegate('a.cheat-action-edit', 'click', function(event){
    $('#editCheatModal').modal('show');
  });

  ipc.on('new-cheat-window-msg', function(event){
    $('#addBtn').click();
  });

  $('.modal').on('hidden.bs.modal', function(){
    $(this).find('#editCheatForm')[0].reset();
  });

  var remote = require('remote');
  var Menu = remote.require('menu');
  var MenuItem = remote.require('menu-item');

  var menu = new Menu();
  if (navigator.appVersion.indexOf("Mac")!=-1)
  {
    menu.append(new MenuItem({ label: 'Cut', selector: 'cut:', accelerator: 'CmdOrCtrl+X' }));
    menu.append(new MenuItem({ label: 'Copy', selector: 'copy:', accelerator: 'CmdOrCtrl+C' }));
    menu.append(new MenuItem({ label: 'Paste', selector: 'paste:', accelerator: 'CmdOrCtrl+V' }));
    menu.append(new MenuItem({ label: 'Select All', selector: 'selectAll:', accelerator: 'CmdOrCtrl+A' }));
  }
  else {
    menu.append(new MenuItem({ label: 'Cut', role: 'cut', accelerator: 'CmdOrCtrl+X' }));
    menu.append(new MenuItem({ label: 'Copy', role: 'copy', accelerator: 'CmdOrCtrl+C' }));
    menu.append(new MenuItem({ label: 'Paste', role: 'paste', accelerator: 'CmdOrCtrl+V' }));
    menu.append(new MenuItem({ label: 'Select All', role: 'selectall', accelerator: 'CmdOrCtrl+A' }));
  }
  menu.append(new MenuItem({ type: 'separator' }));
  menu.append(new MenuItem({
    label: 'Reload',
    accelerator: 'CmdOrCtrl+R',
    click: function(){
      //var focusedWindow = BrowserWindow.getFocusedWindow();
      //if (focusedWindow)
      //  focusedWindow.reload();
      location.reload();
    }
  }))

  window.addEventListener('contextmenu', function (e) {
    e.preventDefault();
    menu.popup(remote.getCurrentWindow());
  }, false);

})();

/*************************
* Cheat manager module
**************************/

(function(){
  // initialize
  var cheatList = ipc.sendSync('load-cheats-msg');

  //cache DOM
  var $editCheatForm = $('#editCheatForm');
  var $cheatsView = $('#cheatsView');
  var $cheatsUl = $('#cheatsUl');
  var $tagListUl = $('#tagList');
  var cheatListTemplate = $cheatsView.find('#cheats-template').html();
  var tagListTemplate = $('#tags-template').html();

  // bind events
  $editCheatForm.on('submit', saveEdits);
  $cheatsUl.delegate('a.cheat-action-edit', 'click', loadCheatToEditForm);
  $cheatsUl.delegate('a.cheat-action-delete', 'click', deleteCheat);
  $tagListUl.delegate('a', 'click', filterCheatList);

  _render();

  function _render () {
    // render cheats
    $cheatsUl.html(Mustache.render(cheatListTemplate, cheatList));
    _enableDragAndDrop();

    // render tags
    var tagList = [];
    cheatList.cheats.forEach(function(cheat){
      if (cheat.tags)
      {
        cheat.tags.forEach(function(tag){
          if (tagList.indexOf(tag) === -1)
            tagList.push(tag);
        });
      }
    });
    $tagListUl.html(Mustache.render(tagListTemplate, {"tagList":tagList}));

    _renderTagSelection();
  }

  function _enableDragAndDrop()
  {
    $('.sortable').sortable({
      forcePlaceholderSize: true,
      handle: '.sort-handle'
    })
    .bind('sortupdate', function(e, ui) {
      cheatList.cheats.move(ui.oldElementIndex, ui.elementIndex);
      ipc.send('reorder-cheatlist-msg', {from: ui.oldElementIndex, to: ui.elementIndex});
    });
  }

  function _renderTagSelection()
  {
    $tagListUl.find('li').each(function(i, li){
      var tagItem = $(li);
      if (!tagItem.hasClass('selectedTag'))
        tagItem.find('span').css('visibility', 'hidden');
      else
        tagItem.find('span').css('visibility', 'visible');
    });
  }

  function loadCheatToEditForm(event) {
    var $cheat = $(event.target).closest('li');

    $("#inputId").val($cheat.find('.panel-body .cheatId').text().trim());
    $("#inputTitle").val($cheat.find('.panel-body .cheatTitle').text());
    $("#inputNotes").val($cheat.find('.panel-body .cheatNotes').text().trim());
    $("#inputCode").val($cheat.find('.panel-body .cheatCode').text());

    var tagString = $cheat.find('.panel-body .cheatTags').map(function () {
          return $(this).text();
      }).get().join();
    $("#inputTags").val(tagString);
  }

  function saveEdits(event) {
    var $cheatId = $("#inputId").val().trim();
    var sep = /\s*,\s*/;

    if ($cheatId === "") //We have a brand new cheat
    {
      var newCheat = {
        'id': Date.now(),
        'title': $("#inputTitle").val(),
        'notes' : $("#inputNotes").val(),
        'code' : $("#inputCode").val(),
        'tags' : $("#inputTags").val().split(sep)
      };

      if (newCheat.tags.length === 1 && newCheat.tags[0] === '') // no tags
        newCheat.tags = null;

      cheatList.cheats.unshift(newCheat);
      ipc.send('add-cheat-msg', newCheat);
    }
    else // We are editing an existing cheat
    {
      var editedCheat = {
        'id': $cheatId,
        'title': $("#inputTitle").val(),
        'notes' : $("#inputNotes").val(),
        'code' : $("#inputCode").val(),
        'tags' : $("#inputTags").val().split(sep)
      };

      if (editedCheat.tags.length === 1 && editedCheat.tags[0] === '') // no tags
        editedCheat.tags = null;

      var cheatSearchResult = $.grep(cheatList.cheats, function(c){ return c.id == $cheatId; });
      if (cheatSearchResult.length > 0)
      {
        cheatSearchResult[0].title = editedCheat.title;
        cheatSearchResult[0].notes = editedCheat.notes;
        cheatSearchResult[0].code = editedCheat.code;
        cheatSearchResult[0].tags = editedCheat.tags;
      }
      ipc.send('edit-cheat-msg', editedCheat);
    }

    event.preventDefault();
    _render();
  }

  function deleteCheat(event) {
    var cont = confirm("Confirm deletion");
    if (cont === false)
      return;

    var $cheat = $(event.target).closest('li');
    var cheatId = $cheat.find('.panel-body .cheatId').text().trim();

    cheatList.cheats = cheatList.cheats.filter(function (cheat) {
                          return cheat.id != cheatId;
                         });

    ipc.send('delete-cheat-msg', cheatId);

    _render();
  }

  function filterCheatList(event) {

    $tagListUl.find('li').removeClass('selectedTag');
    var $selectedTag = $(event.target).closest('li');
    $selectedTag.addClass('selectedTag');
    _renderTagSelection();

    var selectedTagText = $selectedTag.text();
    if (selectedTagText === 'All')
    {
      $cheatsUl.find('li').each(function (index, listItem){
        $(listItem).show();
      });
    }
    else {
      $cheatsUl.find('li').each(function (index, listItem){
        $tagSpans = $(listItem).find('span.cheatTags');
        if (!$tagSpans.text().includes(selectedTagText))
        {
          $(listItem).hide();
        }
        else {
          $(listItem).show();
        }
      });
    }

  }

})();
<|endoftext|>


<commit_before>"use strict";

const Telegraf = require("telegraf");
const { Telegram } = require("telegraf");
const { json } = require("req");
const cowsay = require("cowsay");
// const cron = require("node-cron");
const key = process.argv[2];
const readline = require("readline");
const Danbooru = require("danbooru");
// const fs = require("fs");

const args = text => text.split(" ").slice(1);
const argstring = text => args(text).join(" ").trim();

const bot = new Telegraf(key);
bot.telegram.getMe().then(data =>
	bot.options.username = data.username);

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
	prompt: "chat: "
});

const tg = new Telegram(key);

const booru = new Danbooru();

const feature = ({ reply }) =>
	reply("This feature is either under construction " +
	"or I'm too retarded to implement it");

const cow = `

         (__)
         (oo)
   /------\\/
  / |    ||
 *  /\\---/\\
    ~~   ~~
...."Have you mooed today?"...
`;

const cows = ["beavis.zen", "bong", "bud-frogs", "bunny", "cheese" +
"cower", "daemon", "default", "doge", "dragon-and-cow", "dragon", +
"elephant-in-snake", "elephant", "eyes", "flaming-sheep", +
"ghostbusters", "goat", "head-in", "hedgehog", "hellokitty", "kiss", +
"kitty", "koala", "kosh", "luke-koala", "mech-and-cow", "meow", "milk", +
"moofasa", "moose", "mutilated", "ren", "satanic", "sheep", "skeleton", +
"small", "sodomized", "squirrel", "stegosaurus", "stimpy", "supermilker", +
"surgery", "telebears", "turkey", "turtle", "tux", "vader-koala", "vader", "whale", "www"];

bot.command("start", ({ reply }) =>
	reply("fuck off"));

bot.command("moo", ({ reply }) =>
	reply(cow, { parse_mode: "HTML" }));

bot.command("test", feature);

bot.command("rogue", feature);

bot.command("info", feature);

bot.command("danbooru", ({ message, reply, replyWithPhoto }) => {
	const tags = args(message.text);
	let errors = "Following errors occured:\n";
	if(tags == "")
		reply("you forgot to specify tags retard");
	else booru.posts(tags)
		.then(posts => posts[Math.floor(Math.random()*posts.length)])
		.then(post => booru.posts.get(post))
		.catch(function(e) {
			errors += e + "\n";
		})
		.then(postInfo => {
			const file = postInfo.file;
			if(!("request" in file))
				reply("image unavailable");
			else replyWithPhoto(`https://danbooru.donmai.us/data/${file.name}`)
				.catch(function(e) {
					if(e.toString().includes("400"))
						replyWithPhoto(`https://danbooru.donmai.us/cached/data/${file.name}`);
					else {
						errors += e + " (image unavailable)\n";
						reply(errors);
					}
				})
				.then(reply(`Post ID: ${postInfo.id}\n` +
				`Artist: ${postInfo.tags.artist}\n` +
				`Characters: ${postInfo.tags.character}\n` +
				`Copyright info: ${postInfo.tags.copyright}`));
		})
		.catch(function(e) {
			errors += e + "\n";
			reply(errors + "You propably used nonexisting tags.");
		});
});

bot.command("price", ({ message, reply }) => {
	if(args(message.text)[0] == undefined)
		reply("input a valid ticker symbol retard");
	else json("https://api.coinmarketcap.com/v1/ticker/")
		.then(crap => crap.find(obj =>
			obj.symbol === args(message.text)[0].toUpperCase()))
		.then(balls => {
			if(balls == undefined)
				reply("input a valid ticker symbol retard");
			else balls.percent_change_24h.includes("-") //as long as it works
				? reply(balls.name + ": " + balls.price_usd + "$ " + balls.percent_change_24h + "% 📉")
				: reply(balls.name + ": " + balls.price_usd + "$ +" + balls.percent_change_24h + "% 📈");
		});
});

bot.command("weather", ({ message, reply }) => {
	const K = 273.15;
	const icons = {
		"01d": "☀", "01n": "🌕",
		"02d": "🌤", "02n": "🌤",
		"03d": "⛅", "03n": "⛅",
		"04d": "☁", "04n": "☁",
		"09d": "🌧", "09n": "🌧",
		"10d": "🌦", "10n": "🌦",
		"11d": "🌩", "11n": "🌩",
		"13d": "🌨", "13n": "🌨",
		"50d": "🌫", "50n": "🌫"
	};
	return json("http://api.openweathermap.org/data/2.5/weather?q=" +
		encodeURIComponent(argstring(message.text)) +
		"&APPID=1566ed87c9944f0df94332da29ee817c").then(data =>
		data.cod !== 200
			? reply(`Error:\n${data.cod}: ${data.message}`)
			: reply(
				"Weather in " +
				data.name + ", " +
				data.sys.country + ": " +
				Math.floor(data.main.temp - K) + "°C, " +
				data.weather[0].description + " " +
				(icons[data.weather[0].icon] || "") + "\n" +
				" Humidity: " + Math.floor(data.main.humidity) + "%\n" +
				" Air pressure: " + Math.floor(data.main.pressure) + " hPa"));
});

bot.command("skelet", ({ reply }) => {
	let skelets = "";
	for (let i = 0; i < Math.floor((Math.random() * 20) + 1 ); i++)
		skelets += Math.random() < 0.5 ? "💀" : "☠";
	return reply(skelets);
});

bot.command("cowsay", ({ message, reply }) => {
	const arg = args(message.text);
	let text = arg.slice();
	let notCow = false;
	text.splice(0,1);
	if(arg == undefined || message.text == undefined || arg[0] == undefined) {
		reply("specify animal and/or text");
	} else for(let i = 0; i < cows.length; i++){
		if(arg[0].includes(cows[i])) {
			reply("```" + cowsay.say({
				text : text.join(" ") || "I'm too dumb to type some text",
				f : arg[0]
			}) + "```", { parse_mode: "Markdown" });
			notCow = true; //fucking genius
			break;
		}
	} if(arg[0].includes("list") && notCow === false) {
		reply(cows);
	} else if(notCow === false) {
		reply("```" + cowsay.say({
			text : arg.join(" ") || "Have you mooed today?",
		}) + "```", { parse_mode: "Markdown" });
	}
});

bot.on("text", ({ message, replyWithSticker, reply, tg }) => {
	let msg = message.from.username + ": " + message.text;
	if (message.from.username == undefined)
		msg = message.from.first_name + " " + message.from.last_name + ": " + message.text;
	if(message.chat.id != "-1001064029829" && message.chat.id != "-1001138989974" && message.chat.id != "-1001144567507")
		tg.sendMessage("@skeletlog", msg);
	const text = message.text.toLowerCase();
	if(message.from.id == 353196474 && text.includes("nice") || message.from.id == 128432371 && text.includes("nice"))
		replyWithSticker("CAADBAADPwADulkNFYeAzy5ClSxjAg");
	else if(text == undefined)
		reply("unknown error");
});

bot.on("photo", ({ message, tg }) => {
	let caption = message.from.username + ": " + message.caption;
	if (message.from.username == undefined)
		caption = message.from.first_name + " " + message.from.last_name + ": " + message.caption;
	if(message.chat.id != "-1001064029829" && message.chat.id != "-1001138989974" && message.chat.id != "-1001144567507"){
		tg.sendPhoto("@skeletlog", message.photo[0].file_id, [caption]);
		tg.sendMessage("@skeletlog", caption);
	}
});

let id = "@skeletlog";
rl.prompt();
rl.on("line", (line) => {
	switch (line.trim()) {
	case "/setchat":
		rl.question("set chat id: ", (setid) => {
			id = setid;
			rl.prompt();
		});
		break;
	default:
		tg.sendMessage(id, `${line.trim()}`);
		break;
	}
	rl.prompt();
});

bot.startPolling();
<commit_msg>fix cowsay exploit<commit_after>"use strict";

const Telegraf = require("telegraf");
const { Telegram } = require("telegraf");
const { json } = require("req");
const cowsay = require("cowsay");
// const cron = require("node-cron");
const key = process.argv[2];
const readline = require("readline");
const Danbooru = require("danbooru");
// const fs = require("fs");

const args = text => text.split(" ").slice(1);
const argstring = text => args(text).join(" ").trim();

const bot = new Telegraf(key);
bot.telegram.getMe().then(data =>
	bot.options.username = data.username);

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
	prompt: "chat: "
});

const tg = new Telegram(key);

const booru = new Danbooru();

const feature = ({ reply }) =>
	reply("This feature is either under construction " +
	"or I'm too retarded to implement it");

const cow = `

         (__)
         (oo)
   /------\\/
  / |    ||
 *  /\\---/\\
    ~~   ~~
...."Have you mooed today?"...
`;

const cows = ["beavis.zen", "bong", "bud-frogs", "bunny", "cheese", "cower", "daemon", "default", "doge", "dragon-and-cow", "dragon", "elephant-in-snake", "elephant", "eyes", "flaming-sheep", "ghostbusters", "goat", "head-in", "hedgehog", "hellokitty", "kiss", "kitty", "koala", "kosh", "luke-koala", "mech-and-cow", "meow", "milk", "moofasa", "moose", "mutilated", "ren", "satanic", "sheep", "skeleton", "small", "sodomized", "squirrel", "stegosaurus", "stimpy", "supermilker", "surgery", "telebears", "turkey", "turtle", "tux", "vader-koala", "vader", "whale", "www"];

bot.command("start", ({ reply }) =>
	reply("fuck off"));

bot.command("moo", ({ reply }) =>
	reply(cow, { parse_mode: "HTML" }));

bot.command("test", feature);

bot.command("rogue", feature);

bot.command("info", feature);

bot.command("danbooru", ({ message, reply, replyWithPhoto }) => {
	const tags = args(message.text);
	let errors = "Following errors occured:\n";
	if(tags == "")
		reply("you forgot to specify tags retard");
	else booru.posts(tags)
		.then(posts => posts[Math.floor(Math.random()*posts.length)])
		.then(post => booru.posts.get(post))
		.catch(function(e) {
			errors += e + "\n";
		})
		.then(postInfo => {
			const file = postInfo.file;
			if(!("request" in file))
				reply("image unavailable");
			else replyWithPhoto(`https://danbooru.donmai.us/data/${file.name}`)
				.catch(function(e) {
					if(e.toString().includes("400"))
						replyWithPhoto(`https://danbooru.donmai.us/cached/data/${file.name}`);
					else {
						errors += e + " (image unavailable)\n";
						reply(errors);
					}
				})
				.then(reply(`Post ID: ${postInfo.id}\n` +
				`Artist: ${postInfo.tags.artist}\n` +
				`Characters: ${postInfo.tags.character}\n` +
				`Copyright info: ${postInfo.tags.copyright}`));
		})
		.catch(function(e) {
			errors += e + "\n";
			reply(errors + "You propably used nonexisting tags.");
		});
});

bot.command("price", ({ message, reply }) => {
	if(args(message.text)[0] == undefined)
		reply("input a valid ticker symbol retard");
	else json("https://api.coinmarketcap.com/v1/ticker/")
		.then(crap => crap.find(obj =>
			obj.symbol === args(message.text)[0].toUpperCase()))
		.then(balls => {
			if(balls == undefined)
				reply("input a valid ticker symbol retard");
			else balls.percent_change_24h.includes("-") //as long as it works
				? reply(balls.name + ": " + balls.price_usd + "$ " + balls.percent_change_24h + "% 📉")
				: reply(balls.name + ": " + balls.price_usd + "$ +" + balls.percent_change_24h + "% 📈");
		});
});

bot.command("weather", ({ message, reply }) => {
	const K = 273.15;
	const icons = {
		"01d": "☀", "01n": "🌕",
		"02d": "🌤", "02n": "🌤",
		"03d": "⛅", "03n": "⛅",
		"04d": "☁", "04n": "☁",
		"09d": "🌧", "09n": "🌧",
		"10d": "🌦", "10n": "🌦",
		"11d": "🌩", "11n": "🌩",
		"13d": "🌨", "13n": "🌨",
		"50d": "🌫", "50n": "🌫"
	};
	return json("http://api.openweathermap.org/data/2.5/weather?q=" +
		encodeURIComponent(argstring(message.text)) +
		"&APPID=1566ed87c9944f0df94332da29ee817c").then(data =>
		data.cod !== 200
			? reply(`Error:\n${data.cod}: ${data.message}`)
			: reply(
				"Weather in " +
				data.name + ", " +
				data.sys.country + ": " +
				Math.floor(data.main.temp - K) + "°C, " +
				data.weather[0].description + " " +
				(icons[data.weather[0].icon] || "") + "\n" +
				" Humidity: " + Math.floor(data.main.humidity) + "%\n" +
				" Air pressure: " + Math.floor(data.main.pressure) + " hPa"));
});

bot.command("skelet", ({ reply }) => {
	let skelets = "";
	for (let i = 0; i < Math.floor((Math.random() * 20) + 1 ); i++)
		skelets += Math.random() < 0.5 ? "💀" : "☠";
	return reply(skelets);
});

bot.command("cowsay", ({ message, reply }) => {
	const arg = args(message.text);
	let text = arg.slice();
	let notCow = false;
	text.splice(0,1);
	if(arg == undefined || message.text == undefined || arg[0] == undefined) {
		reply("specify animal and/or text");
	} else for(let i = 0; i < cows.length; i++){
		if(arg[0].includes(cows[i])) {
			reply("```" + cowsay.say({
				text : text.join(" ") || "I'm too dumb to type some text",
				f : arg[0]
			}) + "```", { parse_mode: "Markdown" });
			notCow = true; //fucking genius
			break;
		}
	} if(arg[0].includes("list") && notCow === false) {
		reply(cows);
	} else if(notCow === false) {
		reply("```" + cowsay.say({
			text : arg.join(" ") || "Have you mooed today?",
		}) + "```", { parse_mode: "Markdown" });
	}
});

bot.on("text", ({ message, replyWithSticker, reply, tg }) => {
	let msg = message.from.username + ": " + message.text;
	if (message.from.username == undefined)
		msg = message.from.first_name + " " + message.from.last_name + ": " + message.text;
	if(message.chat.id != "-1001064029829" && message.chat.id != "-1001138989974" && message.chat.id != "-1001144567507")
		tg.sendMessage("@skeletlog", msg);
	const text = message.text.toLowerCase();
	if(message.from.id == 353196474 && text.includes("nice") || message.from.id == 128432371 && text.includes("nice"))
		replyWithSticker("CAADBAADPwADulkNFYeAzy5ClSxjAg");
	else if(text == undefined)
		reply("unknown error");
});

bot.on("photo", ({ message, tg }) => {
	let caption = message.from.username + ": " + message.caption;
	if (message.from.username == undefined)
		caption = message.from.first_name + " " + message.from.last_name + ": " + message.caption;
	if(message.chat.id != "-1001064029829" && message.chat.id != "-1001138989974" && message.chat.id != "-1001144567507"){
		tg.sendPhoto("@skeletlog", message.photo[0].file_id, [caption]);
		tg.sendMessage("@skeletlog", caption);
	}
});

let id = "@skeletlog";
rl.prompt();
rl.on("line", (line) => {
	switch (line.trim()) {
	case "/setchat":
		rl.question("set chat id: ", (setid) => {
			id = setid;
			rl.prompt();
		});
		break;
	default:
		tg.sendMessage(id, `${line.trim()}`);
		break;
	}
	rl.prompt();
});

bot.startPolling();
<|endoftext|>


<commit_before>$( document ).ready(function() {

	// Variable pour le script
	var numberImg = $(".back-image").length;
	var numImgCollection = $(".imageCatalogue").length
	var heightCache = 0;

	// Variable pour savoir sur quel slide on se trouve
	var state = 1;

	// Variable pour les slides
	var offsetBetweenSlide = 50;

	// Variable pour le zoom
	var timeZoom = 10000;
	var timeBetweenZoom = 200;
	var powerZoom = 1.1;
	var zoomInStart = {"ZoomIn" : "1"};
	var zoomInEnd = {"ZoomIn" : powerZoom};
	var zoomState = true;

	zoomin();

	function zoomin() {
		jQuery(zoomInStart).animate(zoomInEnd, {
		    duration: timeZoom,
		    step: function(now) {
		    		$(".back-image:visible").each(function() {
	    		    	$(this).css("transform","scale("+now+","+now+")");
		    		});
		    },
			complete : function() {
				if(zoomState) {
					zoomState = false;
					zoomInEnd = {"ZoomIn" : "1"};
					zoomInStart = {"ZoomIn" : powerZoom};
				} else {
					zoomState = true;
					zoomInStart = {"ZoomIn" : "1"};
					zoomInEnd = {"ZoomIn" : powerZoom};
				}
				setTimeout(zoomin, timeBetweenZoom);
			}
		});
	};

	var positionTopScroll=0;
	$(window).scroll(function(event) {
		positionTopScroll = $(window).scrollTop();
		transition();
	});

	function transition() {
		if(positionTopScroll<($(window).height()+offsetBetweenSlide)) {
			if(state!=1) {
				$("#img1").css("display","block");
	    		$(".back-image").not("#img1").each(function() {
	    			$(this).css("display","none");
	    		});
    			$("#title").css("color","#FFFFFF");
				state=1;
			}
		} else {
			var calcul = 0;
			for(var i=2;i<numberImg+1;i++) {
				if(positionTopScroll>($(window).height()*(i-1)+offsetBetweenSlide*(i-1)+calcul) && state!=i) {
					$("#img"+i).css("display","block");
		    		$(".back-image").not("#img"+i).each(function() {
		    			$(this).css("display","none");
		    		});
	    			$("#title").css("color","#000000");
					state=i;
				}
				calcul = $(".cache:eq("+(i-2)+")").height();
			}
		}
	}

	$( window ).on("resize load",function() {
		init();
	});

	// Affichage du menu 2
	$("#bmenu2").click(function() {
		$("#menu2").css("display","block");
		$("#bemenu1").css("display","none");
		$("#bmenu1").css("display","none");
		$("#bmenu2").css("display","none");
		$("#menu2").animate({"opacity":"0.8"},500,function(){
			$("#menu2").animate({"width":"90%"},{ duration: 100, queue: false });
			$("#menu2").animate({"height":"90%"},{ duration: 100, queue: false, complete: function() {
				$(".imageCatalogue").each(function(index) {
					if(index==0) {
						$(this).css("width",$(this).width()/2);
						slotleft = $(this).width()/2;
						$(this).css("left","0px");
					} else if(index==1) {
						slotmiddle = $("#menu2").width()/2-$(this).width()/2;
						$(this).css("left",slotmiddle+"px");
					} else {
						$(this).css("width",$(this).width()/2);
						slotright = $("#menu2").width()-$(this).width();
						$(this).css("left",slotright+"px");
					}
					if(index<3) {
						$(this).css("display","block");
						$(this).animate({"opacity":"1"},100);
					}
				});
			} });

		});
	});

	$("#bmenu2ext").click(function() {
		$(".imageSlide").each(function() {
			$(this).animate({"opacity":"0"},100,function() {
				$(this).css("display","none");
			});
		});
		$("#menu2").animate({"width":"100%"},{ duration: 100, queue: false });
		$("#menu2").animate({"height":"100%"},{ duration: 100, queue: false });
		$("#menu2").animate({"opacity":"0"},{ duration: 300, queue: false, complete: function() {
			$("#menu2").css("display","none");
			$("#bmenu1").css("display","block");
			$("#bmenu2").css("display","block");
		}});

	});

	// Affichage du menu 1
	var menu2visible = false;
	$("#bmenu1,#bemenu1ext").click(function() {
		$(".imageSlide").each(function(index) {
			$(this).animate({"opacity":"0"},100,function() {
				$(this).css("display","none");
			});
		});
		$("#menu1").css("display","block");
		$("#bemenu1").css("display","block");
		$("#bmenu1").css("display","none");
		$("#bmenu2").css("display","none");
		if($("#menu2").is(':visible')) {
			$("#menu2").css("display","none");
			menu2visible=true;
		}
		$("#bmenu1").animate({"opacity":"0"},{ duration: 100, queue: false });
		$("#menu1").animate({"opacity":"0.8"},{ duration: 100, queue: false });
		$("#menu1").animate({"width":"90%"},{ duration: 300, queue: false });
		$("#menu1").animate({"height":"90%"},{ duration: 300, queue: false });
	});

	// Suppression d'affichage du menu 1
	$("#bemenu1").click(function() {

			if(menu2visible) {
				$("#menu2").css("display","block");
				menu2visible=false;
				$(".imageSlide").each(function() {
					$(this).css("display","block");
					$(this).animate({"opacity":"1"},100);
				});
			} else {
				$("#bmenu1").css("display","block");
				$("#bmenu2").css("display","block");
				$(".imageSlide").each(function() {
					$(this).animate({"opacity":"0"},100,function() {
						$(this).css("display","none");
					});
				});
			}
			$("#bmenu1").animate({"opacity":"1"},{ duration: 100, queue: false });
			$("#menu1").animate({"opacity":"0"},{ duration: 100, queue: false, complete: function(){
				$("#menu1").css("display","none");
				$("#bemenu1").css("display","none");
			}});
			$("#menu1").animate({"width":"100%"},{ duration: 300, queue: false });
			$("#menu1").animate({"height":"100%"},{ duration: 300, queue: false });
	});

	init();
	function init() {
		heightCache = 0;
		$(".cache").each(function() {
			heightCache += $(this).height();
		});
		$("body").css("height",numberImg*$(window).height()+offsetBetweenSlide*numberImg+heightCache+"px");

		//Angle
		$(".tbl").css("border-left",$(window).width()+"px solid transparent");
		$(".tbr").css("border-right",$(window).width()+"px solid transparent");
		$(".ttr").css("border-right",$(window).width()+"px solid transparent");
		$(".ttl").css("border-left",$(window).width()+"px solid transparent");

		$(".tbl").each(function() {
			$(this).css("top",-100+"px");
		});

		$(".tbr").each(function() {
			$(this).css("top",-100+"px");
		});

		$(".ttr").each(function(index) {
			$(this).css("top",$(".cache:eq("+index+")").height()+"px");
		});

		$(".ttl").each(function(index) {
			$(this).css("top",$(".cache:eq("+index+")").height()+"px");
		});

		// Set the position of all the slide
		var positionSlide = $(window).height()+offsetBetweenSlide;
		$(".cache").each(function(index) {
			$(this).css("top",positionSlide+"px");
			positionSlide += $(window).height()+$(this).height()+offsetBetweenSlide;
		});
		$("#footer").css("top",positionSlide-$(window).height()-offsetBetweenSlide+"px");

		// Set the first image to display
		$("#img1").css("display","block");
		$(".back-image").not("#img1").each(function() {
			$(this).css("display","none");
		});

		positionTopScroll = $(window).scrollTop();
		transition();
	}

	var imgCollection = 0;

	var offsetcollection = 200;
	var slotleft = -$(".imageSlide").first().width()+offsetcollection;
	var slotmiddle = $("#menu2").width()/2-$(".imageCatalogue").first().width()/2;
	var slotright = ($(window).width()-$(".imageSlide").first().width())+$(".imageSlide").first().width()-offsetcollection;

	$("#arrowLeft").click(function() {
		$(".imageCatalogue").each(function(index) {
			if(index==imgCollection) {
				$(this).animate({"opacity" : "0"},{duration:300, queue: false});
			}
			if(index==imgCollection+1) {
				$(this).animate({"width" : $(this).width()/2},{duration:300, queue: false});
				$(this).animate({"left":"0px"},{duration:300, queue: false});
			}
			if(index==imgCollection+2) {
				$(this).animate({"width" : $(this).width()*2},{duration:300, queue: false});
				$(this).animate({"left":slotmiddle+"px"},{duration:300, queue: false, complete: function() {
					$(".imageCatalogue").eq(imgCollection+2).animate({"opacity" : "1"},{duration:300, queue: false});
				}});
			}

		});
		imgCollection++;
	});

		/**
		if(imgCollection < numImgCollection - 1) {
			var scale=1.2;
			var scale2=1;
			$(".imageSlide").each(function(index) {
						if(index==imgCollection) {
							$(this).animate({"left":slotleft+"px"},{duration:1000, queue: false, step: function() {
								if(scale2<1.2) {
									scale2+=0.02;
									$(this).css("transform","translateY(-50%) scale("+scale2+","+scale2+")");
								}
							}});
						}
						if(index==imgCollection+1) {
							$(this).animate({"left":slotmiddle+"px"},{duration:1000, queue: false, step: function() {
								if(scale>1) {
									scale-=0.02;
									$(this).css("transform","translateY(-50%) scale("+scale+","+scale+")");
								}
							}});
						}
						if(index==imgCollection+2) {
							$(this).animate({"left":slotright+"px"},{duration:1000, queue: false, step: function() {
								if(scale2<1.2) {
									scale2+=0.02;
									$(this).css("transform","translateY(-50%) scale("+scale2+","+scale2+")");
								}
							}});
						}
						if(index<imgCollection) {
							$(this).animate({"left":-2*$(window).width()+"px"},{duration:1000, queue: false, step: function() {
								if(scale>1) {
									scale-=0.02;
									$(this).css("transform","translateY(-50%) scale("+scale+","+scale+")");
								}
							}});
						}
			});
			**/

	$("#arrowRight").click(function() {
		if(imgCollection>0) {
			var scale=1.2;
			var scale2=1;
			$(".imageSlide").each(function(index) {
						if(index==imgCollection) {
							$(this).animate({"left":slotright+"px"},{duration:1000, queue: false, step: function() {
								if(scale2<1.2) {
									scale2+=0.02;
									$(this).css("transform","translateY(-50%) scale("+scale2+","+scale2+")");
								}
							}});
						}
						if(index==imgCollection-1) {
							$(this).animate({"left":slotmiddle+"px"},{duration:1000, queue: false, step: function() {
								if(scale>1) {
									scale-=0.02;
									$(this).css("transform","translateY(-50%) scale("+scale+","+scale+")");
								}
							}});
						}
						if(index==imgCollection-2) {
							$(this).animate({"left":slotleft+"px"},{duration:1000, queue: false, step: function() {
								if(scale2<1.2) {
									scale2+=0.02;
									$(this).css("transform","translateY(-50%) scale("+scale2+","+scale2+")");
								}
							}});
						}
						if(index>imgCollection) {
							$(this).animate({"left":2*$(window).width()+"px"},{duration:1000, queue: false, step: function() {
								if(scale2<1.2) {
									scale2+=0.02;
									$(this).css("transform","translateY(-50%) scale("+scale2+","+scale2+")");
								}
							}});
						}
			});
			imgCollection--;
		}
	});

});

<commit_msg>Creating the carousel<commit_after>$( document ).ready(function() {

	// Variable pour le script
	var numberImg = $(".back-image").length;
	var numImgCollection = $(".imageCatalogue").length
	var heightCache = 0;

	// Variable pour savoir sur quel slide on se trouve
	var state = 1;

	// Variable pour les slides
	var offsetBetweenSlide = 50;

	// Variable pour le zoom
	var timeZoom = 10000;
	var timeBetweenZoom = 200;
	var powerZoom = 1.1;
	var zoomInStart = {"ZoomIn" : "1"};
	var zoomInEnd = {"ZoomIn" : powerZoom};
	var zoomState = true;

	zoomin();

	function zoomin() {
		jQuery(zoomInStart).animate(zoomInEnd, {
		    duration: timeZoom,
		    step: function(now) {
		    		$(".back-image:visible").each(function() {
	    		    	$(this).css("transform","scale("+now+","+now+")");
		    		});
		    },
			complete : function() {
				if(zoomState) {
					zoomState = false;
					zoomInEnd = {"ZoomIn" : "1"};
					zoomInStart = {"ZoomIn" : powerZoom};
				} else {
					zoomState = true;
					zoomInStart = {"ZoomIn" : "1"};
					zoomInEnd = {"ZoomIn" : powerZoom};
				}
				setTimeout(zoomin, timeBetweenZoom);
			}
		});
	};

	var positionTopScroll=0;
	$(window).scroll(function(event) {
		positionTopScroll = $(window).scrollTop();
		transition();
	});

	function transition() {
		if(positionTopScroll<($(window).height()+offsetBetweenSlide)) {
			if(state!=1) {
				$("#img1").css("display","block");
	    		$(".back-image").not("#img1").each(function() {
	    			$(this).css("display","none");
	    		});
    			$("#title").css("color","#FFFFFF");
				state=1;
			}
		} else {
			var calcul = 0;
			for(var i=2;i<numberImg+1;i++) {
				if(positionTopScroll>($(window).height()*(i-1)+offsetBetweenSlide*(i-1)+calcul) && state!=i) {
					$("#img"+i).css("display","block");
		    		$(".back-image").not("#img"+i).each(function() {
		    			$(this).css("display","none");
		    		});
	    			$("#title").css("color","#000000");
					state=i;
				}
				calcul = $(".cache:eq("+(i-2)+")").height();
			}
		}
	}

	$( window ).on("resize load",function() {
		init();
	});

	// Affichage du menu 2
	$("#bmenu2").click(function() {
		$("#menu2").css("display","block");
		$("#bemenu1").css("display","none");
		$("#bmenu1").css("display","none");
		$("#bmenu2").css("display","none");
		$("#menu2").animate({"opacity":"0.8"},500,function(){
			$("#menu2").animate({"width":"90%"},{ duration: 100, queue: false });
			$("#menu2").animate({"height":"90%"},{ duration: 100, queue: false, complete: function() {
				$(".imageCatalogue").each(function(index) {
					if(index==0) {
						$(this).css("width",$(this).width()/2);
						slotleft = $(this).width()/2;
						$(this).css("left","0px");
					} else if(index==1) {
						slotmiddle = $("#menu2").width()/2-$(this).width()/2;
						$(this).css("left",slotmiddle+"px");
					} else {
						$(this).css("width",$(this).width()/2);
						slotright = $("#menu2").width()-$(this).width();
						$(this).css("left",slotright+"px");
					}
					if(index<3) {
						$(this).css("display","block");
						$(this).animate({"opacity":"1"},100);
					}
				});
			} });

		});
	});

	$("#bmenu2ext").click(function() {
		$(".imageSlide").each(function() {
			$(this).animate({"opacity":"0"},100,function() {
				$(this).css("display","none");
			});
		});
		$("#menu2").animate({"width":"100%"},{ duration: 100, queue: false });
		$("#menu2").animate({"height":"100%"},{ duration: 100, queue: false });
		$("#menu2").animate({"opacity":"0"},{ duration: 300, queue: false, complete: function() {
			$("#menu2").css("display","none");
			$("#bmenu1").css("display","block");
			$("#bmenu2").css("display","block");
		}});

	});

	// Affichage du menu 1
	var menu2visible = false;
	$("#bmenu1,#bemenu1ext").click(function() {
		$(".imageSlide").each(function(index) {
			$(this).animate({"opacity":"0"},100,function() {
				$(this).css("display","none");
			});
		});
		$("#menu1").css("display","block");
		$("#bemenu1").css("display","block");
		$("#bmenu1").css("display","none");
		$("#bmenu2").css("display","none");
		if($("#menu2").is(':visible')) {
			$("#menu2").css("display","none");
			menu2visible=true;
		}
		$("#bmenu1").animate({"opacity":"0"},{ duration: 100, queue: false });
		$("#menu1").animate({"opacity":"0.8"},{ duration: 100, queue: false });
		$("#menu1").animate({"width":"90%"},{ duration: 300, queue: false });
		$("#menu1").animate({"height":"90%"},{ duration: 300, queue: false });
	});

	// Suppression d'affichage du menu 1
	$("#bemenu1").click(function() {

			if(menu2visible) {
				$("#menu2").css("display","block");
				menu2visible=false;
				$(".imageSlide").each(function() {
					$(this).css("display","block");
					$(this).animate({"opacity":"1"},100);
				});
			} else {
				$("#bmenu1").css("display","block");
				$("#bmenu2").css("display","block");
				$(".imageSlide").each(function() {
					$(this).animate({"opacity":"0"},100,function() {
						$(this).css("display","none");
					});
				});
			}
			$("#bmenu1").animate({"opacity":"1"},{ duration: 100, queue: false });
			$("#menu1").animate({"opacity":"0"},{ duration: 100, queue: false, complete: function(){
				$("#menu1").css("display","none");
				$("#bemenu1").css("display","none");
			}});
			$("#menu1").animate({"width":"100%"},{ duration: 300, queue: false });
			$("#menu1").animate({"height":"100%"},{ duration: 300, queue: false });
	});

	init();
	function init() {
		heightCache = 0;
		$(".cache").each(function() {
			heightCache += $(this).height();
		});
		$("body").css("height",numberImg*$(window).height()+offsetBetweenSlide*numberImg+heightCache+"px");

		//Angle
		$(".tbl").css("border-left",$(window).width()+"px solid transparent");
		$(".tbr").css("border-right",$(window).width()+"px solid transparent");
		$(".ttr").css("border-right",$(window).width()+"px solid transparent");
		$(".ttl").css("border-left",$(window).width()+"px solid transparent");

		$(".tbl").each(function() {
			$(this).css("top",-100+"px");
		});

		$(".tbr").each(function() {
			$(this).css("top",-100+"px");
		});

		$(".ttr").each(function(index) {
			$(this).css("top",$(".cache:eq("+index+")").height()+"px");
		});

		$(".ttl").each(function(index) {
			$(this).css("top",$(".cache:eq("+index+")").height()+"px");
		});

		// Set the position of all the slide
		var positionSlide = $(window).height()+offsetBetweenSlide;
		$(".cache").each(function(index) {
			$(this).css("top",positionSlide+"px");
			positionSlide += $(window).height()+$(this).height()+offsetBetweenSlide;
		});
		$("#footer").css("top",positionSlide-$(window).height()-offsetBetweenSlide+"px");

		// Set the first image to display
		$("#img1").css("display","block");
		$(".back-image").not("#img1").each(function() {
			$(this).css("display","none");
		});

		positionTopScroll = $(window).scrollTop();
		transition();
	}

	var imgCollection = 0;
	var imgInterract = 0;
	var offsetcollection = 200;
	var slotleft = -$(".imageSlide").first().width()+offsetcollection;
	var slotmiddle = $("#menu2").width()/2-$(".imageCatalogue").first().width()/2;
	var slotright = ($(window).width()-$(".imageSlide").first().width())+$(".imageSlide").first().width()-offsetcollection;

	var jewelries = [];
	var imgCollection = 0;
	$(".imageCatalogue").each(function() {
		jewelries.push($(this));
	});

	$("#arrowLeft").click(function() {
		$(".imageCatalogue").each(function(index) {
			console.log(imgCollection);
			if(imgCollection==numImgCollection-2) {
				if(index==0) {
					$(this).animate({"width" : $(this).width()*2},{duration:300, queue: false});
					$(this).animate({"left":slotmiddle+"px"},{duration:300, queue: false, complete: function() {
						$(".imageCatalogue").eq(1).css("left",slotright+"px");
						$(".imageCatalogue").eq(1).animate({"opacity" : "1"},{duration:300, queue: false});
					}});
				}
				if(index==numImgCollection-1) {
					$(this).animate({"width" : $(this).width()/2},{duration:300, queue: false});
					$(this).animate({"left":"0px"},{duration:300, queue: false});
				}
				if(index==numImgCollection-2) {
					$(this).animate({"opacity" : "0"},{duration:300, queue: false, complete: function() {
						$(this).css("left",slotright+"px");
					}});
				}
			} else if(imgCollection==numImgCollection-1) {
				if(index==numImgCollection-1) {
					$(this).animate({"opacity" : "0"},{duration:300, queue: false, complete: function() {
						$(this).css("left",slotright+"px");
					}});
				}
				if(index==0) {
					$(this).animate({"width" : $(this).width()/2},{duration:300, queue: false});
					$(this).animate({"left":"0px"},{duration:300, queue: false});
				}
				if(index==1) {
					$(this).animate({"width" : $(this).width()*2},{duration:300, queue: false});
					$(this).animate({"left":slotmiddle+"px"},{duration:300, queue: false, complete: function() {
						$(".imageCatalogue").eq(2).css("left",slotright+"px");
						$(".imageCatalogue").eq(2).animate({"opacity" : "1"},{duration:300, queue: false});
						imgCollection=0;
					}});
				}
			} else {
				if(index==imgCollection) {
					$(this).animate({"opacity" : "0"},{duration:300, queue: false, complete: function() {
						$(this).css("left",slotright+"px");
					}});
				}
				if(index==imgCollection+1) {
					$(this).animate({"width" : $(this).width()/2},{duration:300, queue: false});
					$(this).animate({"left":"0px"},{duration:300, queue: false});
				}
				if(index==imgCollection+2) {
					$(this).animate({"width" : $(this).width()*2},{duration:300, queue: false});
					$(this).animate({"left":slotmiddle+"px"},{duration:300, queue: false, complete: function() {
						$(".imageCatalogue").eq(imgCollection+2).animate({"opacity" : "1"},{duration:300, queue: false});
						if(imgCollection==numImgCollection-2) {
							$(".imageCatalogue").eq(0).css("left",slotright+"px");
							$(".imageCatalogue").eq(0).animate({"opacity" : "1"},{duration:300, queue: false});
						}
					}});
				}
			}
		});
		imgCollection++;
	});

	$("#arrowRight").click(function() {
		$(".imageCatalogue").each(function(index) {
			if(imgCollection==0) {
				if(index==0) {
					$(this).animate({"width" : $(this).width()*2},{duration:300, queue: false});
					$(this).animate({"left":slotmiddle+"px"},{duration:300, queue: false, complete: function() {
						$(".imageCatalogue").eq(numImgCollection-1).css("left","0px");
						$(".imageCatalogue").eq(numImgCollection-1).animate({"opacity" : "1"},{duration:300, queue: false});
					}});
				}
				if(index==1) {
					$(this).animate({"width" : $(this).width()/2},{duration:300, queue: false});
					$(this).animate({"left":slotright+"px"},{duration:300, queue: false});
				}
				if(index==2) {
					$(this).animate({"opacity" : "0"},{duration:300, queue: false});
				}
			} else if(imgCollection==4) {
				if(index==0) {
					$(this).animate({"width" : $(this).width()/2},{duration:300, queue: false});
					$(this).animate({"left":slotright+"px"},{duration:300, queue: false});
				}
				if(index==1) {
					$(this).animate({"opacity" : "0"},{duration:300, queue: false});
				}
				if(index==numImgCollection-1) {
					$(this).animate({"width" : $(this).width()*2},{duration:300, queue: false});
					$(this).animate({"left":slotmiddle+"px"},{duration:300, queue: false, complete: function() {
						$(".imageCatalogue").eq(numImgCollection-2).css("left","0px");
						$(".imageCatalogue").eq(numImgCollection-2).animate({"opacity" : "1"},{duration:300, queue: false});
					}});
				}
			} else {
				if(index==imgCollection) {
					$(this).animate({"width" : $(this).width()*2},{duration:300, queue: false});
					$(this).animate({"left":slotmiddle+"px"},{duration:300, queue: false, complete: function() {
						$(".imageCatalogue").eq(imgCollection).css("left","0px");
						$(".imageCatalogue").eq(imgCollection).animate({"opacity" : "1"},{duration:300, queue: false});
					}});
				}
				if(index==imgCollection+1) {
					$(this).animate({"width" : $(this).width()/2},{duration:300, queue: false});
					$(this).animate({"left":slotright+"px"},{duration:300, queue: false});
				}
				if(index==imgCollection+2 || index==0) {
					$(this).animate({"opacity" : "0"},{duration:300, queue: false});
				}
			}

		});
		if(imgCollection==0) {
			imgCollection=4;
		} else {
			imgCollection--;
		}
	});

});

<|endoftext|>


<commit_before>( function( window, undefined ){

	window.MarioGolf = function( code ){
		var tmp = [];
		if( !code || !( code = code.match( /(?:^|[\r\n])([MLPBTYK]+)\|(?:(.*)\|)?([OQ|\-1RNM])(?:$|[\r\n])/ ) ) )
		{
			throw new SyntaxError( 'Expecting identifier, got ' + (code? 'invalid program' : '0-length code' ) + '.', 'code', 0 );
		}
		/*All credits due to @Jens (http://stackoverflow.com/users/276070/jens) for the trick:
		 *\+(?=([^"]*"[^"]*")*[^"]*$) - matches any + not inside quotes
		 *Question: http://stackoverflow.com/questions/6462578/alternative-to-regex-match-all-instances-not-inside-quotes
		 */
		else if( code[2] != undefined && ( tmp[0] = code[2].match( /\{(?=([^"]*"[^"]*")*[^"]*$)/g ) || [] ).length != ( tmp[1] = code[2].match( /\}(?=([^"]*"[^"]*")*[^"]*$)/g ) || [] ).length )
		{
			throw new SyntaxError( 'Missing "' + ( tmp[0] < tmp[1] ? '{' : '}' ) + '" before the last identifier.', 'code', 0 );
		}

		var memory = {
			code:code,
			return:'',
			input:'',
			stack:[],
			registers:{R:0,I:0,P:0,L:0,Z:0},
			vars:{},
			output:''
		},

		/*All credits due to @BenAlpert (http://stackoverflow.com/users/49485/ben-alpert) for this implementation
		 *Original code: s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
		 *Also, the use @ledlogic (http://stackoverflow.com/users/987044/ledlogic) made a general rot# function:
		 *function rot(s,i){return s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+i)?c:c-26);});}
		 *The latest is available on http://jsfiddle.net/ledlogic/tC7qe/
		 */
		rot13 = function(s){return s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});},

		/*All credits due to @Jeff (http://stackoverflow.com/users/353278) for this function
		 *Original source: http://snippets.dzone.com/posts/show/849
		 *http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
		 */
		shuffle = function(o){
			for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
			return o;
		},

		//tries to parse or get a value from a piece of code
		fetchValue = function( code ){
			var currentChar = code.charAt(0), nextChar = code.charAt(1)
			switch( currentChar )
			{
				case '\'':
					return nextChar;

				case '"':
					if( ~code.indexOf('"',1) )
					{
						return code.substring(1, code.indexOf('"',1) );
					}
					else
					{
						throw new SyntaxError( 'Missing " before the end of the code', 'code', 0 );
					}
					break;

				case '|':
					if( /[a-zRIPLZ]/.test( nextChar ) && (memory.vars[nextChar] || nextChar in memory.registers) )
					{
						if( /^[a-z]$/.test( nextChar ) )
						{
							return memory.vars[nextChar];
						}
						else
						{
							return memory.registers[nextChar];
						}
					}
					else
					{
						throw new ReferenceError( 'Undefined register "'+nextChar+'"', 'code', 0 );
					}
					break;

				case '{':
					return runBlock( code );

				default:

					if( /[a-z\d]/.test(currentChar) )
					{
						return code.match( /(^[a-z\d]+)/ )[1] || 0;
					}
					else
					{
						return;
					}
			}

		},

		runBlock = function( block ){
			for( var i = 0, l = block.length, c, Return; i<l; i++)
			{
				memory.registers.P++;
				switch(c = block.charAt(i))
				{

					/*******Arithmetic*******/

					case '+':
						Return = (memory.registers.R / 1 || 0 ) + fetchValue( block.slice( i + 1 ) );
						break;
					case '/':
						Return = ( (memory.registers.R / 1 || 0 ) / fetchValue( block.slice( i + 1 ) ) ) >> 0;
						break;
					case '\\':
						Return = ( memory.registers.R / 1 || 0 ) % fetchValue( block.slice( i + 1 ) );
						break;
					case '-':
						Return = memory.registers.R - fetchValue( block.slice( i + 1 ) );
						break;
					case '^':
						Return = Math.pow( memory.registers.R, fetchValue( block.slice( i + 1 ) ) );
						break;
					case '«':
						Return = ( memory.registers.R / 1 || 0 ) << ( fetchValue( block.slice( i + 1 ) ) & 32 );
						break;
					case '»':
						Return = ( memory.registers.R / 1 || 0 ) >> ( fetchValue( block.slice( i + 1 ) ) & 32 );
						break;
					case '~':
						Return = ~ ( memory.registers.R / 1 || 0 );
						break;

					/*******   Stack   *******/

					case '<':
						var tmp = fetchValue( block.slice( i + 1 ) );
						if( tmp / 1 == tmp / 1)
						{
							Return = memory.stack[memory.stack.length] = tmp >> 0;
						}
						else
						{
							Return = tmp;
							for(var j = 0, l = tmp.length; j<l; j++ )
							{
								memory.stack[memory.stack.length] = tmp.charAt(j);
							}
						}
						memory.registers.R = memory.stack[0];
						memory.registers.L = memory.stack.length;
						break;
				}
			}
		},

		outputHandler = window.console.log;

		return {
			run: function( input ){
				memory = {
					code:memory.code,
					return:'',
					input:input,
					stack:[],
					registers:{R:0,I:memory.code.index,P:0,L:0,Z:0},
					vars:{},
					output:''
				};

				var negative = true;

				for(var i = 0, l = memory.code[1].length, c; i<l; i++)
				{
					switch(c = memory.code[1].charAt(i))
					{
						case 'M': //loads all the characters to the stack
							memory.stack = (input || '').split('');break;
						case 'L': //same as M, but reverses
							memory.stack = input ? (input + '').reverse().split('') : [];break;
						case 'P': //disables negatives
							negative = false;break;
						case 'B': //EVERYTHING is a negative number
							memory.stack = [];
							if( input )
							{
								for(var j = 0, k = input.length; j<k; j++)
								{
									memory.stack[j] = -input.charAt(j);
								}
							}
							break;
						case 'T': //shuffles the stack
							memory.stack = shuffle( memory.stack );break;
						case 'Y':break; //empty stack
						case 'K': //places a quine into the stack
							memory.stack = memory.code[0].replace(/^\s+/,'').split('');break;
						default:
							throw new ReferenceError('Unknown identifier "'+c+'"');
					}
				}

				memory.registers.L = memory.stack.length;
				memory.registers.R = memory.stack[0] || 0;
				memory.registers.P = code[1].length + 1 ;

				if( memory.code[3].indexOf('Q') == -1 && memory.code[2] )
				{
					memory.return = runBlock( memory.code[2] );
				}

				if( 0 in memory.stack )
				{
					memory.stack[0] = memory.registers.R;
				}

				for(var i = 0, l = memory.code[3].length, c; i<l; i++)
				{
					switch(c = memory.code[3].charAt(i))
					{
						case '-': //destroy the return
							memory.return = undefined;
						case 'O': //display the content
							outputHandler.call( window.console, [memory.output = memory.stack.join('')] );break;
						case 'Q': //quine
							outputHandler.call( window.console, [memory.output = memory.code[0].replace(/^\s+/,'')] );break;
						case '|': //doesn't display anything, returns the stack
							memory.return = memory.stack;break;
						case '1': //displays the content as rot13
							outputHandler.call( window.console, [memory.output = rot13( memory.stack.join('') )] );break;
						case 'R': //displays reversed
							outputHandler.call( window.console, [memory.output = memory.stack.join('').split('').reverse().join('')] );break;
						case 'N': //outputs line by line, returns array
							outputHandler.call( window.console, [memory.output = memory.stack.join('').split('').join('\r\n')] );
							memory.return = memory.output.split('\r\n');break;
						case 'M': //outputs numbers line-by-line, returns array
							memory.return = [];
							if( memory.stack.length )
							{
								for(var j = 0, k = memory.stack.length; j<k; j++)
								{
									memory.return[j] = 'string' == typeof memory.stack[j] ? memory.stack[j] : String.fromCharCode(memory.stack[j]);
								}
							}
							outputHandler.call( window.console, [memory.output = memory.return.join('\r\n')] );break;
						default:
							throw new ReferenceError('Unknown identifier "'+c+'"');
					}
				}

				return memory.return;
			},
			getStack: function(){ return memory.stack; },
			getReturn: function(){ return memory.return; },
			getVars: function(){ return memory.vars; },
			getOutput: function(){ return memory.output; },
			getMemory: function(){ return memory; },
			setOutputHandler: function( fn ){
				if( fn instanceof window.Function)
				{
					outputHandler = fn;
					return true;
				}
				else
				{
					return false;
				}
			}
		};

	};

} )( Function('return this')() );
<commit_msg>Update mariogolf.js<commit_after>( function( window, undefined ){

	window.MarioGolf = function( code ){
		var tmp = [];
		if( !code || !( code = code.match( /(?:^|[\r\n])([MLPBTYK]+)\|(?:(.*)\|)?([OQ|\-1RNM])(?:$|[\r\n])/ ) ) )
		{
			throw new SyntaxError( 'Expecting identifier, got ' + (code? 'invalid program' : '0-length code' ) + '.', 'code', 0 );
		}
		/*All credits due to @Jens (http://stackoverflow.com/users/276070/jens) for the trick:
		 *\+(?=([^"]*"[^"]*")*[^"]*$) - matches any + not inside quotes
		 *Question: http://stackoverflow.com/questions/6462578/alternative-to-regex-match-all-instances-not-inside-quotes
		 */
		else if( code[2] != undefined && ( tmp[0] = code[2].match( /\{(?=([^"]*"[^"]*")*[^"]*$)/g ) || [] ).length != ( tmp[1] = code[2].match( /\}(?=([^"]*"[^"]*")*[^"]*$)/g ) || [] ).length )
		{
			throw new SyntaxError( 'Missing "' + ( tmp[0] < tmp[1] ? '{' : '}' ) + '" before the last identifier.', 'code', 0 );
		}

		var memory = {
			code:code,
			return:'',
			input:'',
			stack:[],
			registers:{R:0,I:0,P:0,L:0,Z:0},
			vars:{},
			output:''
		},

		/*All credits due to @BenAlpert (http://stackoverflow.com/users/49485/ben-alpert) for this implementation
		 *Original code: s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
		 *Also, the use @ledlogic (http://stackoverflow.com/users/987044/ledlogic) made a general rot# function:
		 *function rot(s,i){return s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+i)?c:c-26);});}
		 *The latest is available on http://jsfiddle.net/ledlogic/tC7qe/
		 */
		rot13 = function(s){return s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});},

		/*All credits due to @Jeff (http://stackoverflow.com/users/353278) for this function
		 *Original source: http://snippets.dzone.com/posts/show/849
		 *http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
		 */
		shuffle = function(o){
			for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
			return o;
		},

		//tries to parse or get a value from a piece of code
		fetchValue = function( code ){
			var currentChar = code.charAt(0), nextChar = code.charAt(1)
			switch( currentChar )
			{
				case '\'':
					return nextChar;

				case '"':
					if( ~code.indexOf('"',1) )
					{
						return code.substring(1, code.indexOf('"',1) );
					}
					else
					{
						throw new SyntaxError( 'Missing " before the end of the code', 'code', 0 );
					}
					break;

				case '|':
					if( /[a-zRIPLZ]/.test( nextChar ) && (memory.vars[nextChar] || nextChar in memory.registers) )
					{
						if( /^[a-z]$/.test( nextChar ) )
						{
							return memory.vars[nextChar];
						}
						else
						{
							return memory.registers[nextChar];
						}
					}
					else
					{
						throw new ReferenceError( 'Undefined register "'+nextChar+'"', 'code', 0 );
					}
					break;

				case '{':
					return runBlock( code );

				default:

					if( /[a-z\d]/.test(currentChar) )
					{
						return code.match( /(^[a-z\d]+)/ )[1] || 0;
					}
					else
					{
						return;
					}
			}

		},

		runBlock = function( block ){
			for( var i = 0, l = block.length, c, Return; i<l; i++)
			{
				memory.registers.P++;
				switch(c = block.charAt(i))
				{

					/*******Arithmetic*******/

					case '+':
						Return = (memory.registers.R / 1 || 0 ) + fetchValue( block.slice( i + 1 ) );
						break;
					case '/':
						Return = ( (memory.registers.R / 1 || 0 ) / fetchValue( block.slice( i + 1 ) ) ) >> 0;
						break;
					case '\\':
						Return = ( memory.registers.R / 1 || 0 ) % fetchValue( block.slice( i + 1 ) );
						break;
					case '-':
						Return = memory.registers.R - fetchValue( block.slice( i + 1 ) );
						break;
					case '^':
						Return = Math.pow( memory.registers.R, fetchValue( block.slice( i + 1 ) ) );
						break;
					case '«':
						Return = ( memory.registers.R / 1 || 0 ) << ( fetchValue( block.slice( i + 1 ) ) & 32 );
						break;
					case '»':
						Return = ( memory.registers.R / 1 || 0 ) >> ( fetchValue( block.slice( i + 1 ) ) & 32 );
						break;
					case '~':
						Return = ~ ( memory.registers.R / 1 || 0 );
						break;

					/*******   Stack   *******/
					case '.':
						memory.stack = [];
						memory.registers.L = memory.registers.R = 0;
						break;
					case '<':
						var tmp = fetchValue( block.slice( i + 1 ) );
						if( tmp / 1 == tmp / 1)
						{
							Return = memory.stack[memory.stack.length] = tmp >> 0;
						}
						else
						{
							Return = tmp;
							for(var j = 0, l = tmp.length; j<l; j++ )
							{
								memory.stack[memory.stack.length] = tmp.charAt(j);
							}
						}
						memory.registers.R = memory.stack[0];
						memory.registers.L = memory.stack.length;
						break;
				}
			}
		},

		outputHandler = window.console.log;

		return {
			run: function( input ){
				memory = {
					code:memory.code,
					return:'',
					input:input,
					stack:[],
					registers:{R:0,I:memory.code.index,P:0,L:0,Z:0},
					vars:{},
					output:''
				};

				var negative = true;

				for(var i = 0, l = memory.code[1].length, c; i<l; i++)
				{
					switch(c = memory.code[1].charAt(i))
					{
						case 'M': //loads all the characters to the stack
							memory.stack = (input || '').split('');break;
						case 'L': //same as M, but reverses
							memory.stack = input ? (input + '').reverse().split('') : [];break;
						case 'P': //disables negatives
							negative = false;break;
						case 'B': //EVERYTHING is a negative number
							memory.stack = [];
							if( input )
							{
								for(var j = 0, k = input.length; j<k; j++)
								{
									memory.stack[j] = -input.charAt(j);
								}
							}
							break;
						case 'T': //shuffles the stack
							memory.stack = shuffle( memory.stack );break;
						case 'Y':break; //empty stack
						case 'K': //places a quine into the stack
							memory.stack = memory.code[0].replace(/^\s+/,'').split('');break;
						default:
							throw new ReferenceError('Unknown identifier "'+c+'"');
					}
				}

				memory.registers.L = memory.stack.length;
				memory.registers.R = memory.stack[0] || 0;
				memory.registers.P = code[1].length + 1 ;

				if( memory.code[3].indexOf('Q') == -1 && memory.code[2] )
				{
					memory.return = runBlock( memory.code[2] );
				}

				if( 0 in memory.stack )
				{
					memory.stack[0] = memory.registers.R;
				}

				for(var i = 0, l = memory.code[3].length, c; i<l; i++)
				{
					switch(c = memory.code[3].charAt(i))
					{
						case '-': //destroy the return
							memory.return = undefined;
						case 'O': //display the content
							outputHandler.call( window.console, [memory.output = memory.stack.join('')] );break;
						case 'Q': //quine
							outputHandler.call( window.console, [memory.output = memory.code[0].replace(/^\s+/,'')] );break;
						case '|': //doesn't display anything, returns the stack
							memory.return = memory.stack;break;
						case '1': //displays the content as rot13
							outputHandler.call( window.console, [memory.output = rot13( memory.stack.join('') )] );break;
						case 'R': //displays reversed
							outputHandler.call( window.console, [memory.output = memory.stack.join('').split('').reverse().join('')] );break;
						case 'N': //outputs line by line, returns array
							outputHandler.call( window.console, [memory.output = memory.stack.join('').split('').join('\r\n')] );
							memory.return = memory.output.split('\r\n');break;
						case 'M': //outputs numbers line-by-line, returns array
							memory.return = [];
							if( memory.stack.length )
							{
								for(var j = 0, k = memory.stack.length; j<k; j++)
								{
									memory.return[j] = 'string' == typeof memory.stack[j] ? memory.stack[j] : String.fromCharCode(memory.stack[j]);
								}
							}
							outputHandler.call( window.console, [memory.output = memory.return.join('\r\n')] );break;
						default:
							throw new ReferenceError('Unknown identifier "'+c+'"');
					}
				}

				return memory.return;
			},
			getStack: function(){ return memory.stack; },
			getReturn: function(){ return memory.return; },
			getVars: function(){ return memory.vars; },
			getOutput: function(){ return memory.output; },
			getMemory: function(){ return memory; },
			setOutputHandler: function( fn ){
				if( fn instanceof window.Function)
				{
					outputHandler = fn;
					return true;
				}
				else
				{
					return false;
				}
			}
		};

	};

} )( Function('return this')() );
<|endoftext|>