<commit_before>/*
 * grunt-responsive-videos
 * https://github.com/sjwilliams/grunt-responsive-videos
 *
 * Based on the very handy grunt-responsive-images
 * by andismith: https://github.com/andismith/grunt-responsive-images
 * and ffmpeg-node by xonecase: https://github.com/xonecas/ffmpeg-node
 *
 * Copyright (c) 2013 Josh Williams
 * Licensed under the MIT license.
 */

'use strict';

var _ = require('underscore'),
    async = require('async'),
    path = require('path'),
    ffmpeg = require('ffmpeg-node');

module.exports = function(grunt) {

    var DEFAULT_OPTIONS = {
        separator: '-',
        sizes: [{
            name: 'small',
            width: 320,
            poster: true
        },{
            name: 'large',
            width: 640,
            poster: true
        }
        ],
        encodes:[{
            webm: [
                {'-vcodec': 'libvpx'},
                {'-acodec': 'libvorbis'},
                {'-crf': '12'},
                {'-q:a': '100'},
                {'-threads': '0'}
            ],
            mp4: [
                {'-vcodec':'libx264'},
                {'-acodec': 'libfaac'},
                {'-pix_fmt': 'yuv420p'},
                {'-q:v': '4'},
                {'-q:a': '100'},
                {'-threads': '0'}
            ]
        }]
    };

    // check if there are any items in our array
    function isValidArray(obj) {
        return (_.isArray(obj) && obj.length > 0);
    }

    // check whether we've been given any valid size values
    function isValidSize(obj) {
        return (_.isNumber(obj.width) && obj.width%2===0);
    }

    // create a name to suffix to our file.
    function getName(name, width, separator) {

        // handle empty separator as no separator
        if (typeof separator === 'undefined') {
            separator = '';
        }

        if (name) {
            return separator + name;
        } else {
            return separator + width;
        }
    }

    grunt.registerMultiTask('responsive_videos', 'Videos at various responsive sizes', function() {

        // Merge task-specific and/or target-specific options with these defaults.
        var that = this;
        var done = this.async();
        var series = [];
        var options = this.options(DEFAULT_OPTIONS);
        var sizeTally = {};  // track number of files per size
        var encodeTally = {}; // track number of files by codec
        var count = 0; // track total number of files

        if (!isValidArray(options.sizes)) {
            return grunt.fail.warn('No sizes have been defined.');
        }

        // build encode settings for each size
        options.sizes.forEach(function(size) {

            if (!isValidSize(size)) {
                return grunt.fail.warn('Width is invalid. It must be an integer and divisible by 2 (libx264 requirement)');
            }

            // create a name suffix for our image
            size.name = getName(size.name, size.width, options.separator);

            sizeTally[size.name] = 0;

            // build encode settings for each input file
            that.files.forEach(function(f) {
                var extName = path.extname(f.dest),
                    srcPath = f.src[0],
                    baseName = path.basename(srcPath, extName), // filename without extension
                    dirName = path.dirname(f.dest),
                    dstPath = path.join(dirName, baseName + size.name),
                    posterPath = dstPath + '.jpg';

                // more than 1 source.
                if (f.src.length > 1) {
                    return grunt.fail.warn('Unable to encode more than one video in compact or files object format.\n' +
                        'For multiple files please use the files array format.\nSee http://gruntjs.com/configuring-tasks');
                }

                // Make directory if it doesn't exist.
                if (!grunt.file.isDir(dirName)) {
                    grunt.file.mkdir(dirName);
                }

                // queue poster creation
                if (size.poster) {
                    series.push(function(callback){
                        var flags = [];
                        flags.push('-i', srcPath);
                        flags.push('-vframes', '1');
                        flags.push('-vf', 'scale='+size.width+':-1');
                        flags.push(posterPath);
                        ffmpeg.exec(flags, function(error, info) {
                            grunt.verbose.ok('Responsive Video: ' + srcPath + ' now ' + posterPath);
                            return callback();
                        });
                    });
                }

                // generate encode settings for each output encode type
                options.encodes.forEach(function(encodeSettings){
                    _.each(encodeSettings, function(codecSettings, codecName){
                        var outPath = dstPath + '.' + codecName;

                        if (encodeTally[codecName]) {
                            encodeTally[codecName]++;
                        } else {
                            encodeTally[codecName] = 1;
                        }

                        // build up flags array ffmpeg-node expects.
                        // ex: ['-i', srcPath, '-vcodec', 'libx264', '-acodec', 'libfaac', '-pix_fmt', 'yuv420p', '-q:v', '4',  '-q:a', '100', '-threads', '0', dstPath]
                        var flags = [];

                        // input file first
                        flags.push('-i', srcPath);

                        // encode settings next
                        _.each(codecSettings, function(codecSetting){
                            for (var key in codecSetting){
                                flags.push(key,codecSetting[key]);
                            }
                        });

                        // set size
                        flags.push('-vf', 'scale='+size.width+':-1');

                        // output file
                        flags.push(outPath);

                        // if an output file already exist, delete it.
                        // ffmpeg-node fails otherwise
                        if (grunt.file.exists(outPath)) {
                            grunt.file.delete(outPath);
                        }

                        // update tallies
                        sizeTally[size.name]++;
                        count++;

                        // queue encode jobs
                        series.push(function(callback){
                            ffmpeg.exec(flags, function(error, info) {
                                // if (error) {
                                //     grunt.fail.warn(error.message);
                                // } else {
                                //     grunt.verbose.ok('Responsive Video: ' + srcPath + ' now ' + outPath);
                                // }
                                // console.log(error);
                                grunt.verbose.ok('Responsive Video: ' + srcPath + ' now ' + outPath);
                                return callback();
                            });
                        });

                    });

                    series.push(function(callback) {
                        if (sizeTally[size.name]) {
                            grunt.log.writeln('Created ' + sizeTally[size.name].toString().cyan + ' files for size ' + size.name);
                        }
                        return callback();
                    });
                });
            });
        });

        grunt.log.writeln('Starting ' + count.toString().cyan + ' encodes jobs.');

        // run encode jobs async
        async.series(series, done);
    });
};<commit_msg>task cleanup<commit_after>/*
 * grunt-responsive-videos
 * https://github.com/sjwilliams/grunt-responsive-videos
 *
 * Based on the very handy grunt-responsive-images
 * by andismith: https://github.com/andismith/grunt-responsive-images
 * and ffmpeg-node by xonecase: https://github.com/xonecas/ffmpeg-node
 *
 * Copyright (c) 2013 Josh Williams
 * Licensed under the MIT license.
 */

'use strict';

var _ = require('underscore'),
    async = require('async'),
    path = require('path'),
    ffmpeg = require('ffmpeg-node');

module.exports = function(grunt) {

    var DEFAULT_OPTIONS = {
        separator: '-',
        sizes: [{
            name: 'small',
            width: 320,
            poster: true
        },{
            name: 'large',
            width: 640,
            poster: true
        }
        ],
        encodes:[{
            webm: [
                {'-vcodec': 'libvpx'},
                {'-acodec': 'libvorbis'},
                {'-crf': '12'},
                {'-q:a': '100'},
                {'-threads': '0'}
            ],
            mp4: [
                {'-vcodec':'libx264'},
                {'-acodec': 'libfaac'},
                {'-pix_fmt': 'yuv420p'},
                {'-q:v': '4'},
                {'-q:a': '100'},
                {'-threads': '0'}
            ]
        }]
    };

    // check if there are any items in our array
    function isValidArray(obj) {
        return (_.isArray(obj) && obj.length > 0);
    }

    // check whether we've been given any valid size values
    function isValidSize(obj) {
        return (_.isNumber(obj.width) && obj.width%2===0);
    }

    // create a name to suffix to our file.
    function getName(name, width, separator) {

        // handle empty separator as no separator
        if (typeof separator === 'undefined') {
            separator = '';
        }

        if (name) {
            return separator + name;
        } else {
            return separator + width;
        }
    }

    grunt.registerMultiTask('responsive_videos', 'Videos at various responsive sizes', function() {
        var that = this;

        // Merge task-specific and/or target-specific options with these defaults.
        var done = this.async();
        var series = [];
        var options = this.options(DEFAULT_OPTIONS);
        var sizeTally = {};  // track number of files per size
        var encodeTally = {}; // track number of files by codec
        var count = 0; // track total number of files

        if (!isValidArray(options.sizes)) {
            return grunt.fail.warn('No sizes have been defined.');
        }

        // build encode settings for each size
        options.sizes.forEach(function(size) {

            if (!isValidSize(size)) {
                return grunt.fail.warn('Width is invalid. It must be an integer and divisible by 2 (libx264 requirement)');
            }

            // create a name suffix for our image
            size.name = getName(size.name, size.width, options.separator);

            sizeTally[size.name] = 0;

            // build encode settings for each input file
            that.files.forEach(function(f) {
                var extName = path.extname(f.dest),
                    srcPath = f.src[0],
                    baseName = path.basename(srcPath, extName), // filename without extension
                    dirName = path.dirname(f.dest),
                    dstPath = path.join(dirName, baseName + size.name),
                    posterPath = dstPath + '.jpg';

                // more than 1 source.
                if (f.src.length > 1) {
                    return grunt.fail.warn('Unable to encode more than one video in compact or files object format.\n' +
                        'For multiple files please use the files array format.\nSee http://gruntjs.com/configuring-tasks');
                }

                // Make directory if it doesn't exist.
                if (!grunt.file.isDir(dirName)) {
                    grunt.file.mkdir(dirName);
                }

                // queue poster creation
                if (size.poster) {
                    series.push(function(callback){
                        var flags = [];
                        flags.push('-i', srcPath);
                        flags.push('-vframes', '1');
                        flags.push('-vf', 'scale='+size.width+':-1');
                        flags.push(posterPath);
                        ffmpeg.exec(flags, function() {
                            grunt.verbose.ok('Responsive Video: ' + srcPath + ' now ' + posterPath);
                            return callback();
                        });
                    });
                }

                // generate encode settings for each output encode type
                options.encodes.forEach(function(encodeSettings){
                    _.each(encodeSettings, function(codecSettings, codecName){
                        var outPath = dstPath + '.' + codecName;

                        if (encodeTally[codecName]) {
                            encodeTally[codecName]++;
                        } else {
                            encodeTally[codecName] = 1;
                        }

                        // build up flags array ffmpeg-node expects.
                        // ex: ['-i', srcPath, '-vcodec', 'libx264', '-acodec', 'libfaac', '-pix_fmt', 'yuv420p', '-q:v', '4',  '-q:a', '100', '-threads', '0', dstPath]
                        var flags = [];

                        // input file first
                        flags.push('-i', srcPath);

                        // encode settings next
                        _.each(codecSettings, function(codecSetting){
                            for (var key in codecSetting){
                                flags.push(key,codecSetting[key]);
                            }
                        });

                        // set size
                        flags.push('-vf', 'scale='+size.width+':-1');

                        // output file
                        flags.push(outPath);

                        // if an output file already exist, delete it.
                        // ffmpeg-node fails otherwise
                        if (grunt.file.exists(outPath)) {
                            grunt.file.delete(outPath);
                        }

                        // update tallies
                        sizeTally[size.name]++;
                        count++;

                        // queue encode jobs
                        series.push(function(callback){
                            ffmpeg.exec(flags, function() {
                                grunt.verbose.ok('Responsive Video: ' + srcPath + ' now ' + outPath);
                                return callback();
                            });
                        });

                    });

                    series.push(function(callback) {
                        if (sizeTally[size.name]) {
                            grunt.log.writeln('Created ' + sizeTally[size.name].toString().cyan + ' files for size ' + size.name);
                        }
                        return callback();
                    });
                });
            });
        });

        grunt.log.writeln('Starting ' + count.toString().cyan + ' encodes jobs.');

        // run encode jobs async
        async.series(series, done);
    });
};<|endoftext|>


<commit_before>/*
 * grunt-ts-reference-file
 * https://github.com/ufon/ts-reference-file
 *
 * Copyright (c) 2013 Václav Oborník
 * Licensed under the MIT license.
 */

var path = require("path");
var fs = require("fs");
var os = require("os");
var _ = require('underscore');
var _str = require('underscore.string');
var eol = os.EOL;
var pathSeperator = path.sep;

module.exports = function (grunt) {

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

  /**
   * Returns the result of an array inserted into another, starting at the given index.
   */
  function insertArrayAt(array, index, arrayToInsert) {
    var updated = array.slice(0);
    Array.prototype.splice.apply(updated, [index, 0].concat(arrayToInsert));
    return updated;
  }

  // Useful string functions
  // used to make sure string ends with a slash
  function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  }

  function endWithSlash(path) {
    if (!endsWith(path, '/') && !endsWith(path, '\\')) {
      return path + '/';
    }
    return path;
  }

  grunt.registerTask('tsReferenceFile', '', function () {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options();

    // Create a reference file?
    var reference = options.dest;
    var referenceFile;
    var referencePath;
    if (!!reference) {
      referenceFile = path.resolve(reference);
      referencePath = path.dirname(referenceFile);
    }
    function isReferenceFile(filename) {
      return path.resolve(filename) == referenceFile;
    }

    var files = grunt.file.expand(options.src);
    if(options.exclude) {
      files = _.difference(files, grunt.file.expand(options.exclude));
    }

    // ignore directories
    files = files.filter(function (file) {
      var stats = fs.lstatSync(file);
      return !stats.isDirectory();
    });

    // Clear the files of output.d.ts and reference.ts
    files = _.filter(files, function (filename) {
      return (!isReferenceFile(filename) && !endsWith(filename, 'd.td'));
    });

    updateReferenceFile(files, referenceFile, referencePath);

    // Converts "C:\boo" , "C:\boo\foo.ts" => "./foo.ts"; Works on unix as well.
    function makeReferencePath(folderpath, filename) {
      return path.relative(folderpath, filename).split('\\').join('/');
    }

    // Updates the reference file
    function updateReferenceFile(files, referenceFile, referencePath) {
      var referenceIntro = '/// <reference path="';
      var referenceEnd = '" />';
      var referenceMatch = /\/\/\/ <reference path=\"(.*?)\"/;
      var ourSignatureStart = '//grunt-start';
      var ourSignatureEnd = '//grunt-end';

      var lines = []; // All lines of the file
      var origFileLines = []; // The lines we do not modify and send out as is. Lines will we reach grunt-ts generated
      var origFileReferences = []; // The list of files already there that we do not need to manage

      // Location of our generated references
      // By default at start of file
      var signatureSectionPosition = 0;

      // Read the original file if it exists
      if (fs.existsSync(referenceFile)) {
        lines = fs.readFileSync(referenceFile).toString().split('\n');

        var inSignatureSection = false;

        // By default our signature goes at end of file
        signatureSectionPosition = lines.length;

        for (var i = 0; i < lines.length; i++) {

          var line = _str.trim(lines[i]);

          // Skip logic for our generated section
          if (_str.include(line, ourSignatureStart)) {
            //Wait for the end signature:
            signatureSectionPosition = i;
            inSignatureSection = true;
            continue;
          }
          if (_str.include(line, ourSignatureEnd)) {
            inSignatureSection = false;
            continue;
          }
          if (inSignatureSection) continue;

          // store the line
          origFileLines.push(line);

          // Fetch the existing reference's filename if any:
          if (_str.include(line, referenceIntro)) {
            var match = line.match(referenceMatch);
            var filename = match[1];
            origFileReferences.push(filename);
          }
        }
      }

      // Put in the generated files
      var generatedFiles = _.map(generatedFiles, function (file) {
        return referenceIntro + makeReferencePath(referencePath, file) + referenceEnd + generatedSignature;
      });
      var contents = insertArrayAt([ourSignatureStart], 1, generatedFiles);

      // Put in the new / observed missing files:
      files.forEach(function (filename) {
        // The file we are about to add
        var filepath = makeReferencePath(referencePath, filename);

        // If there are orig references
        if (origFileReferences.length) {
          if (_.contains(origFileReferences, filepath)) {
            return;
          }
        }

        // Finally add the filepath
        contents.push(referenceIntro + filepath + referenceEnd);
      });
      contents.push(ourSignatureEnd);

      // Modify the orig contents to put in our contents
      var updatedFileLines = insertArrayAt(origFileLines, signatureSectionPosition, contents);
      fs.writeFileSync(referenceFile, updatedFileLines.join(eol));

      // Return whether the file was changed
      if (lines.length == updatedFileLines.length) {
        var updated = false;
        for (var i = 0; i < lines.length; i++) {
          if (lines[i] != updatedFileLines[i]) {
            updated = true;
          }
        }
        return updated;
      }
      else {
        return true;
      }
    }
  });
}
<commit_msg>task to multiTask<commit_after>/*
 * grunt-ts-reference-file
 * https://github.com/ufon/ts-reference-file
 *
 * Copyright (c) 2013 Václav Oborník
 * Licensed under the MIT license.
 */

var path = require("path");
var fs = require("fs");
var os = require("os");
var _ = require('underscore');
var _str = require('underscore.string');
var eol = os.EOL;
var pathSeperator = path.sep;

module.exports = function (grunt) {

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

  /**
   * Returns the result of an array inserted into another, starting at the given index.
   */
  function insertArrayAt(array, index, arrayToInsert) {
    var updated = array.slice(0);
    Array.prototype.splice.apply(updated, [index, 0].concat(arrayToInsert));
    return updated;
  }

  // Useful string functions
  // used to make sure string ends with a slash
  function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  }

  function endWithSlash(path) {
    if (!endsWith(path, '/') && !endsWith(path, '\\')) {
      return path + '/';
    }
    return path;
  }

  grunt.registerMultiTask('tsReferenceFile', '', function () {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options();

    // Create a reference file?
    var reference = options.dest;
    var referenceFile;
    var referencePath;
    if (!!reference) {
      referenceFile = path.resolve(reference);
      referencePath = path.dirname(referenceFile);
    }
    function isReferenceFile(filename) {
      return path.resolve(filename) == referenceFile;
    }

    var files = grunt.file.expand(options.src);
    if(options.exclude) {
      files = _.difference(files, grunt.file.expand(options.exclude));
    }

    // ignore directories
    files = files.filter(function (file) {
      var stats = fs.lstatSync(file);
      return !stats.isDirectory();
    });

    // Clear the files of output.d.ts and reference.ts
    files = _.filter(files, function (filename) {
      return (!isReferenceFile(filename) && !endsWith(filename, 'd.td'));
    });

    updateReferenceFile(files, referenceFile, referencePath);

    // Converts "C:\boo" , "C:\boo\foo.ts" => "./foo.ts"; Works on unix as well.
    function makeReferencePath(folderpath, filename) {
      return path.relative(folderpath, filename).split('\\').join('/');
    }

    // Updates the reference file
    function updateReferenceFile(files, referenceFile, referencePath) {
      var referenceIntro = '/// <reference path="';
      var referenceEnd = '" />';
      var referenceMatch = /\/\/\/ <reference path=\"(.*?)\"/;
      var ourSignatureStart = '//grunt-start';
      var ourSignatureEnd = '//grunt-end';

      var lines = []; // All lines of the file
      var origFileLines = []; // The lines we do not modify and send out as is. Lines will we reach grunt-ts generated
      var origFileReferences = []; // The list of files already there that we do not need to manage

      // Location of our generated references
      // By default at start of file
      var signatureSectionPosition = 0;

      // Read the original file if it exists
      if (fs.existsSync(referenceFile)) {
        lines = fs.readFileSync(referenceFile).toString().split('\n');

        var inSignatureSection = false;

        // By default our signature goes at end of file
        signatureSectionPosition = lines.length;

        for (var i = 0; i < lines.length; i++) {

          var line = _str.trim(lines[i]);

          // Skip logic for our generated section
          if (_str.include(line, ourSignatureStart)) {
            //Wait for the end signature:
            signatureSectionPosition = i;
            inSignatureSection = true;
            continue;
          }
          if (_str.include(line, ourSignatureEnd)) {
            inSignatureSection = false;
            continue;
          }
          if (inSignatureSection) continue;

          // store the line
          origFileLines.push(line);

          // Fetch the existing reference's filename if any:
          if (_str.include(line, referenceIntro)) {
            var match = line.match(referenceMatch);
            var filename = match[1];
            origFileReferences.push(filename);
          }
        }
      }

      // Put in the generated files
      var generatedFiles = _.map(generatedFiles, function (file) {
        return referenceIntro + makeReferencePath(referencePath, file) + referenceEnd + generatedSignature;
      });
      var contents = insertArrayAt([ourSignatureStart], 1, generatedFiles);

      // Put in the new / observed missing files:
      files.forEach(function (filename) {
        // The file we are about to add
        var filepath = makeReferencePath(referencePath, filename);

        // If there are orig references
        if (origFileReferences.length) {
          if (_.contains(origFileReferences, filepath)) {
            return;
          }
        }

        // Finally add the filepath
        contents.push(referenceIntro + filepath + referenceEnd);
      });
      contents.push(ourSignatureEnd);

      // Modify the orig contents to put in our contents
      var updatedFileLines = insertArrayAt(origFileLines, signatureSectionPosition, contents);
      fs.writeFileSync(referenceFile, updatedFileLines.join(eol));

      // Return whether the file was changed
      if (lines.length == updatedFileLines.length) {
        var updated = false;
        for (var i = 0; i < lines.length; i++) {
          if (lines[i] != updatedFileLines[i]) {
            updated = true;
          }
        }
        return updated;
      }
      else {
        return true;
      }
    }
  });
}
<|endoftext|>


<commit_before>import Head from 'components/head';
import Layout from 'components/Layout';
import Spacer from 'components/Spacer';
import getWallpapers from 'lib/get-wallpapers';
import Router from 'next/router';

const Blog = ({ walls }) => {
  return (
    <>

        <title>Wallpapers | Reaper</title>

      <Layout>

            {walls.map(({ name, link }, index) => {
              return (

                  <a
                    className="flex flex-col just-center align-center"
                    target="_blank"
                    href={`/wallpapers/${link}`}
                  >
                    <img src={`/wallpapers/${link}`} />
                    {name}

              );
            })}

          <Spacer y={1}></Spacer>
          <button
            className="margin-top-sm  align-start button black outline-btn"
            onClick={() => Router.push('/')}
          >
            Back
          </button>
          <Spacer y={2}></Spacer>

      </Layout>

    </>
  );
};

export async function getStaticProps() {
  const walls = await getWallpapers();
  return {
    props: {
      walls,
    },
  };
}

export default Blog;
<commit_msg>fix for mobile responsive<commit_after>import Head from 'components/head';
import Layout from 'components/Layout';
import Spacer from 'components/Spacer';
import getWallpapers from 'lib/get-wallpapers';
import Router from 'next/router';

const Blog = ({ walls }) => {
  return (
    <>

        <title>Wallpapers | Reaper</title>

      <Layout>

            {walls.map(({ name, link }, index) => {
              return (

                  <a
                    className="flex flex-col just-center align-center"
                    target="_blank"
                    href={`/wallpapers/${link}`}
                  >
                    <img src={`/wallpapers/${link}`} />
                    {name}

              );
            })}

          <Spacer y={1}></Spacer>
          <button
            className="margin-top-sm  align-start button black outline-btn"
            onClick={() => Router.push('/')}
          >
            Back
          </button>
          <Spacer y={2}></Spacer>

      </Layout>

    </>
  );
};

export async function getStaticProps() {
  const walls = await getWallpapers();
  return {
    props: {
      walls,
    },
  };
}

export default Blog;
<|endoftext|>


<commit_before>var argv = require('minimist')(process.argv);
var fs = require('fs');
var joinPath = require('path').join;

var log = console.log.bind(console);
var warn = console.warn.bind(console);

var logLevels = require('../../logging').logLevels;

var KiteServer = require('../../server');

var math = new KiteServer({
  name:         'math',
  username:     'koding',
  environment:  'vagrant',
  region:       'vagrant',
  version:      '1.0.0',
  api: {

    square: function (x, callback) {
      callback(null, x * x);
    }

  },
  logLevel: argv.v ? logLevels.DEBUG : logLevels.INFO
});

math.listen(5647);

var registationIp = require('../fetch-registration-ip.js')(argv.c ? argv.c : 'vagrant');

var kiteKey = fs.createReadStream(joinPath(__dirname, './kite.key'), 'utf-8');

math.register('ws://localhost:4000', registationIp, kiteKey);
<commit_msg>move var statements to the top<commit_after>var argv = require('minimist')(process.argv);
var fs = require('fs');
var joinPath = require('path').join;

var log = console.log.bind(console);
var warn = console.warn.bind(console);

var registationIp = require('../fetch-registration-ip.js')(argv.c || 'vagrant');

var kiteKey = fs.createReadStream(joinPath(__dirname, './kite.key'), 'utf-8');

var logLevels = require('../../logging').logLevels;

var KiteServer = require('../../server');

var math = new KiteServer({
  name:         'math',
  username:     'koding',
  environment:  'vagrant',
  region:       'vagrant',
  version:      '1.0.0',
  api: {

    square: function (x, callback) {
      callback(null, x * x);
    }

  },
  logLevel: argv.v ? logLevels.DEBUG : logLevels.INFO
});

math.listen(5647);

math.register('ws://localhost:4000', registationIp, kiteKey);
<|endoftext|>


<commit_before>/**
 * yii2-dynamic-form
 *
 * A jQuery plugin to clone form elements in a nested manner, maintaining accessibility.
 *
 * @author Wanderson Bragança <wanderson.wbc@gmail.com>
 */
(function ($) {
    var pluginName = 'yiiDynamicForm';
    $.fn.yiiDynamicForm = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.yiiDynamicForm');
            return false;
        }
    };

    var events = {
        beforeClone: 'beforeClone',
        afterClone: 'afterClone',
        limitReached: 'limitReached',
        afterRemove: 'afterRemove'
    };

    var defaults = {
        // the maximum times, an element can be cloned
        limit: 999, //setting it to a high number, by default
        min: 1,
        dynamicItems: '.dynamic-items',
        dynamicItem: '.dynamic-item',
        cloneButton: '.clone',
        deleteButton: '.delete',
        clonePosition: 'after', // or 'before'
        template: false
    };

    var regex = /(.*-)(\d)(-.*)/i;

    var methods = {
        init: function (options) {
            return this.each(function () {
                var $container = $(this);

                var data = $container.data(pluginName);
                if (!data) {
                    var settings = $.extend({}, defaults, options || {});

                    settings.fields.forEach(function(attribute) {
                        var yiiActiveFormAttribute = $("#" + settings.formId).yiiActiveForm("find", attribute.id.replace("{}", 0));
                        if (yiiActiveFormAttribute !== undefined) {
                           attribute.baseConfig = yiiActiveFormAttribute;
                        }
                    });

                    $container.data(pluginName, {
                        target : $container,
                        settings: settings
                    });

                    if ($container.find(settings.cloneButton).length) {
                        // add a click handler for the clone button
                        $container.on('click', settings.cloneButton, function(event) {
                            event.preventDefault();
                            $container.triggerHandler(events.beforeClone, [$(this)]);
                            startClone(event, $(this), $container);
                        });
                    }

                    $container.on('click', settings.deleteButton, function(event) {
                        event.preventDefault();
                        removeItem($container, $(this));
                    });

                    if ($container.find(settings.dynamicItem).length === 0) {
                        settings.fields.forEach(function(attribute) {
                            var id = attribute.id.replace("{}", 0);
                            if ($("#" + settings.formId).yiiActiveForm("find", id) !== undefined) {
                               $("#" + settings.formId).yiiActiveForm("remove", id);
                            }
                        });
                    }
                }
            });
        },

        updateContainer: function () {
            var $container = $(this);
            redoIDs($container);
            restoreSpecialJs($container);
            fixFormValidaton($container);
        }
    };

    var startClone = function(event, $btnAdd, $container) {
        var config = $container.data(pluginName).settings;

        // get the count of all the clones
        var cloneCount = $container.find(config.dynamicItem).length;
        // check if we've reached the maximum limit
        if (cloneCount < config.limit) {
            $toclone = $($(config.template).html());
            // clone it
            $newclone = $toclone.clone(false, false);
            $newclone.find('input, textarea, select').each(function() {
                $(this).val('');
            });
            if (config.clonePosition != 'after') {
                $(config.dynamicItems).prepend($newclone);
            } else {
                $(config.dynamicItems).append($newclone);
            }
            redoIDs($container);
            removeErrorCssClass($newclone);
            restoreSpecialJs($container);
            fixFormValidaton($container);
            $container.triggerHandler(events.afterClone, $newclone);
        } else {
            // trigger a custom event for hooking
            $container.triggerHandler(events.limitReached, config.limit);
        }
    };

    var fixFormValidaton = function($container) {
        var config = $container.data(pluginName).settings;
        $(config.dynamicItem).each(function(i) {
            config.fields.forEach(function(v) {
                var id = v.id.replace("{}", i);
                var attribute = v.baseConfig;
                if (attribute !== undefined) {
                    attribute = $.extend(true, {}, attribute);
                    attribute.id = id;
                    attribute.container = ".field-" + id;
                    attribute.input = "#" + id;
                    attribute.name = v.name.replace("{}", i);
                    attribute.value = $("#" + id).val();
                    attribute.status = 0;
                    if ($("#" + config.formId).yiiActiveForm("find", id) !== "undefined") {
                        $("#" + config.formId).yiiActiveForm("remove", id);
                    }
                    $("#" + config.formId).yiiActiveForm("add", attribute);
                }
            });
        });
    };

    var removeItem = function($container, $item) {
        var config = $container.data(pluginName).settings;
        var cloneCount = $container.find(config.dynamicItem).length;
        if (cloneCount > config.min) {
            // get the closest parent clone
            $todelete = $item.closest(config.dynamicItem);
            $todelete.remove();
            redoIDs($container);
            restoreSpecialJs($container);
            fixFormValidaton($container);
            if (cloneCount > 0) {
                config.fields.forEach(function(v) {
                    var id = v.id.replace("{}", (cloneCount - 1));
                    if ($("#" + config.formId).yiiActiveForm("find", id) !== "undefined") {
                        $("#" + config.formId).yiiActiveForm("remove", id);
                    }
                });
            }
            $container.triggerHandler(events.afterRemove);
        }
    }

    var removeErrorCssClass = function($container) {
        $container.find('.has-success').each(function() {
            $(this).removeClass('has-success');
        });
        $container.find('.has-error').each(function() {
            $(this).removeClass('has-error');
        });
    };

    var restoreSpecialJs = function($container) {
        var config = $container.data(pluginName).settings;

        // "kartik-v/yii2-widget-datepicker"
        var $hasDatepicker = $(config.dynamicItems).find('[data-krajee-datepicker]');
        if ($hasDatepicker.length > 0) {
            $hasDatepicker.each(function() {
                $(this).parent().removeData().datepicker('remove');
                $(this).parent().datepicker(eval($(this).attr('data-krajee-datepicker')));
            });
        }

        // "kartik-v/yii2-widget-timepicker"
        var $hasTimepicker = $(config.dynamicItems).find('[data-krajee-timepicker]');
        if ($hasTimepicker.length > 0) {
            $hasTimepicker.each(function() {
                $(this).removeData().off();
                $(this).parent().find('.bootstrap-timepicker-widget').remove();
                $(this).unbind();
                $(this).timepicker(eval($(this).attr('data-krajee-timepicker')));
            });
        }

        // "kartik-v/yii2-money"
        var $hasMaskmoney = $(config.dynamicItems).find('[data-krajee-maskMoney]');
        if ($hasMaskmoney.length > 0) {
            $hasMaskmoney.each(function() {
                $(this).parent().find('input').removeData().off();
                var id = '#' + $(this).attr('id');
                var displayID  = id + '-disp';
                $(displayID).maskMoney('destroy');
                $(displayID).maskMoney(eval($(this).attr('data-krajee-maskMoney')));
                $(displayID).maskMoney('mask', parseFloat($(displayID).val()));
                $(displayID).on('change', function () {
                    var numDecimal = $(displayID).maskMoney('unmasked')[0];
                    $(id).val(numDecimal);
                    $(id).trigger('change');
                });
            });
        }

        // "kartik-v/yii2-widget-fileinput"
        var $hasFileinput = $(config.dynamicItems).find('[data-krajee-fileinput]');
        if ($hasFileinput.length > 0) {
            $hasFileinput.each(function() {
                $(this).fileinput(eval($(this).attr('data-krajee-fileinput')));
            });
        }

        // "kartik-v/yii2-widget-touchspin"
        var $hasTouchSpin = $(config.dynamicItems).find('[data-krajee-TouchSpin]');
        if ($hasTouchSpin.length > 0) {
            $hasTouchSpin.each(function() {
                $(this).TouchSpin('destroy');
                $(this).TouchSpin(eval($(this).attr('data-krajee-TouchSpin')));
            });
        }

        // "kartik-v/yii2-widget-colorinput"
        var $hasSpectrum = $(config.dynamicItems).find('[data-krajee-spectrum]');
        if ($hasSpectrum.length > 0) {
            $hasSpectrum.each(function() {
                var id = '#' + $(this).attr('id');
                var sourceID  = id + '-source';
                $(sourceID).spectrum('destroy');
                $(sourceID).unbind();
                $(id).unbind();
                var configSpectrum = eval($(this).attr('data-krajee-spectrum'));
                configSpectrum.change = function (color) {
                    jQuery(id).val(color.toString());
                };
                $(sourceID).attr('name', $(sourceID).attr('id'));
                $(sourceID).spectrum(configSpectrum);
                $(sourceID).spectrum('set', jQuery(id).val());
                $(id).on('change', function(){
                    $(sourceID).spectrum('set', jQuery(id).val());
                });
            });
        }

        // "kartik-v/yii2-widget-depdrop"
        var $hasDepdrop = $(config.dynamicItems).find('[data-krajee-depdrop]');
        if ($hasDepdrop.length > 0) {
            $hasDepdrop.each(function() {
                $(this).removeData().off();
                $(this).unbind();
                var configDepdrop = eval($(this).attr('data-krajee-depdrop'));
                var inputID = $(this).attr('id');
                var matchID = inputID.match(regex);
                if (matchID && matchID.length === 4) {
                    for (index = 0; index < configDepdrop.depends.length; ++index) {
                        var match = configDepdrop.depends[index].match(regex);
                        if (match && match.length === 4) {
                            configDepdrop.depends[index] = match[1] + matchID[2] + match[3];
                        }
                    }
                }
                $(this).depdrop(configDepdrop);
            });
        }

        // "kartik-v/yii2-widget-select2"
        var $hasSelect2 = $(config.dynamicItems).find('[data-krajee-select2]');
        if ($hasSelect2.length > 0) {
            $hasSelect2.each(function() {
                var id = $(this).attr('id');
                var configSelect2 = eval($(this).attr('data-krajee-select2'));
                $(this).select2('destroy');
                $.when($('#' + id).select2(configSelect2)).done(initSelect2Loading(id));
                $('#' + id).on('select2-open', function() {
                    initSelect2DropStyle(id)
                });
                if ($(this).attr('data-krajee-depdrop')) {
                    $(this).on('depdrop.beforeChange', function(e,i,v) {
                        var configDepdrop = eval($(this).attr('data-krajee-depdrop'));
                        var loadingText = (configDepdrop.loadingText)? configDepdrop.loadingText : 'Loading ...';
                        $('#' + id).select2('data', {text: loadingText});
                    });
                    $(this).on('depdrop.change', function(e,i,v,c) {
                        $('#' + id).select2('val', $('#' + id).val());
                    });
                }
            });
        }
    };

    var redoIDs = function($container) {
        var config = $container.data(pluginName).settings;
        $container.find(config.dynamicItem).each(function(i) {
            // first modify the clone id
            var j = i;
            var $obj = $(this);
            $(this).find('*').each(function() {
                var id = $(this).attr('id');
                if (id) {
                    var newID = id;
                    var match = id.match(regex);
                    if (match && match.length === 4) {
                        newID = match[1] + i + match[3];
                        $(this).attr('id', newID);
                    } else {
                        newID = id + i;
                        $(this).attr('id', newID);
                    }
                    if (id !== newID) {
                        $obj.find('.field-' + id).each(function() {
                            $(this).removeClass('field-' + id).addClass('field-' + newID);
                        });
                    }
                }
                // "for" attribute
                var elmLabel = $(this).attr('for');
                if (elmLabel) {
                    var match = elmLabel.match(regex);
                    if (match && match.length === 4) {
                        $(this).attr('for', match[1] + i + match[3]);
                    } else {
                        $(this).attr('for', elmLabel + i);
                    }
                }
                // "name" attribute
                var name = $(this).attr('name');
                // This will increment the numeric array index for cloned field names
                if (name) {
                    var matches = name.match(/\[([^}]+)\]/);
                    if (matches && matches.length >= 1) {
                        var st = name;
                        name = [].map.call(st, function(s, i) {
                            return (!isNaN(+s) && st[i - 1] === '[' && st[i + 1] === ']') ? j : s;
                        }).join('');
                        $(this).attr('name', name);
                    }
                }
            });
        });
    };

})(window.jQuery);
<commit_msg>Fix for currency format € xx,xx<commit_after>/**
 * yii2-dynamic-form
 *
 * A jQuery plugin to clone form elements in a nested manner, maintaining accessibility.
 *
 * @author Wanderson Bragança <wanderson.wbc@gmail.com>
 */
(function ($) {
    var pluginName = 'yiiDynamicForm';
    $.fn.yiiDynamicForm = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.yiiDynamicForm');
            return false;
        }
    };

    var events = {
        beforeClone: 'beforeClone',
        afterClone: 'afterClone',
        limitReached: 'limitReached',
        afterRemove: 'afterRemove'
    };

    var defaults = {
        // the maximum times, an element can be cloned
        limit: 999, //setting it to a high number, by default
        min: 1,
        dynamicItems: '.dynamic-items',
        dynamicItem: '.dynamic-item',
        cloneButton: '.clone',
        deleteButton: '.delete',
        clonePosition: 'after', // or 'before'
        template: false
    };

    var regex = /(.*-)(\d)(-.*)/i;

    var methods = {
        init: function (options) {
            return this.each(function () {
                var $container = $(this);

                var data = $container.data(pluginName);
                if (!data) {
                    var settings = $.extend({}, defaults, options || {});

                    settings.fields.forEach(function(attribute) {
                        var yiiActiveFormAttribute = $("#" + settings.formId).yiiActiveForm("find", attribute.id.replace("{}", 0));
                        if (yiiActiveFormAttribute !== undefined) {
                           attribute.baseConfig = yiiActiveFormAttribute;
                        }
                    });

                    $container.data(pluginName, {
                        target : $container,
                        settings: settings
                    });

                    if ($container.find(settings.cloneButton).length) {
                        // add a click handler for the clone button
                        $container.on('click', settings.cloneButton, function(event) {
                            event.preventDefault();
                            $container.triggerHandler(events.beforeClone, [$(this)]);
                            startClone(event, $(this), $container);
                        });
                    }

                    $container.on('click', settings.deleteButton, function(event) {
                        event.preventDefault();
                        removeItem($container, $(this));
                    });

                    if ($container.find(settings.dynamicItem).length === 0) {
                        settings.fields.forEach(function(attribute) {
                            var id = attribute.id.replace("{}", 0);
                            if ($("#" + settings.formId).yiiActiveForm("find", id) !== undefined) {
                               $("#" + settings.formId).yiiActiveForm("remove", id);
                            }
                        });
                    }
                }
            });
        },

        updateContainer: function () {
            var $container = $(this);
            redoIDs($container);
            restoreSpecialJs($container);
            fixFormValidaton($container);
        }
    };

    var startClone = function(event, $btnAdd, $container) {
        var config = $container.data(pluginName).settings;

        // get the count of all the clones
        var cloneCount = $container.find(config.dynamicItem).length;
        // check if we've reached the maximum limit
        if (cloneCount < config.limit) {
            $toclone = $($(config.template).html());
            // clone it
            $newclone = $toclone.clone(false, false);
            $newclone.find('input, textarea, select').each(function() {
                $(this).val('');
            });
            if (config.clonePosition != 'after') {
                $(config.dynamicItems).prepend($newclone);
            } else {
                $(config.dynamicItems).append($newclone);
            }
            redoIDs($container);
            removeErrorCssClass($newclone);
            restoreSpecialJs($container);
            fixFormValidaton($container);
            $container.triggerHandler(events.afterClone, $newclone);
        } else {
            // trigger a custom event for hooking
            $container.triggerHandler(events.limitReached, config.limit);
        }
    };

    var fixFormValidaton = function($container) {
        var config = $container.data(pluginName).settings;
        $(config.dynamicItem).each(function(i) {
            config.fields.forEach(function(v) {
                var id = v.id.replace("{}", i);
                var attribute = v.baseConfig;
                if (attribute !== undefined) {
                    attribute = $.extend(true, {}, attribute);
                    attribute.id = id;
                    attribute.container = ".field-" + id;
                    attribute.input = "#" + id;
                    attribute.name = v.name.replace("{}", i);
                    attribute.value = $("#" + id).val();
                    attribute.status = 0;
                    if ($("#" + config.formId).yiiActiveForm("find", id) !== "undefined") {
                        $("#" + config.formId).yiiActiveForm("remove", id);
                    }
                    $("#" + config.formId).yiiActiveForm("add", attribute);
                }
            });
        });
    };

    var removeItem = function($container, $item) {
        var config = $container.data(pluginName).settings;
        var cloneCount = $container.find(config.dynamicItem).length;
        if (cloneCount > config.min) {
            // get the closest parent clone
            $todelete = $item.closest(config.dynamicItem);
            $todelete.remove();
            redoIDs($container);
            restoreSpecialJs($container);
            fixFormValidaton($container);
            if (cloneCount > 0) {
                config.fields.forEach(function(v) {
                    var id = v.id.replace("{}", (cloneCount - 1));
                    if ($("#" + config.formId).yiiActiveForm("find", id) !== "undefined") {
                        $("#" + config.formId).yiiActiveForm("remove", id);
                    }
                });
            }
            $container.triggerHandler(events.afterRemove);
        }
    }

    var removeErrorCssClass = function($container) {
        $container.find('.has-success').each(function() {
            $(this).removeClass('has-success');
        });
        $container.find('.has-error').each(function() {
            $(this).removeClass('has-error');
        });
    };

    var restoreSpecialJs = function($container) {
        var config = $container.data(pluginName).settings;

        // "kartik-v/yii2-widget-datepicker"
        var $hasDatepicker = $(config.dynamicItems).find('[data-krajee-datepicker]');
        if ($hasDatepicker.length > 0) {
            $hasDatepicker.each(function() {
                $(this).parent().removeData().datepicker('remove');
                $(this).parent().datepicker(eval($(this).attr('data-krajee-datepicker')));
            });
        }

        // "kartik-v/yii2-widget-timepicker"
        var $hasTimepicker = $(config.dynamicItems).find('[data-krajee-timepicker]');
        if ($hasTimepicker.length > 0) {
            $hasTimepicker.each(function() {
                $(this).removeData().off();
                $(this).parent().find('.bootstrap-timepicker-widget').remove();
                $(this).unbind();
                $(this).timepicker(eval($(this).attr('data-krajee-timepicker')));
            });
        }

        // "kartik-v/yii2-money"
        var $hasMaskmoney = $(config.dynamicItems).find('[data-krajee-maskMoney]');
        if ($hasMaskmoney.length > 0) {
            $hasMaskmoney.each(function() {
                $(this).parent().find('input').removeData().off();
                var id = '#' + $(this).attr('id');
                var displayID  = id + '-disp';
                $(displayID).maskMoney('destroy');
                $(displayID).maskMoney(eval($(this).attr('data-krajee-maskMoney')));
                $(displayID).maskMoney('mask', parseFloat($(id).val()));
                $(displayID).on('change', function () {
                    var numDecimal = $(displayID).maskMoney('unmasked')[0];
                    $(id).val(numDecimal);
                    $(id).trigger('change');
                });
            });
        }

        // "kartik-v/yii2-widget-fileinput"
        var $hasFileinput = $(config.dynamicItems).find('[data-krajee-fileinput]');
        if ($hasFileinput.length > 0) {
            $hasFileinput.each(function() {
                $(this).fileinput(eval($(this).attr('data-krajee-fileinput')));
            });
        }

        // "kartik-v/yii2-widget-touchspin"
        var $hasTouchSpin = $(config.dynamicItems).find('[data-krajee-TouchSpin]');
        if ($hasTouchSpin.length > 0) {
            $hasTouchSpin.each(function() {
                $(this).TouchSpin('destroy');
                $(this).TouchSpin(eval($(this).attr('data-krajee-TouchSpin')));
            });
        }

        // "kartik-v/yii2-widget-colorinput"
        var $hasSpectrum = $(config.dynamicItems).find('[data-krajee-spectrum]');
        if ($hasSpectrum.length > 0) {
            $hasSpectrum.each(function() {
                var id = '#' + $(this).attr('id');
                var sourceID  = id + '-source';
                $(sourceID).spectrum('destroy');
                $(sourceID).unbind();
                $(id).unbind();
                var configSpectrum = eval($(this).attr('data-krajee-spectrum'));
                configSpectrum.change = function (color) {
                    jQuery(id).val(color.toString());
                };
                $(sourceID).attr('name', $(sourceID).attr('id'));
                $(sourceID).spectrum(configSpectrum);
                $(sourceID).spectrum('set', jQuery(id).val());
                $(id).on('change', function(){
                    $(sourceID).spectrum('set', jQuery(id).val());
                });
            });
        }

        // "kartik-v/yii2-widget-depdrop"
        var $hasDepdrop = $(config.dynamicItems).find('[data-krajee-depdrop]');
        if ($hasDepdrop.length > 0) {
            $hasDepdrop.each(function() {
                $(this).removeData().off();
                $(this).unbind();
                var configDepdrop = eval($(this).attr('data-krajee-depdrop'));
                var inputID = $(this).attr('id');
                var matchID = inputID.match(regex);
                if (matchID && matchID.length === 4) {
                    for (index = 0; index < configDepdrop.depends.length; ++index) {
                        var match = configDepdrop.depends[index].match(regex);
                        if (match && match.length === 4) {
                            configDepdrop.depends[index] = match[1] + matchID[2] + match[3];
                        }
                    }
                }
                $(this).depdrop(configDepdrop);
            });
        }

        // "kartik-v/yii2-widget-select2"
        var $hasSelect2 = $(config.dynamicItems).find('[data-krajee-select2]');
        if ($hasSelect2.length > 0) {
            $hasSelect2.each(function() {
                var id = $(this).attr('id');
                var configSelect2 = eval($(this).attr('data-krajee-select2'));
                $(this).select2('destroy');
                $.when($('#' + id).select2(configSelect2)).done(initSelect2Loading(id));
                $('#' + id).on('select2-open', function() {
                    initSelect2DropStyle(id)
                });
                if ($(this).attr('data-krajee-depdrop')) {
                    $(this).on('depdrop.beforeChange', function(e,i,v) {
                        var configDepdrop = eval($(this).attr('data-krajee-depdrop'));
                        var loadingText = (configDepdrop.loadingText)? configDepdrop.loadingText : 'Loading ...';
                        $('#' + id).select2('data', {text: loadingText});
                    });
                    $(this).on('depdrop.change', function(e,i,v,c) {
                        $('#' + id).select2('val', $('#' + id).val());
                    });
                }
            });
        }
    };

    var redoIDs = function($container) {
        var config = $container.data(pluginName).settings;
        $container.find(config.dynamicItem).each(function(i) {
            // first modify the clone id
            var j = i;
            var $obj = $(this);
            $(this).find('*').each(function() {
                var id = $(this).attr('id');
                if (id) {
                    var newID = id;
                    var match = id.match(regex);
                    if (match && match.length === 4) {
                        newID = match[1] + i + match[3];
                        $(this).attr('id', newID);
                    } else {
                        newID = id + i;
                        $(this).attr('id', newID);
                    }
                    if (id !== newID) {
                        $obj.find('.field-' + id).each(function() {
                            $(this).removeClass('field-' + id).addClass('field-' + newID);
                        });
                    }
                }
                // "for" attribute
                var elmLabel = $(this).attr('for');
                if (elmLabel) {
                    var match = elmLabel.match(regex);
                    if (match && match.length === 4) {
                        $(this).attr('for', match[1] + i + match[3]);
                    } else {
                        $(this).attr('for', elmLabel + i);
                    }
                }
                // "name" attribute
                var name = $(this).attr('name');
                // This will increment the numeric array index for cloned field names
                if (name) {
                    var matches = name.match(/\[([^}]+)\]/);
                    if (matches && matches.length >= 1) {
                        var st = name;
                        name = [].map.call(st, function(s, i) {
                            return (!isNaN(+s) && st[i - 1] === '[' && st[i + 1] === ']') ? j : s;
                        }).join('');
                        $(this).attr('name', name);
                    }
                }
            });
        });
    };

})(window.jQuery);
<|endoftext|>


<commit_before>module('users.timfelgentreff.babelsberg.deltablue_ext').requires('users.timfelgentreff.deltablue.deltablue').toRun(function() {

Function.addMethods({
    shouldBeSatisfiedWith: function(priority, methods, ctx) {
        // method for deltablue constraint (for now)
        if (!ctx) {
            ctx = methods;
            methods = priority;
            priority = DBStrength.required;
        }
        return DBPlanner.getInstance().always({
            priority: priority,
            methods: methods,
            ctx: ctx
        }, this);
    }
});

DBPlanner.addMethods({
    isConstraintObject: function() {
        return true;
    },
    constraintVariableFor: function(value, ivarname) {
        return new DBVariable(ivarname, value, this);
    },
    get strength() {
        return DBStrength;
    },
    always: function(opts, func) {
        if (Object.isString(opts.priority)) {
            opts.priority = this.strength[opts.priority];
        }
        //func.allowUnsolvableOperations = true; // XXX TODO: find out if we need this
        var planner = this,
            ctx = opts.ctx,
            priority = opts.priority,
            methods = opts.methods;
        func.varMapping = ctx;
        if (!methods) {
            methods = func;
            func = undefined;
        }
        methods.varMapping = ctx;
        var cobj = new Constraint(methods, planner);
        var formulas = cobj.constraintvariables.collect(function (v) {
            var v = v.externalVariables(planner);
            return v ? v.removeFormula() : null;
        }).compact();

        if (formulas.length > 0) {
            var constraint = new UserDBConstraint(priority, func, function (c) {
                formulas.each(function (m) {
                    var inputs = m.inputs.select(function (input) {
                        return input instanceof DBVariable
                    });
                    dbgOn(inputs.length !== m.inputs.length);
                    c.formula(m.output, inputs, m.func);
                });
            }, planner);
            cobj.addPrimitiveConstraint(constraint);
        };
        cobj.priority = priority;
        cobj.enable();
        return cobj;
    },

    weight: 100,
    addEditVar: function(v) {
        if (!this.currentEdits) {
            this.currentEdits = new DBOrderedCollection();
        }
        var edit = new EditDBConstraint(v, DBStrength.REQUIRED, this);
        this.currentEdits.add(edit);
        return edit;
    },
    solve: function() {
        // not required
    },

    beginEdit: function() {
        if (this.currentEditPlan) {
            throw "Trying to run nested edits - this isn't supported"
        }
        if (!this.currentEdits) {
            throw "No edit variables - cannot beginEdit"
        }
        this.currentEditPlan = this.extractDBPlanFromDBConstraints(this.currentEdits);
    },
    endEdit: function() {
        if (this.currentEdits && this.currentEdits.length !== 0) {
            this.currentEdits.elms.each(function (edit) {
                edit.destroyDBConstraint();
            })
        }
        this.currentEditPlan = null;
    },
    resolveArray: function(newValues) {
        if (!this.currentEdits) {
            throw "resolveArray only valid in edit"
        }
        this.currentEdits.elms.each(function (edit, idx) {
            edit.myOutput.value = newValues[idx];
        })
        this.currentEditPlan.execute();
    }
})

Object.extend(DBPlanner, {
    getInstance: function() {
        if (!this["$$instance"]) {
            this["$$instance"] = new DBPlanner();
        }
        return this["$$instance"];
    },

    resetInstance: function() {
        this["$$instance"] = undefined;
    }
});

Object.extend(DBStrength, {
    required: DBStrength.REQUIRED,
    strong: DBStrength.STRONG_DEFAULT,
    medium: DBStrength.NORMAL,
    weak: DBStrength.WEAK_DEFAULT
});

DBVariable.addMethods({
    isConstraintObject: function() {
        return true;
    },

    stay: function(strength) {
        var cn = new StayDBConstraint(this, strength || DBStrength.WEAK_DEFAULT, this.planner);
        cn.enable();
        this._stayConstraint = cn;
        return cn;
    },
    setReadonly: function(bool) {
        if (bool && !this.readonlyConstraint) {
            var cn = new StayDBConstraint(this, DBStrength.required, this.planner);
            cn.enable();
            this.readonlyConstraint = cn;
            return cn;
        } else if (!bool && this.readonlyConstraint) {
            this.readonlyConstraint.disable();
            this.readonlyConstraint = undefined;
        }
    },
    isReadonly: function() {
        return !!this.readonlyConstraint;
    },

    formula: function (inputs, func) {
        if (!Constraint.current) {
            throw "invalid outside constraint construction"
        }
        // var constraint = new Constraint(func, Constraint.current.solver),
        //     inputs = constraint.constraintvariables
        if (this.__formula__) {
            throw "two formulas for the same variable " + this;
        }
        this.__formula__ = {output: this, inputs: inputs, func: func};
    },

    removeFormula: function () {
        var f = this.__formula__;
        this.__formula__ = undefined;
        if (!f) {
            f = this.deriveFormula();
        }
        return f;
    },
    deriveFormula: function() {
        // TODO
        return;
    },

    removeStay: function() {
        if (this._stayConstraint) {
            try {
                this.planner.removeConstraint(this._stayConstraint);
            } catch(_) {
                this._stayConstraint = null;
            }
        }
    },

    suggestValue: function(value) {
        this.assignValue(value);
    },

    prepareEdit: function() {
        if (this.editConstraint) {
            // ignore?
        } else {
            this.editConstraint = this.planner.addEditVar(this);
        }
    },

    finishEdit: function() {
        this.editConstraint = null;
    },
    cnIdentical: function(other) {
        if (!(other instanceof DBVariable)) {
            other = new DBVariable("___", other, this.planner);
            var stay = new StayDBConstraint(other, DBStrength.required, this.planner);
            stay.enable(DBStrength.required);
        }
        return new EqualityDBConstraint(this, other, DBStrength.required, Constraint.current.solver);
    },
    cnEquals: function(other) {
        if (!(other instanceof DBVariable)) {
            other = new DBVariable("constant/" + other, other, this.planner);
            Constraint.current.addPrimitiveConstraint(
                new StayDBConstraint(other, DBStrength.required, this.planner)
            );
        }

        var self = this;
        cloneFunc = function (fromObj) {
            if (fromObj.clone) {
                return fromObj.clone();
            } else if (fromObj.copy) {
                return fromObj.copy();
            } else {
                return fromObj; // regress to identity constraint
            }
        }

        return new UserDBConstraint(
            function (c) {
                c.formula(self, [other], cloneFunc);
                c.formula(other, [self], cloneFunc);
            },
            Constraint.current.solver
        );
    },
    cnOr: function(other) {
        return this.value ? this : other;
    },
    equals: function(argument) {
        return this.cnEquals(argument);
    },
})

DBConstraint.addMethods({
    isConstraintObject: function () {
        return true;
    },

    enable: function (priority) {
        this.strength = priority || this.strength;
        this.addDBConstraint()
    },

    disable: function () {
        this.destroyDBConstraint()
    },

    cnOr: function (other) {
        return this; // assume we can satisfy this
    }
});
EqualityDBConstraint.addMethods({
    setExecuteFunction: function (func) {
        var orig = this.execute.$originalFunction || this.execute;
        func.$originalFunction = orig;
        this.execute = func;
    },

    unsetExecuteFunction: function () {
        this.execute = this.execute.$originalFunction || this.execute;
    }
});}) // end of module
<commit_msg>added postponeEnabling flag to DeltaBlue<commit_after>module('users.timfelgentreff.babelsberg.deltablue_ext').requires('users.timfelgentreff.deltablue.deltablue').toRun(function() {

Function.addMethods({
    shouldBeSatisfiedWith: function(priority, methods, ctx) {
        // method for deltablue constraint (for now)
        if (!ctx) {
            ctx = methods;
            methods = priority;
            priority = DBStrength.required;
        }
        return DBPlanner.getInstance().always({
            priority: priority,
            methods: methods,
            ctx: ctx
        }, this);
    }
});

DBPlanner.addMethods({
    isConstraintObject: function() {
        return true;
    },
    constraintVariableFor: function(value, ivarname) {
        return new DBVariable(ivarname, value, this);
    },
    get strength() {
        return DBStrength;
    },
    always: function(opts, func) {
        if (Object.isString(opts.priority)) {
            opts.priority = this.strength[opts.priority];
        }
        //func.allowUnsolvableOperations = true; // XXX TODO: find out if we need this
        var planner = this,
            ctx = opts.ctx,
            priority = opts.priority,
            methods = opts.methods;
        func.varMapping = ctx;
        if (!methods) {
            methods = func;
            func = undefined;
        }
        methods.varMapping = ctx;
        var cobj = new Constraint(methods, planner);
        var formulas = cobj.constraintvariables.collect(function (v) {
            var v = v.externalVariables(planner);
            return v ? v.removeFormula() : null;
        }).compact();

        if (formulas.length > 0) {
            var constraint = new UserDBConstraint(priority, func, function (c) {
                formulas.each(function (m) {
                    var inputs = m.inputs.select(function (input) {
                        return input instanceof DBVariable
                    });
                    dbgOn(inputs.length !== m.inputs.length);
                    c.formula(m.output, inputs, m.func);
                });
            }, planner);
            cobj.addPrimitiveConstraint(constraint);
        };
        cobj.priority = priority;
        if(!opts.postponeEnabling) { cobj.enable(); }
        return cobj;
    },

    weight: 100,
    addEditVar: function(v) {
        if (!this.currentEdits) {
            this.currentEdits = new DBOrderedCollection();
        }
        var edit = new EditDBConstraint(v, DBStrength.REQUIRED, this);
        this.currentEdits.add(edit);
        return edit;
    },
    solve: function() {
        // not required
    },

    beginEdit: function() {
        if (this.currentEditPlan) {
            throw "Trying to run nested edits - this isn't supported"
        }
        if (!this.currentEdits) {
            throw "No edit variables - cannot beginEdit"
        }
        this.currentEditPlan = this.extractDBPlanFromDBConstraints(this.currentEdits);
    },
    endEdit: function() {
        if (this.currentEdits && this.currentEdits.length !== 0) {
            this.currentEdits.elms.each(function (edit) {
                edit.destroyDBConstraint();
            })
        }
        this.currentEditPlan = null;
    },
    resolveArray: function(newValues) {
        if (!this.currentEdits) {
            throw "resolveArray only valid in edit"
        }
        this.currentEdits.elms.each(function (edit, idx) {
            edit.myOutput.value = newValues[idx];
        })
        this.currentEditPlan.execute();
    }
})

Object.extend(DBPlanner, {
    getInstance: function() {
        if (!this["$$instance"]) {
            this["$$instance"] = new DBPlanner();
        }
        return this["$$instance"];
    },

    resetInstance: function() {
        this["$$instance"] = undefined;
    }
});

Object.extend(DBStrength, {
    required: DBStrength.REQUIRED,
    strong: DBStrength.STRONG_DEFAULT,
    medium: DBStrength.NORMAL,
    weak: DBStrength.WEAK_DEFAULT
});

DBVariable.addMethods({
    isConstraintObject: function() {
        return true;
    },

    stay: function(strength) {
        var cn = new StayDBConstraint(this, strength || DBStrength.WEAK_DEFAULT, this.planner);
        cn.enable();
        this._stayConstraint = cn;
        return cn;
    },
    setReadonly: function(bool) {
        if (bool && !this.readonlyConstraint) {
            var cn = new StayDBConstraint(this, DBStrength.required, this.planner);
            cn.enable();
            this.readonlyConstraint = cn;
            return cn;
        } else if (!bool && this.readonlyConstraint) {
            this.readonlyConstraint.disable();
            this.readonlyConstraint = undefined;
        }
    },
    isReadonly: function() {
        return !!this.readonlyConstraint;
    },

    formula: function (inputs, func) {
        if (!Constraint.current) {
            throw "invalid outside constraint construction"
        }
        // var constraint = new Constraint(func, Constraint.current.solver),
        //     inputs = constraint.constraintvariables
        if (this.__formula__) {
            throw "two formulas for the same variable " + this;
        }
        this.__formula__ = {output: this, inputs: inputs, func: func};
    },

    removeFormula: function () {
        var f = this.__formula__;
        this.__formula__ = undefined;
        if (!f) {
            f = this.deriveFormula();
        }
        return f;
    },
    deriveFormula: function() {
        // TODO
        return;
    },

    removeStay: function() {
        if (this._stayConstraint) {
            try {
                this.planner.removeConstraint(this._stayConstraint);
            } catch(_) {
                this._stayConstraint = null;
            }
        }
    },

    suggestValue: function(value) {
        this.assignValue(value);
    },

    prepareEdit: function() {
        if (this.editConstraint) {
            // ignore?
        } else {
            this.editConstraint = this.planner.addEditVar(this);
        }
    },

    finishEdit: function() {
        this.editConstraint = null;
    },
    cnIdentical: function(other) {
        if (!(other instanceof DBVariable)) {
            other = new DBVariable("___", other, this.planner);
            var stay = new StayDBConstraint(other, DBStrength.required, this.planner);
            stay.enable(DBStrength.required);
        }
        return new EqualityDBConstraint(this, other, DBStrength.required, Constraint.current.solver);
    },
    cnEquals: function(other) {
        if (!(other instanceof DBVariable)) {
            other = new DBVariable("constant/" + other, other, this.planner);
            Constraint.current.addPrimitiveConstraint(
                new StayDBConstraint(other, DBStrength.required, this.planner)
            );
        }

        var self = this;
        cloneFunc = function (fromObj) {
            if (fromObj.clone) {
                return fromObj.clone();
            } else if (fromObj.copy) {
                return fromObj.copy();
            } else {
                return fromObj; // regress to identity constraint
            }
        }

        return new UserDBConstraint(
            function (c) {
                c.formula(self, [other], cloneFunc);
                c.formula(other, [self], cloneFunc);
            },
            Constraint.current.solver
        );
    },
    cnOr: function(other) {
        return this.value ? this : other;
    },
    equals: function(argument) {
        return this.cnEquals(argument);
    },
})

DBConstraint.addMethods({
    isConstraintObject: function () {
        return true;
    },

    enable: function (priority) {
        this.strength = priority || this.strength;
        this.addDBConstraint()
    },

    disable: function () {
        this.destroyDBConstraint()
    },

    cnOr: function (other) {
        return this; // assume we can satisfy this
    }
});
EqualityDBConstraint.addMethods({
    setExecuteFunction: function (func) {
        var orig = this.execute.$originalFunction || this.execute;
        func.$originalFunction = orig;
        this.execute = func;
    },

    unsetExecuteFunction: function () {
        this.execute = this.execute.$originalFunction || this.execute;
    }
});}) // end of module
<|endoftext|>


<commit_before>/**
This module is inteded to contain functionality that can be shared between client and server side

@module DynamoDB
@submodule DynamoDB-Shared
@author Sergio Alcantara
 */

if (typeof require === 'function') {
	var _ = _ || require('underscore');
	var Backbone = Backbone || require('backbone');
}

function bindContext(options){
	if (options && options.context) {
		if (_.isFunction(options.error)) options.error = _.bind(options.error, options.context);
		if (_.isFunction(options.success)) options.success = _.bind(options.success, options.context);
		if (_.isFunction(options.complete)) options.complete = _.bind(options.complete, options.context);
	}
	return options;
}

var isISODate = /^\d{4}(-\d{2}){2}T\d{2}(:\d{2}){2}\.\d{3}Z$/;

Backbone.DynamoDB = {
	isISODate: isISODate,

	/**
	@class Backbone.DynamoDB.Model
	@extends Backbone.Model
	 */
	Model: Backbone.Model.extend({
		/**
		Using the [jQuery.ajax](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) `context` option doesn't work on
		the `success` and `error` callbacks in the original Backbone `save()`, `destroy()`, and `fetch()` methods. This method is overwritten
		to fix that issue.

		@method save
		@param {Object} attributes
		@param {Object} options
		 */
		save: function(attributes, options) {
			return Backbone.Model.prototype.save.call(this, attributes, bindContext(options));
		},
		/**
		Using the [jQuery.ajax](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) `context` option doesn't work on
		the `success` and `error` callbacks in the original Backbone `save()`, `destroy()`, and `fetch()` methods. This method is overwritten
		to fix that issue.

		@method destroy
		@param {Object} options
		 */
		destroy: function(options) {
			return Backbone.Model.prototype.destroy.call(this, bindContext(options));
		},
		/**
		Using the [jQuery.ajax](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) `context` option doesn't work on
		the `success` and `error` callbacks in the original Backbone `save()`, `destroy()`, and `fetch()` methods. This method is overwritten
		to fix that issue.

		@method fetch
		@param {Object} options
		 */
		fetch: function(options) {
			return Backbone.Model.prototype.fetch.call(this, bindContext(options));
		},
		toJSON: function(options) {
			return {
				model: Backbone.Model.prototype.toJSON.call(this, options)
			};
		},
		/**
		Iterates through the given attributes looking for `Date` values that have been converted into string, and converts them back to `Date` instances.

		@method parse
		@param {Object} obj
		@return {Object} Parsed attributes
		 */
		parse: function(obj) {
			var m = obj.model;
			for (var k in m) if (isISODate.test(m[k])) m[k] = new Date(m[k]);
			return m;
		}
	}),

	/**
	@class Backbone.DynamoDB.Collection
	@extends Backbone.Collection
	 */
	Collection: Backbone.Collection.extend({
		/**
		Using the [jQuery.ajax](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) `context` option doesn't work on
		the `success` and `error` callbacks in the original Backbone `save()`, `destroy()`, and `fetch()` methods. This method is overwritten
		to fix that issue.

		@method save
		@param {Object} options
		 */
		fetch: function(options) {
			return Backbone.Collection.prototype.fetch.call(this, bindContext(options));
		},
		toJSON: function(options) {
			return {
				collection: Backbone.Collection.prototype.toJSON.call(this, options)
			};
		},
		parse: function(obj) {
			// Backbone passes each object in the collection through model.parse when instantiating the Models
			return obj.collection;
		}
	})
};

if (typeof module !== 'undefined') module.exports = Backbone;<commit_msg>`Model.toJSON(options)` can now take an array of attribute names in `options.exclude` or `options.include` to exclude or include certain attributes in the returned object.<commit_after>/**
This module is inteded to contain functionality that can be shared between client and server side

@module DynamoDB
@submodule DynamoDB-Shared
@author Sergio Alcantara
 */

if (typeof require === 'function') {
	var _ = _ || require('underscore');
	var Backbone = Backbone || require('backbone');
}

function bindContext(options){
	if (options && options.context) {
		if (_.isFunction(options.error)) options.error = _.bind(options.error, options.context);
		if (_.isFunction(options.success)) options.success = _.bind(options.success, options.context);
		if (_.isFunction(options.complete)) options.complete = _.bind(options.complete, options.context);
	}
	return options;
}

var isISODate = /^\d{4}(-\d{2}){2}T\d{2}(:\d{2}){2}\.\d{3}Z$/;

Backbone.DynamoDB = {
	isISODate: isISODate,

	/**
	@class Backbone.DynamoDB.Model
	@extends Backbone.Model
	 */
	Model: Backbone.Model.extend({
		/**
		Using the [jQuery.ajax](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) `context` option doesn't work on
		the `success` and `error` callbacks in the original Backbone `save()`, `destroy()`, and `fetch()` methods. This method is overwritten
		to fix that issue.

		@method save
		@param {Object} attributes
		@param {Object} options
		 */
		save: function(attributes, options) {
			return Backbone.Model.prototype.save.call(this, attributes, bindContext(options));
		},
		/**
		Using the [jQuery.ajax](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) `context` option doesn't work on
		the `success` and `error` callbacks in the original Backbone `save()`, `destroy()`, and `fetch()` methods. This method is overwritten
		to fix that issue.

		@method destroy
		@param {Object} options
		 */
		destroy: function(options) {
			return Backbone.Model.prototype.destroy.call(this, bindContext(options));
		},
		/**
		Using the [jQuery.ajax](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) `context` option doesn't work on
		the `success` and `error` callbacks in the original Backbone `save()`, `destroy()`, and `fetch()` methods. This method is overwritten
		to fix that issue.

		@method fetch
		@param {Object} options
		 */
		fetch: function(options) {
			return Backbone.Model.prototype.fetch.call(this, bindContext(options));
		},
		toJSON: function(options) {
			var json = Backbone.Model.prototype.toJSON.call(this, options);

			if (options && !_.isEmpty(options.exclude)) {
				var filtered = {},
					exclude = options.exclude;
				_.isArray(exclude) || (exclude = [exclude]);

				_.each(json, function(value, name) {
					if (_.indexOf(exclude, name) === -1) filtered[name] = value;
				});
				json = filtered;
			} else if (options && !_.isEmpty(options.include)) {
				var filtered = {},
					include = options.include;
				_.isArray(include) || (include = [include]);

				_.each(json, function(value, name) {
					if (_.indexOf(include, name) !== -1) filtered[name] = value;
				});
				json = filtered;
			}

			return {model: json};
		},
		/**
		Iterates through the given attributes looking for `Date` values that have been converted into string, and converts them back to `Date` instances.

		@method parse
		@param {Object} obj
		@return {Object} Parsed attributes
		 */
		parse: function(obj) {
			var m = obj.model;
			for (var k in m) if (isISODate.test(m[k])) m[k] = new Date(m[k]);
			return m;
		}
	}),

	/**
	@class Backbone.DynamoDB.Collection
	@extends Backbone.Collection
	 */
	Collection: Backbone.Collection.extend({
		/**
		Using the [jQuery.ajax](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) `context` option doesn't work on
		the `success` and `error` callbacks in the original Backbone `save()`, `destroy()`, and `fetch()` methods. This method is overwritten
		to fix that issue.

		@method save
		@param {Object} options
		 */
		fetch: function(options) {
			return Backbone.Collection.prototype.fetch.call(this, bindContext(options));
		},
		toJSON: function(options) {
			return {
				collection: Backbone.Collection.prototype.toJSON.call(this, options)
			};
		},
		parse: function(obj) {
			// Backbone passes each object in the collection through model.parse when instantiating the Models
			return obj.collection;
		}
	})
};

if (typeof module !== 'undefined') module.exports = Backbone;<|endoftext|>


<commit_before>var passport = require('passport');
var passportVenmo = require('passport-venmo');
var User = require('../models/user');

var client_id = process.env.CLIENT_ID;
var client_secret = process.env.CLIENT_SECRET;

var venmoStrategy = passportVenmo.Strategy;

var venmo_strategy = new venmoStrategy(
    {
        'clientID': client_id,
        'clientSecret': client_secret,
        'callbackURL': "http://loanr.thenoobprogrammer.com/api/users/authenticate/callback"
    },
    function(accessToken, refreshToken, profile, next){
        User.findOrCreate({"username": profile.username, "venmoId": profile.id}, function(err, user){
            return next(err, user);
        });
    }
);

passport.use(venmo_strategy);

module.exports = passport; <commit_msg>trying to save user<commit_after>var passport = require('passport');
var passportVenmo = require('passport-venmo');
var User = require('../models/user');

var client_id = process.env.CLIENT_ID;
var client_secret = process.env.CLIENT_SECRET;

var venmoStrategy = passportVenmo.Strategy;

var venmo_strategy = new venmoStrategy(
    {
        'clientID': client_id,
        'clientSecret': client_secret,
        'callbackURL': "http://loanr.thenoobprogrammer.com/api/users/authenticate/callback"
    },
    function(accessToken, refreshToken, profile, next){
        User.findOrCreate({"username": profile.username, "venmoId": profile.id, 'access_token': accessToken}, function(err, user, created){
            user.save(function(err, user){
                return next(err, user);
            });
        });
    }
);

passport.use(venmo_strategy);

module.exports = passport; <|endoftext|>