<commit_before>#!/usr/bin/env node
;(function() {
  'use strict';

  /** The Node filesystem, path, and child process modules */
  var fs = require('fs'),
      path = require('path'),
      spawn = require('child_process').spawn;

  /** The build directory containing the build scripts */
  var buildPath = path.join(__dirname, 'build');

  /** The directory where the Closure Compiler is located */
  var closurePath = path.join(__dirname, 'vendor', 'closure-compiler', 'compiler.jar');

  /** The distribution directory */
  var distPath = path.join(__dirname, 'dist');

  /** Load other modules */
  var preprocess = require(path.join(buildPath, 'pre-compile')),
      postprocess = require(path.join(buildPath, 'post-compile')),
      uglifyJS = require(path.join(__dirname, 'vendor', 'uglifyjs', 'uglify-js'));

  /** Used to shares values between multiple callbacks */
  var accumulator = {
    'compiled': {},
    'uglified': {}
  };

  /** Closure Compiler command-line options */
  var closureOptions = [
    '--compilation_level=ADVANCED_OPTIMIZATIONS',
    '--language_in=ECMASCRIPT5_STRICT',
    '--warning_level=QUIET'
  ];

  /** Gzip command-line options */
  var gzipOptions = ['-9f', '-c'];

  /** The pre-processed Lo-Dash source */
  var source = preprocess(fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8'));

  /*--------------------------------------------------------------------------*/

  /**
   * Invokes a process with the given `name`, `parameters`, and `source` (used as
   * the standard input). Yields the result to a `callback` function. The optional
   * `encoding` argument specifies the output stream encoding.
   *
   * @private
   * @param {String} name The name of the process.
   * @param {Array} parameters An array of arguments to proxy to the process.
   * @param {String} source The standard input to proxy to the process.
   * @param {String} [encoding] The expected encoding of the output stream.
   * @param {Function} callback The function to call once the process completes.
   */
  function invoke(name, parameters, source, encoding, callback) {
    // the standard error stream, standard output stream, and process instance
    var error = '',
        output = '',
        process = spawn(name, parameters);

    // juggle arguments
    if (typeof encoding == 'string') {
      // explicitly set the encoding of the output stream if one is specified
      process.stdout.setEncoding(encoding);
    } else {
      callback = encoding;
      encoding = null;
    }

    process.stdout.on('data', function(data) {
      // append the data to the output stream
      output += data;
    });

    process.stderr.on('data', function(data) {
      // append the error message to the error stream
      error += data;
    });

    process.on('exit', function(status) {
      var exception = null;
      // `status` contains the process exit code
      if (status) {
        exception = new Error(error);
        exception.status = status;
      }
      callback(exception, output);
    });

    // proxy the standard input to the process
    process.stdin.end(source);
  }

  /*--------------------------------------------------------------------------*/

  /**
   * Compresses a `source` string using the Closure Compiler. Yields the
   * minified result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to minify.
   * @param {Function} callback The function to call once the process completes.
   */
  function closureCompile(source, callback) {
    console.log('Compressing lodash.js using the Closure Compiler...');
    invoke('java', ['-jar', closurePath].concat(closureOptions), source, callback);
  }

  /**
   * Compresses a `source` string using UglifyJS. Yields the result to a
   * `callback` function. This function is synchronous; the `callback` is used
   * for symmetry.
   *
   * @private
   * @param {String} source The JavaScript source to minify.
   * @param {Function} callback The function to call once the process completes.
   */
  function uglify(source, callback) {
    var exception,
        result,
        ugly = uglifyJS.uglify;

    console.log('Compressing lodash.js using UglifyJS...');

    try {
      result = ugly.gen_code(
        // enable unsafe transformations
        ugly.ast_squeeze_more(
          ugly.ast_squeeze(
            // munge variable and function names, excluding the special `define`
            // function exposed by AMD loaders
            ugly.ast_mangle(uglifyJS.parser.parse(source), {
              'except': ['define']
            }
        ))), {
        'ascii_only': true
      });
    } catch(e) {
      exception = e;
    }
    // lines are restricted to 500 characters for consistency with the Closure Compiler
    callback(exception, result && ugly.split_lines(result, 500));
  }

  /*--------------------------------------------------------------------------*/

  /**
   * The `closureCompile()` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {String} result The resulting minified source.
   */
  function onClosureCompile(exception, result) {
    if (exception) {
      throw exception;
    }
    // store the post-processed Closure Compiler result and gzip it
    accumulator.compiled.source = result = postprocess(result);
    invoke('gzip', gzipOptions, result, 'binary', onClosureGzip);
  }

  /**
   * The Closure Compiler `gzip` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {String} result The resulting gzipped source.
   */
  function onClosureGzip(exception, result) {
    if (exception) {
      throw exception;
    }
    // store the gzipped result and report the size
    accumulator.compiled.gzip = result;
    console.log('Done. Size: %d KB.', result.length);

    // next, minify using UglifyJS
    uglify(source, onUglify);
  }

  /**
   * The `uglify()` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {String} result The resulting minified source.
   */
  function onUglify(exception, result) {
    if (exception) {
      throw exception;
    }
    // store the post-processed Uglified result and gzip it
    accumulator.uglified.source = result = postprocess(result);
    invoke('gzip', gzipOptions, result, 'binary', onUglifyGzip);
  }

  /**
   * The UglifyJS `gzip` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {String} result The resulting gzipped source.
   */
  function onUglifyGzip(exception, result) {
    if (exception) {
      throw exception;
    }
    // store the gzipped result and report the size
    accumulator.uglified.gzip = result;
    console.log('Done. Size: %d KB.', result.length);

    // finish by choosing the smallest compressed file
    onComplete();
  }

  /**
   * The callback executed after JavaScript source is minified and gzipped.
   *
   * @private
   */
  function onComplete() {
    var compiled = accumulator.compiled,
        uglified = accumulator.uglified;

    // save the Closure Compiled version to disk
    fs.writeFileSync(path.join(distPath, 'lodash.compiler.js'), compiled.source);
    // explicit 'binary' is necessary to ensure the stream is written correctly
    fs.writeFileSync(path.join(distPath, 'lodash.compiler.js.gz'), compiled.gzip, 'binary');

    // save the Uglified version to disk
    fs.writeFileSync(path.join(distPath, 'lodash.uglify.js'), uglified.source);
    fs.writeFileSync(path.join(distPath, 'lodash.uglify.js.gz'), uglified.gzip, 'binary');

    // select the smallest gzipped file and use its minified counterpart as the
    // official minified release (ties go to Closure Compiler)
    fs.writeFileSync(path.join(__dirname, 'lodash.min.js'),
      uglified.gzip.length < compiled.gzip.length
        ? uglified.source
        : compiled.source
    );
  }

  /*--------------------------------------------------------------------------*/

  // create the destination directory if it doesn't exist
  if (!path.existsSync(distPath)) {
    fs.mkdirSync(distPath);
  }
  // begin the minification process
  closureCompile(source, onClosureCompile);
}());
<commit_msg>Use the Node `zlib` module instead of shelling out to `gzip`.<commit_after>#!/usr/bin/env node
;(function() {
  'use strict';

  /** The Node filesystem, path, `zlib`, and child process modules */
  var fs = require('fs'),
      path = require('path'),
      gzip = require('zlib').gzip,
      spawn = require('child_process').spawn;

  /** The build directory containing the build scripts */
  var buildPath = path.join(__dirname, 'build');

  /** The directory where the Closure Compiler is located */
  var closurePath = path.join(__dirname, 'vendor', 'closure-compiler', 'compiler.jar');

  /** The distribution directory */
  var distPath = path.join(__dirname, 'dist');

  /** Load other modules */
  var preprocess = require(path.join(buildPath, 'pre-compile')),
      postprocess = require(path.join(buildPath, 'post-compile')),
      uglifyJS = require(path.join(__dirname, 'vendor', 'uglifyjs', 'uglify-js'));

  /** Used to shares values between multiple callbacks */
  var accumulator = {
    'compiled': {},
    'uglified': {}
  };

  /** Closure Compiler command-line options */
  var closureOptions = [
    '--compilation_level=ADVANCED_OPTIMIZATIONS',
    '--language_in=ECMASCRIPT5_STRICT',
    '--warning_level=QUIET'
  ];

  /** The pre-processed Lo-Dash source */
  var source = preprocess(fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8'));

  /*--------------------------------------------------------------------------*/

  /**
   * Invokes a process with the given `name`, `parameters`, and `source` (used as
   * the standard input). Yields the result to a `callback` function. The optional
   * `encoding` argument specifies the output stream encoding.
   *
   * @private
   * @param {String} name The name of the process.
   * @param {Array} parameters An array of arguments to proxy to the process.
   * @param {String} source The standard input to proxy to the process.
   * @param {String} [encoding] The expected encoding of the output stream.
   * @param {Function} callback The function to call once the process completes.
   */
  function invoke(name, parameters, source, encoding, callback) {
    // the standard error stream, standard output stream, and process instance
    var error = '',
        output = '',
        process = spawn(name, parameters);

    // juggle arguments
    if (typeof encoding == 'string') {
      // explicitly set the encoding of the output stream if one is specified
      process.stdout.setEncoding(encoding);
    } else {
      callback = encoding;
      encoding = null;
    }

    process.stdout.on('data', function(data) {
      // append the data to the output stream
      output += data;
    });

    process.stderr.on('data', function(data) {
      // append the error message to the error stream
      error += data;
    });

    process.on('exit', function(status) {
      var exception = null;
      // `status` contains the process exit code
      if (status) {
        exception = new Error(error);
        exception.status = status;
      }
      callback(exception, output);
    });

    // proxy the standard input to the process
    process.stdin.end(source);
  }

  /*--------------------------------------------------------------------------*/

  /**
   * Compresses a `source` string using the Closure Compiler. Yields the
   * minified result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to minify.
   * @param {Function} callback The function to call once the process completes.
   */
  function closureCompile(source, callback) {
    console.log('Compressing lodash.js using the Closure Compiler...');
    invoke('java', ['-jar', closurePath].concat(closureOptions), source, callback);
  }

  /**
   * Compresses a `source` string using UglifyJS. Yields the result to a
   * `callback` function. This function is synchronous; the `callback` is used
   * for symmetry.
   *
   * @private
   * @param {String} source The JavaScript source to minify.
   * @param {Function} callback The function to call once the process completes.
   */
  function uglify(source, callback) {
    var exception,
        result,
        ugly = uglifyJS.uglify;

    console.log('Compressing lodash.js using UglifyJS...');

    try {
      result = ugly.gen_code(
        // enable unsafe transformations
        ugly.ast_squeeze_more(
          ugly.ast_squeeze(
            // munge variable and function names, excluding the special `define`
            // function exposed by AMD loaders
            ugly.ast_mangle(uglifyJS.parser.parse(source), {
              'except': ['define']
            }
        ))), {
        'ascii_only': true
      });
    } catch(e) {
      exception = e;
    }
    // lines are restricted to 500 characters for consistency with the Closure Compiler
    callback(exception, result && ugly.split_lines(result, 500));
  }

  /*--------------------------------------------------------------------------*/

  /**
   * The `closureCompile()` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {String} result The resulting minified source.
   */
  function onClosureCompile(exception, result) {
    if (exception) {
      throw exception;
    }
    // store the post-processed Closure Compiler result and gzip it
    accumulator.compiled.source = result = postprocess(result);
    gzip(result, onClosureGzip);
  }

  /**
   * The Closure Compiler `gzip` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {Buffer} result The resulting gzipped source.
   */
  function onClosureGzip(exception, result) {
    if (exception) {
      throw exception;
    }
    // store the gzipped result and report the size
    accumulator.compiled.gzip = result;
    console.log('Done. Size: %d KB.', result.length);

    // next, minify using UglifyJS
    uglify(source, onUglify);
  }

  /**
   * The `uglify()` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {String} result The resulting minified source.
   */
  function onUglify(exception, result) {
    if (exception) {
      throw exception;
    }
    // store the post-processed Uglified result and gzip it
    accumulator.uglified.source = result = postprocess(result);
    gzip(result, onUglifyGzip);
  }

  /**
   * The UglifyJS `gzip` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {Buffer} result The resulting gzipped source.
   */
  function onUglifyGzip(exception, result) {
    if (exception) {
      throw exception;
    }
    // store the gzipped result and report the size
    accumulator.uglified.gzip = result;
    console.log('Done. Size: %d KB.', result.length);

    // finish by choosing the smallest compressed file
    onComplete();
  }

  /**
   * The callback executed after JavaScript source is minified and gzipped.
   *
   * @private
   */
  function onComplete() {
    var compiled = accumulator.compiled,
        uglified = accumulator.uglified;

    // save the Closure Compiled version to disk
    fs.writeFileSync(path.join(distPath, 'lodash.compiler.js'), compiled.source);
    fs.writeFileSync(path.join(distPath, 'lodash.compiler.js.gz'), compiled.gzip);

    // save the Uglified version to disk
    fs.writeFileSync(path.join(distPath, 'lodash.uglify.js'), uglified.source);
    fs.writeFileSync(path.join(distPath, 'lodash.uglify.js.gz'), uglified.gzip);

    // select the smallest gzipped file and use its minified counterpart as the
    // official minified release (ties go to Closure Compiler)
    fs.writeFileSync(path.join(__dirname, 'lodash.min.js'),
      uglified.gzip.length < compiled.gzip.length
        ? uglified.source
        : compiled.source
    );
  }

  /*--------------------------------------------------------------------------*/

  // create the destination directory if it doesn't exist
  if (!path.existsSync(distPath)) {
    fs.mkdirSync(distPath);
  }
  // begin the minification process
  closureCompile(source, onClosureCompile);
}());
<|endoftext|>


<commit_before>var qm = require('qminer');
var base1 = new qm.Base({
    mode: 'createClean',
    schema: [
      {
          name: 'People',
          fields: [{ name: 'name', type: 'string', null: true }],
      }
    ],
    dbPath: './db1'
});

var store1 = base1.store("People");
store1.add({ name: "Jan" });
store1.add({ name: null });
assert(store1.length == 2);
base1.close();
<commit_msg>test fix (missing require)<commit_after>var assert = require('assert');
var qm = require('qminer');
var base1 = new qm.Base({
    mode: 'createClean',
    schema: [
      {
          name: 'People',
          fields: [{ name: 'name', type: 'string', null: true }],
      }
    ],
    dbPath: './db1'
});

var store1 = base1.store("People");
store1.add({ name: "Jan" });
store1.add({ name: null });
assert(store1.length == 2);
base1.close();
<|endoftext|>


<commit_before>"use strict";

var _ = require('underscore');
var CompositeView = require("../composite").View;
var $$ = require("substance-application").$$;
var ResourceView = require('../../resource_view');

// Lens.Supplement.View
// ==========================================================================

var SupplementView = function(node, viewFactory, options) {
  CompositeView.call(this, node, viewFactory);

  // Mix-in
  ResourceView.call(this, options);

};

SupplementView.Prototype = function() {

  // Mix-in
  _.extend(this, ResourceView.prototype);

  this.renderBody = function() {

    this.renderChildren();

    var file = $$('div.file', {
      children: [
        $$('a', {href: this.node.url, html: '<i class="icon-download-alt"/> Download' })
      ]
    });
    this.content.appendChild(file);
  };
};

SupplementView.Prototype.prototype = CompositeView.prototype;
SupplementView.prototype = new SupplementView.Prototype();
SupplementView.prototype.constructor = SupplementView;

module.exports = SupplementView;
<commit_msg>Fix icon for supplements.<commit_after>"use strict";

var _ = require('underscore');
var CompositeView = require("../composite").View;
var $$ = require("substance-application").$$;
var ResourceView = require('../../resource_view');

// Lens.Supplement.View
// ==========================================================================

var SupplementView = function(node, viewFactory, options) {
  CompositeView.call(this, node, viewFactory);

  // Mix-in
  ResourceView.call(this, options);

};

SupplementView.Prototype = function() {

  // Mix-in
  _.extend(this, ResourceView.prototype);

  this.renderBody = function() {

    this.renderChildren();

    var file = $$('div.file', {
      children: [
        $$('a', {href: this.node.url, html: '<i class="fa fa-download"/> Download' })
      ]
    });
    this.content.appendChild(file);
  };
};

SupplementView.Prototype.prototype = CompositeView.prototype;
SupplementView.prototype = new SupplementView.Prototype();
SupplementView.prototype.constructor = SupplementView;

module.exports = SupplementView;
<|endoftext|>


<commit_before>// Generated on 2014-10-16 using generator-jekyllrb 1.2.1
'use strict';

// Directory reference:
//   css: _css
//   compass: _scss
//   javascript: _js
//   coffeescript: _src
//   images: _img
//   fonts: _fonts

module.exports = function (grunt) {
  // Show elapsed time after tasks run
  require('time-grunt')(grunt);
  // Load all Grunt tasks
  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    // Configurable paths
    yeoman: {
      app: 'app',
      dist: 'dist'
    },
    watch: {
      compass: {
        files: ['<%= yeoman.app %>/_scss/**/*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer:server']
      },
      autoprefixer: {
        files: ['<%= yeoman.app %>/_css/**/*.css'],
        tasks: ['copy:stageCss', 'autoprefixer:server']
      },
      coffee: {
        files: ['<%= yeoman.app %>/_src/**/*.coffee'],
        tasks: ['coffee:dist']
      },
      coffeeTest: {
        files: ['test/spec/**/*.coffee'],
        tasks: ['coffee:test']
      },
      jekyll: {
        files: [
          '<%= yeoman.app %>/**/*.{html,yml,md,mkd,markdown}',
          '!<%= yeoman.app %>/_bower_components/**/*'
        ],
        tasks: ['jekyll:server']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '.jekyll/**/*.html',
          '.tmp/_css/**/*.css',
          '{.tmp,<%= yeoman.app %>}/<%= js %>/**/*.js',
          '<%= yeoman.app %>/_img/**/*.{gif,jpg,jpeg,png,svg,webp}'
        ]
      }
    },
    connect: {
      options: {
        port: 9000,
        livereload: 35729,
        // change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '.jekyll',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          open: true,
          base: [
            '<%= yeoman.dist %>'
          ]
        }
      },
      test: {
        options: {
          base: [
            '.tmp',
            '.jekyll',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      }
    },
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '<%= yeoman.dist %>/*',
            // Running Jekyll also cleans the target directory.  Exclude any
            // non-standard `keep_files` here (e.g., the generated files
            // directory from Jekyll Picture Tag).
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: [
        '.tmp',
        '.jekyll'
      ]
    },
    compass: {
      options: {
        // If you're using global Sass gems, require them here.
        // require: ['singularity', 'jacket'],
        bundleExec: true,
        sassDir: '<%= yeoman.app %>/_scss',
        cssDir: '.tmp/_css',
        imagesDir: '<%= yeoman.app %>/_img',
        javascriptsDir: '<%= yeoman.app %>/_js',
        relativeAssets: false,
        httpImagesPath: '/_img',
        httpGeneratedImagesPath: '/_img/generated',
        outputStyle: 'expanded',
        raw: 'extensions_dir = "<%= yeoman.app %>/_bower_components"\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/_img/generated'
        }
      },
      server: {
        options: {
          debugInfo: true,
          generatedImagesDir: '.tmp/_img/generated'
        }
      }
    },
    autoprefixer: {
      options: {
        browsers: ['last 2 versions']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>/_css',
          src: '**/*.css',
          dest: '<%= yeoman.dist %>/_css'
        }]
      },
      server: {
        files: [{
          expand: true,
          cwd: '.tmp/_css',
          src: '**/*.css',
          dest: '.tmp/_css'
        }]
      }
    },
    coffee: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/_src',
          src: '**/*.coffee',
          dest: '.tmp/_js',
          ext: '.js'
        }]
      },
      test: {
        files: [{
          expand: true,
          cwd: 'test/spec',
          src: '**/*.coffee',
          dest: '.tmp/spec',
          ext: '.js'
        }]
      }
    },
    jekyll: {
      options: {
        bundleExec: true,
        config: '_config.yml,_config.build.yml',
        src: '<%= yeoman.app %>'
      },
      dist: {
        options: {
          dest: '<%= yeoman.dist %>',
        }
      },
      server: {
        options: {
          config: '_config.yml',
          dest: '.jekyll'
        }
      },
      check: {
        options: {
          doctor: true
        }
      }
    },
    useminPrepare: {
      options: {
        dest: '<%= yeoman.dist %>'
      },
      html: '<%= yeoman.dist %>/index.html'
    },
    usemin: {
      options: {
        assetsDirs: '<%= yeoman.dist %>',
      },
      html: ['<%= yeoman.dist %>/**/*.html'],
      css: ['<%= yeoman.dist %>/_css/**/*.css']
    },
    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeAttributeQuotes: true,
          removeRedundantAttributes: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: '**/*.html',
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    // Usemin adds files to concat
    concat: {},
    // Usemin adds files to uglify
    uglify: {},
    // Usemin adds files to cssmin
    cssmin: {
      dist: {
        options: {
          check: 'gzip'
        }
      }
    },
    imagemin: {
      dist: {
        options: {
          progressive: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: '**/*.{jpg,jpeg,png}',
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: '**/*.svg',
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          src: [
            // Jekyll processes and moves HTML and text files.
            // Usemin moves CSS and javascript inside of Usemin blocks.
            // Copy moves asset files and directories.
            '_img/**/*',
            '_fonts/**/*',
            // Like Jekyll, exclude files & folders prefixed with an underscore.
            '!**/_*{,/**}'
            // Explicitly add any files your site needs for distribution here.
            //'_bower_components/jquery/jquery.js',
            //'favicon.ico',
            //'apple-touch*.png'
          ],
          dest: '<%= yeoman.dist %>'
        }]
      },
      // Copy CSS into .tmp directory for Autoprefixer processing
      stageCss: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>/_css',
          src: '**/*.css',
          dest: '.tmp/_css'
        }]
      }
    },
    filerev: {
      options: {
        length: 4
      },
      dist: {
        files: [{
          src: [
            '<%= yeoman.dist %>/_js/**/*.js',
            '<%= yeoman.dist %>/_css/**/*.css',
            '<%= yeoman.dist %>/_img/**/*.{gif,jpg,jpeg,png,svg,webp}',
            '<%= yeoman.dist %>/_fonts/**/*.{eot*,otf,svg,ttf,woff}'
          ]
        }]
      }
    },
    buildcontrol: {
      dist: {
        options: {
          remote: 'https://github.com/ilkelma/ilkelma-page-build.git',
          branch: 'master',
          commit: true,
          push: true
        }
      }
    },
    coffeelint: {
      options: {
        'max_line_length': {
          'level': 'ignore'
        }
      },
      check: ['<%= yeoman.app %>/_src/*.coffee']
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/_js/**/*.js',
        'test/spec/**/*.js'
      ]
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc'
      },
      check: {
        src: [
          '<%= yeoman.app %>/_css/**/*.css',
          '<%= yeoman.app %>/_scss/**/*.scss'
        ]
      }
    },
    concurrent: {
      server: [
        'compass:server',
        'coffee:dist',
        'copy:stageCss',
        'jekyll:server'
      ],
      dist: [
        'compass:dist',
        'coffee:dist',
        'copy:dist'
      ]
    }
  });

  // Define Tasks
  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',
      'autoprefixer:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', function () {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve']);
  });

  // No real tests yet. Add your own.
  grunt.registerTask('test', [
  //   'clean:server',
  //   'concurrent:test',
  //   'connect:test'
  ]);

  grunt.registerTask('check', [
    'clean:server',
    'jekyll:check',
    'compass:server',
    'coffeelint:check',
    'coffee:dist',
    'jshint:all',
    'csslint:check'
  ]);

  grunt.registerTask('build', [
    'clean',
    // Jekyll cleans files from the target directory, so must run first
    'jekyll:dist',
    'concurrent:dist',
    'useminPrepare',
    'concat',
    'autoprefixer:dist',
    'cssmin',
    'uglify',
    'imagemin',
    'svgmin',
    'filerev',
    'usemin',
    'htmlmin'
    ]);

  grunt.registerTask('deploy', [
    'check',
    'test',
    'build',
    'buildcontrol'
    ]);

  grunt.registerTask('default', [
    'check',
    'test',
    'build'
  ]);
};
<commit_msg>fix git endpoint for build-control<commit_after>// Generated on 2014-10-16 using generator-jekyllrb 1.2.1
'use strict';

// Directory reference:
//   css: _css
//   compass: _scss
//   javascript: _js
//   coffeescript: _src
//   images: _img
//   fonts: _fonts

module.exports = function (grunt) {
  // Show elapsed time after tasks run
  require('time-grunt')(grunt);
  // Load all Grunt tasks
  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    // Configurable paths
    yeoman: {
      app: 'app',
      dist: 'dist'
    },
    watch: {
      compass: {
        files: ['<%= yeoman.app %>/_scss/**/*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer:server']
      },
      autoprefixer: {
        files: ['<%= yeoman.app %>/_css/**/*.css'],
        tasks: ['copy:stageCss', 'autoprefixer:server']
      },
      coffee: {
        files: ['<%= yeoman.app %>/_src/**/*.coffee'],
        tasks: ['coffee:dist']
      },
      coffeeTest: {
        files: ['test/spec/**/*.coffee'],
        tasks: ['coffee:test']
      },
      jekyll: {
        files: [
          '<%= yeoman.app %>/**/*.{html,yml,md,mkd,markdown}',
          '!<%= yeoman.app %>/_bower_components/**/*'
        ],
        tasks: ['jekyll:server']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '.jekyll/**/*.html',
          '.tmp/_css/**/*.css',
          '{.tmp,<%= yeoman.app %>}/<%= js %>/**/*.js',
          '<%= yeoman.app %>/_img/**/*.{gif,jpg,jpeg,png,svg,webp}'
        ]
      }
    },
    connect: {
      options: {
        port: 9000,
        livereload: 35729,
        // change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '.jekyll',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          open: true,
          base: [
            '<%= yeoman.dist %>'
          ]
        }
      },
      test: {
        options: {
          base: [
            '.tmp',
            '.jekyll',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      }
    },
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '<%= yeoman.dist %>/*',
            // Running Jekyll also cleans the target directory.  Exclude any
            // non-standard `keep_files` here (e.g., the generated files
            // directory from Jekyll Picture Tag).
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: [
        '.tmp',
        '.jekyll'
      ]
    },
    compass: {
      options: {
        // If you're using global Sass gems, require them here.
        // require: ['singularity', 'jacket'],
        bundleExec: true,
        sassDir: '<%= yeoman.app %>/_scss',
        cssDir: '.tmp/_css',
        imagesDir: '<%= yeoman.app %>/_img',
        javascriptsDir: '<%= yeoman.app %>/_js',
        relativeAssets: false,
        httpImagesPath: '/_img',
        httpGeneratedImagesPath: '/_img/generated',
        outputStyle: 'expanded',
        raw: 'extensions_dir = "<%= yeoman.app %>/_bower_components"\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/_img/generated'
        }
      },
      server: {
        options: {
          debugInfo: true,
          generatedImagesDir: '.tmp/_img/generated'
        }
      }
    },
    autoprefixer: {
      options: {
        browsers: ['last 2 versions']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>/_css',
          src: '**/*.css',
          dest: '<%= yeoman.dist %>/_css'
        }]
      },
      server: {
        files: [{
          expand: true,
          cwd: '.tmp/_css',
          src: '**/*.css',
          dest: '.tmp/_css'
        }]
      }
    },
    coffee: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/_src',
          src: '**/*.coffee',
          dest: '.tmp/_js',
          ext: '.js'
        }]
      },
      test: {
        files: [{
          expand: true,
          cwd: 'test/spec',
          src: '**/*.coffee',
          dest: '.tmp/spec',
          ext: '.js'
        }]
      }
    },
    jekyll: {
      options: {
        bundleExec: true,
        config: '_config.yml,_config.build.yml',
        src: '<%= yeoman.app %>'
      },
      dist: {
        options: {
          dest: '<%= yeoman.dist %>',
        }
      },
      server: {
        options: {
          config: '_config.yml',
          dest: '.jekyll'
        }
      },
      check: {
        options: {
          doctor: true
        }
      }
    },
    useminPrepare: {
      options: {
        dest: '<%= yeoman.dist %>'
      },
      html: '<%= yeoman.dist %>/index.html'
    },
    usemin: {
      options: {
        assetsDirs: '<%= yeoman.dist %>',
      },
      html: ['<%= yeoman.dist %>/**/*.html'],
      css: ['<%= yeoman.dist %>/_css/**/*.css']
    },
    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeAttributeQuotes: true,
          removeRedundantAttributes: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: '**/*.html',
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    // Usemin adds files to concat
    concat: {},
    // Usemin adds files to uglify
    uglify: {},
    // Usemin adds files to cssmin
    cssmin: {
      dist: {
        options: {
          check: 'gzip'
        }
      }
    },
    imagemin: {
      dist: {
        options: {
          progressive: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: '**/*.{jpg,jpeg,png}',
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: '**/*.svg',
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          src: [
            // Jekyll processes and moves HTML and text files.
            // Usemin moves CSS and javascript inside of Usemin blocks.
            // Copy moves asset files and directories.
            '_img/**/*',
            '_fonts/**/*',
            // Like Jekyll, exclude files & folders prefixed with an underscore.
            '!**/_*{,/**}'
            // Explicitly add any files your site needs for distribution here.
            //'_bower_components/jquery/jquery.js',
            //'favicon.ico',
            //'apple-touch*.png'
          ],
          dest: '<%= yeoman.dist %>'
        }]
      },
      // Copy CSS into .tmp directory for Autoprefixer processing
      stageCss: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>/_css',
          src: '**/*.css',
          dest: '.tmp/_css'
        }]
      }
    },
    filerev: {
      options: {
        length: 4
      },
      dist: {
        files: [{
          src: [
            '<%= yeoman.dist %>/_js/**/*.js',
            '<%= yeoman.dist %>/_css/**/*.css',
            '<%= yeoman.dist %>/_img/**/*.{gif,jpg,jpeg,png,svg,webp}',
            '<%= yeoman.dist %>/_fonts/**/*.{eot*,otf,svg,ttf,woff}'
          ]
        }]
      }
    },
    buildcontrol: {
      dist: {
        options: {
          remote: 'https://github.com/ilkelma/ilkelma.github.io.git',
          branch: 'master',
          commit: true,
          push: true
        }
      }
    },
    coffeelint: {
      options: {
        'max_line_length': {
          'level': 'ignore'
        }
      },
      check: ['<%= yeoman.app %>/_src/*.coffee']
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/_js/**/*.js',
        'test/spec/**/*.js'
      ]
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc'
      },
      check: {
        src: [
          '<%= yeoman.app %>/_css/**/*.css',
          '<%= yeoman.app %>/_scss/**/*.scss'
        ]
      }
    },
    concurrent: {
      server: [
        'compass:server',
        'coffee:dist',
        'copy:stageCss',
        'jekyll:server'
      ],
      dist: [
        'compass:dist',
        'coffee:dist',
        'copy:dist'
      ]
    }
  });

  // Define Tasks
  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',
      'autoprefixer:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', function () {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve']);
  });

  // No real tests yet. Add your own.
  grunt.registerTask('test', [
  //   'clean:server',
  //   'concurrent:test',
  //   'connect:test'
  ]);

  grunt.registerTask('check', [
    'clean:server',
    'jekyll:check',
    'compass:server',
    'coffeelint:check',
    'coffee:dist',
    'jshint:all',
    'csslint:check'
  ]);

  grunt.registerTask('build', [
    'clean',
    // Jekyll cleans files from the target directory, so must run first
    'jekyll:dist',
    'concurrent:dist',
    'useminPrepare',
    'concat',
    'autoprefixer:dist',
    'cssmin',
    'uglify',
    'imagemin',
    'svgmin',
    'filerev',
    'usemin',
    'htmlmin'
    ]);

  grunt.registerTask('deploy', [
    'check',
    'test',
    'build',
    'buildcontrol'
    ]);

  grunt.registerTask('default', [
    'check',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { defineMessages, FormattedMessage } from 'react-intl'
import { Link } from 'react-router'

import Contributors from '../components/Contributors'
import Publications from '../components/Publications'
import Genres from '../components/Genres'
import Subjects from '../components/Subjects'
import * as ResourceActions from '../actions/ResourceActions'
import * as ReservationActions from '../actions/ReservationActions'
import * as ParameterActions from '../actions/ParameterActions'

class Work extends React.Component {
  componentWillMount () {
    this.props.resourceActions.fetchWorkResource(this.props.params.workId)
  }

  renderNoWork () {
    return (

        <FormattedMessage {...messages.noWork} />

    )
  }

  renderEmpty () {
    return

  }

  renderTitle (work) {
    let title = work.mainTitle
    if (work.partTitle) {
      title += ` — ${work.partTitle}`
    }
    return title
  }

  renderYear (work) {
    if (work.publicationYear) {
      return (

          <FormattedMessage {...messages.firstTimePublished} /> {work.publicationYear}

      )
    }
    return
  }

  render () {
    // TODO Better renderEmpty and showing something while it loads the resource.
    if (this.props.isRequesting) {
      return this.renderEmpty()
    }
    let work = this.props.resources[ this.props.params.workId ]
    if (!work) {
      return this.renderNoWork()
    } else {
      work = { ...work }
    }

    if (this.props.params.publicationId) {
      const chosenPublication = work.publications.find(publication => publication.id === this.props.params.publicationId)
      if (chosenPublication) {
        work.mainTitle = chosenPublication.mainTitle
        work.partTitle = chosenPublication.partTitle
        if (chosenPublication.image) {
          work.image = chosenPublication.image
        }
      }
    }

    const { back } = this.props.location.query
    return (

          {back && back.startsWith('/search') // We don't want to allow arbitrary URLs in the back parameter
            ? (

              <Link to={this.props.location.query.back} alt='Back to search page'>Tilbake til søkeresultat</Link>

          ) : ''}

              {work.image ?  : null}

{this.renderTitle(work)}

              <Contributors contributors={work.contributors} />
              {this.renderYear(work)}

              <Subjects subjects={work.subjects} />

              <Genres genres={work.genres} />

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget massa
                id mauris maximus porta. In
                dignissim, metus in elementum ultrices, erat velit gravida turpis, id efficitur nunc est vitae purus.
                Aliquam ornare efficitur tellus sit amet dapibus. Aliquam ultrices, sapien in volutpat vehicula, lacus
                nunc pretium leo, quis dignissim arcu nisl vitae velit. Aliquam sit amet nisl non tortor elementum
                consequat. Morbi id nulla ac quam luctus posuere nec a risus. Aenean congue quam tortor, a volutpat
                quam mollis nec. Nullam metus ex, efficitur vitae tortor vitae, imperdiet semper nisl. Mauris vel
                accumsan odio, venenatis fringilla ex.

              <button className='black-btn' type='button'>Bestill første ledige</button>
              <button className='white-btn-checkmark' type='button'>Min huskeliste</button>

              <Subjects subjects={work.subjects} />

              <Genres genres={work.genres} />

          <Publications locationQuery={this.props.location.query}
                        expandSubResource={this.props.resourceActions.expandSubResource}
                        publications={work.publications}
                        startReservation={this.props.reservationActions.startReservation}
                        toggleParameter={this.props.parameterActions.toggleParameter}
          />

    )
  }
}

Work.propTypes = {
  resourceActions: PropTypes.object.isRequired,
  resources: PropTypes.object.isRequired,
  isRequesting: PropTypes.bool.isRequired,
  dispatch: PropTypes.func.isRequired,
  params: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  reservationActions: PropTypes.object.isRequired,
  parameterActions: PropTypes.object.isRequired
}

const messages = defineMessages({
  noWork: {
    id: 'Work.noWork',
    description: 'When no work was found',
    defaultMessage: 'No work'
  },
  firstTimePublished: {
    id: 'Work.firstTimePublished',
    description: 'The year the work was first published',
    defaultMessage: 'First published:'
  },
  workInformation: {
    id: 'Work.workInformation',
    description: 'The header text for the work information',
    defaultMessage: 'Work information'
  }
})

function mapStateToProps (state) {
  return {
    resources: state.resources.resources,
    isRequesting: state.resources.isRequesting
  }
}

function mapDispatchToProps (dispatch) {
  return {
    dispatch: dispatch,
    resourceActions: bindActionCreators(ResourceActions, dispatch),
    reservationActions: bindActionCreators(ReservationActions, dispatch),
    parameterActions: bindActionCreators(ParameterActions, dispatch)
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Work)
<commit_msg>patron-client: Placeholder status on reserve first button and huskeliste-area<commit_after>import React, { PropTypes } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { defineMessages, FormattedMessage } from 'react-intl'
import { Link } from 'react-router'

import Contributors from '../components/Contributors'
import Publications from '../components/Publications'
import Genres from '../components/Genres'
import Subjects from '../components/Subjects'
import * as ResourceActions from '../actions/ResourceActions'
import * as ReservationActions from '../actions/ReservationActions'
import * as ParameterActions from '../actions/ParameterActions'

class Work extends React.Component {
  componentWillMount () {
    this.props.resourceActions.fetchWorkResource(this.props.params.workId)
  }

  renderNoWork () {
    return (

        <FormattedMessage {...messages.noWork} />

    )
  }

  renderEmpty () {
    return

  }

  renderTitle (work) {
    let title = work.mainTitle
    if (work.partTitle) {
      title += ` — ${work.partTitle}`
    }
    return title
  }

  renderYear (work) {
    if (work.publicationYear) {
      return (

          <FormattedMessage {...messages.firstTimePublished} /> {work.publicationYear}

      )
    }
    return
  }

  render () {
    // TODO Better renderEmpty and showing something while it loads the resource.
    if (this.props.isRequesting) {
      return this.renderEmpty()
    }
    let work = this.props.resources[ this.props.params.workId ]
    if (!work) {
      return this.renderNoWork()
    } else {
      work = { ...work }
    }

    if (this.props.params.publicationId) {
      const chosenPublication = work.publications.find(publication => publication.id === this.props.params.publicationId)
      if (chosenPublication) {
        work.mainTitle = chosenPublication.mainTitle
        work.partTitle = chosenPublication.partTitle
        if (chosenPublication.image) {
          work.image = chosenPublication.image
        }
      }
    }

    const { back } = this.props.location.query
    return (

          {back && back.startsWith('/search') // We don't want to allow arbitrary URLs in the back parameter
            ? (

              <Link to={this.props.location.query.back} alt='Back to search page'>Tilbake til søkeresultat</Link>

          ) : ''}

              {work.image ?  : null}

{this.renderTitle(work)}

              <Contributors contributors={work.contributors} />
              {this.renderYear(work)}

              <Subjects subjects={work.subjects} />

              <Genres genres={work.genres} />

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget massa
                id mauris maximus porta. In
                dignissim, metus in elementum ultrices, erat velit gravida turpis, id efficitur nunc est vitae purus.
                Aliquam ornare efficitur tellus sit amet dapibus. Aliquam ultrices, sapien in volutpat vehicula, lacus
                nunc pretium leo, quis dignissim arcu nisl vitae velit. Aliquam sit amet nisl non tortor elementum
                consequat. Morbi id nulla ac quam luctus posuere nec a risus. Aenean congue quam tortor, a volutpat
                quam mollis nec. Nullam metus ex, efficitur vitae tortor vitae, imperdiet semper nisl. Mauris vel
                accumsan odio, venenatis fringilla ex.

              <button className='black-btn patron-placeholder' type='button'>Bestill første ledige</button>
              <button className='white-btn-checkmark patron-placeholder' type='button'>Min huskeliste</button>

              <Subjects subjects={work.subjects} />

              <Genres genres={work.genres} />

          <Publications locationQuery={this.props.location.query}
                        expandSubResource={this.props.resourceActions.expandSubResource}
                        publications={work.publications}
                        startReservation={this.props.reservationActions.startReservation}
                        toggleParameter={this.props.parameterActions.toggleParameter}
          />

    )
  }
}

Work.propTypes = {
  resourceActions: PropTypes.object.isRequired,
  resources: PropTypes.object.isRequired,
  isRequesting: PropTypes.bool.isRequired,
  dispatch: PropTypes.func.isRequired,
  params: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  reservationActions: PropTypes.object.isRequired,
  parameterActions: PropTypes.object.isRequired
}

const messages = defineMessages({
  noWork: {
    id: 'Work.noWork',
    description: 'When no work was found',
    defaultMessage: 'No work'
  },
  firstTimePublished: {
    id: 'Work.firstTimePublished',
    description: 'The year the work was first published',
    defaultMessage: 'First published:'
  },
  workInformation: {
    id: 'Work.workInformation',
    description: 'The header text for the work information',
    defaultMessage: 'Work information'
  }
})

function mapStateToProps (state) {
  return {
    resources: state.resources.resources,
    isRequesting: state.resources.isRequesting
  }
}

function mapDispatchToProps (dispatch) {
  return {
    dispatch: dispatch,
    resourceActions: bindActionCreators(ResourceActions, dispatch),
    reservationActions: bindActionCreators(ReservationActions, dispatch),
    parameterActions: bindActionCreators(ParameterActions, dispatch)
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Work)
<|endoftext|>


<commit_before>import jsonrpc from '../utils/jsonrpc'
import { pushPath } from 'redux-simple-router'

export const SELECT_CORPUS = '§_SELECT_CORPUS'

export const FETCH_CORPUS_STATUS_REQUEST = '§_FETCH_CORPUS_STATUS_REQUEST'
export const FETCH_CORPUS_STATUS_SUCCESS = '§_FETCH_CORPUS_STATUS_SUCCESS'
export const FETCH_CORPUS_STATUS_FAILURE = '§_FETCH_CORPUS_STATUS_FAILURE'

export const START_CORPUS_REQUEST = '§_START_CORPUS_REQUEST'
export const START_CORPUS_SUCCESS = '§_START_CORPUS_SUCCESS'
export const START_CORPUS_FAILURE = '§_START_CORPUS_FAILURE'

export const CREATE_CORPUS_REQUEST = '§_CREATE_CORPUS_REQUEST'
export const CREATE_CORPUS_SUCCESS = '§_CREATE_CORPUS_SUCCESS'
export const CREATE_CORPUS_FAILURE = '§_CREATE_CORPUS_FAILURE'

export const selectCorpus = (corpus) => (dispatch) => {
  dispatch({
    type: SELECT_CORPUS,
    payload: {
      corpus
    }
  })

  dispatch(pushPath('/browser'))
}

export const requestCorpusStatus = (corpus) => ({
  type: FETCH_CORPUS_STATUS_REQUEST,
  payload: { corpus }
})

export const receiveCorpusStatus = (corpus, status) => ({
  type: FETCH_CORPUS_STATUS_SUCCESS,
  payload: {
    corpus,
    status
  }
})

export const fetchCorpusStatus = (serverUrl, corpus) => (dispatch) => {
  dispatch(requestCorpusStatus(corpus))

  return jsonrpc(serverUrl)('get_status', [corpus.corpus_id])
    .then((status) => dispatch(receiveCorpusStatus(corpus, status)))
    .catch((err) => dispatch({
      type: FETCH_CORPUS_STATUS_FAILURE,
      payload: err
    }))
}

export const startCorpus = (serverUrl, corpus, password) => (dispatch) => {
  dispatch({ type: START_CORPUS_REQUEST, payload: { corpus } })

  return jsonrpc(serverUrl)('start_corpus', [corpus.corpus_id, password])
    .then(() => dispatch({ type: START_CORPUS_SUCCESS, payload: { corpus } }))
    .catch((error) => dispatch({ type: START_CORPUS_FAILURE, payload: { corpus, error } }))
}

export const receiveCorpus = (serverUrl, corpus) => ({
  type: CREATE_CORPUS_SUCCESS,
  payload: {
    serverUrl,
    corpus
  }
})

export const createCorpus = (serverUrl, corpus) => (dispatch) => {
  dispatch({
    type: CREATE_CORPUS_REQUEST,
    payload: {
      serverUrl,
      corpus
    }
  })

  return jsonrpc(serverUrl)('create_corpus', corpus)
    .then((res) => dispatch(receiveCorpus(serverUrl, res)))
    .catch((err) => dispatch({
      type: CREATE_CORPUS_FAILURE,
      payload: err
    }))
}
<commit_msg>fix(RPC): create_corpus call<commit_after>import jsonrpc from '../utils/jsonrpc'
import { pushPath } from 'redux-simple-router'

export const SELECT_CORPUS = '§_SELECT_CORPUS'

export const FETCH_CORPUS_STATUS_REQUEST = '§_FETCH_CORPUS_STATUS_REQUEST'
export const FETCH_CORPUS_STATUS_SUCCESS = '§_FETCH_CORPUS_STATUS_SUCCESS'
export const FETCH_CORPUS_STATUS_FAILURE = '§_FETCH_CORPUS_STATUS_FAILURE'

export const START_CORPUS_REQUEST = '§_START_CORPUS_REQUEST'
export const START_CORPUS_SUCCESS = '§_START_CORPUS_SUCCESS'
export const START_CORPUS_FAILURE = '§_START_CORPUS_FAILURE'

export const CREATE_CORPUS_REQUEST = '§_CREATE_CORPUS_REQUEST'
export const CREATE_CORPUS_SUCCESS = '§_CREATE_CORPUS_SUCCESS'
export const CREATE_CORPUS_FAILURE = '§_CREATE_CORPUS_FAILURE'

export const selectCorpus = (corpus) => (dispatch) => {
  dispatch({
    type: SELECT_CORPUS,
    payload: {
      corpus
    }
  })

  dispatch(pushPath('/browser'))
}

export const requestCorpusStatus = (corpus) => ({
  type: FETCH_CORPUS_STATUS_REQUEST,
  payload: { corpus }
})

export const receiveCorpusStatus = (corpus, status) => ({
  type: FETCH_CORPUS_STATUS_SUCCESS,
  payload: {
    corpus,
    status
  }
})

export const fetchCorpusStatus = (serverUrl, corpus) => (dispatch) => {
  dispatch(requestCorpusStatus(corpus))

  return jsonrpc(serverUrl)('get_status', [corpus.corpus_id])
    .then((status) => dispatch(receiveCorpusStatus(corpus, status)))
    .catch((err) => dispatch({
      type: FETCH_CORPUS_STATUS_FAILURE,
      payload: err
    }))
}

export const startCorpus = (serverUrl, corpus, password) => (dispatch) => {
  dispatch({ type: START_CORPUS_REQUEST, payload: { corpus } })

  return jsonrpc(serverUrl)('start_corpus', [corpus.corpus_id, password])
    .then(() => dispatch({ type: START_CORPUS_SUCCESS, payload: { corpus } }))
    .catch((error) => dispatch({ type: START_CORPUS_FAILURE, payload: { corpus, error } }))
}

export const receiveCorpus = (serverUrl, corpus) => ({
  type: CREATE_CORPUS_SUCCESS,
  payload: {
    serverUrl,
    corpus
  }
})

export const createCorpus = (serverUrl, corpus) => (dispatch) => {
  dispatch({
    type: CREATE_CORPUS_REQUEST,
    payload: {
      serverUrl,
      corpus
    }
  })

  return jsonrpc(serverUrl)('create_corpus', [corpus.name, corpus.password])
    .then((res) => dispatch(receiveCorpus(serverUrl, res)))
    .catch((err) => dispatch({
      type: CREATE_CORPUS_FAILURE,
      payload: err
    }))
}
<|endoftext|>


<commit_before>function(doc) {
  if (doc.created_at) {
      var p = doc.profile || {};
      emit(doc.created_at, {
          message:doc.message,
          gravatar_url : p.gravatar_url,
          nickname : p.nickname,
          name : doc.name
      });
  }
};<commit_msg>removed recent-items view<commit_after><|endoftext|>


<commit_before>import React, { cloneElement } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import all from 'react-prop-types/lib/all';
import warning from 'warning';
import keycode from 'keycode';
import tbsUtils, { bsStyles, bsClass as _bsClass } from './utils/bootstrapUtils';
import { nextEnabled, TAB, PANE } from './utils/tabUtils';

import ValidComponentChildren from './utils/ValidComponentChildren';
import chain from './utils/createChainedFunction';

class Nav extends React.Component {

  componentDidUpdate() {
    if (this._needsRefocus) {
      let ul = this.refs.ul && ReactDOM.findDOMNode(this.refs.ul);
      let tabs = ul ? ul.children || [] : [];
      let tabIdx = this.eventKeys().indexOf(this.getActiveKey());

      this._needsRefocus = false;

      if (tabIdx !== -1) {
        let tabNode = tabs[tabIdx];

        if (tabNode && tabNode.firstChild) {
          tabNode.firstChild.focus();
        }
      }
    }
  }

  render() {
    const { className } = this.props;
    const isNavbar = this.props.navbar != null ? this.props.navbar : this.context.$bs_navbar;

    const classes = tbsUtils.getClassSet(this.props);

    classes[tbsUtils.prefix(this.props, 'stacked')] = this.props.stacked;
    classes[tbsUtils.prefix(this.props, 'justified')] = this.props.justified;

    if (isNavbar) {
      let bsClass = this.context.$bs_navbar_bsClass || 'navbar';

      classes[tbsUtils.prefix({ bsClass }, 'nav')] = true;
      classes[tbsUtils.prefix({ bsClass }, 'right')] = this.props.pullRight;
      classes[tbsUtils.prefix({ bsClass }, 'left')] = this.props.pullLeft;
    } else {
      classes['pull-right'] = this.props.pullRight;
      classes['pull-left'] = this.props.pullLeft;
    }

    let list = (

        {ValidComponentChildren.map(this.props.children, this.renderNavItem, this)}

    );

    return list;
  }

  renderNavItem(child, index) {
    let onSelect = chain(child.props.onSelect, this.props.onSelect);
    let active = this.isChildActive(child);
    let tabProps = this.getTabProps(child, index, active, onSelect);

    return cloneElement(
      child,
      {
        active,
        onSelect,
        key: child.key || index,
        navItem: true,
        ...tabProps
      }
    );
  }

  getActiveKey(props = this.props, context = this.context) {
    let activeKey = props.activeKey;

    context = this.getContext('$bs_tabcontainer', context);

    if (context.activeKey) {
      warning(activeKey == null || props.activeHref,
        'Specifing a Nav `activeKey` or `activeHref` prop in the context of a `TabContainer` is not supported. ' +
        'Instead use `<TabContainer activeKey={' + activeKey + '} />`');

      activeKey = context.activeKey;
    }

    return activeKey;
  }

  isChildActive(child) {
    let activeKey = this.getActiveKey();

    if (this.context.$bs_tabcontainer) {
      warning(!child.props.active,
        'Specifing a NavItem `active` prop in the context of a `TabContainer` is not supported. Instead ' +
        'use `<TabContainer activeKey={' + child.props.eventKey + '} />`');

      return child.props.eventKey === activeKey;
    }

    if (child.props.active) {
      return true;
    }
    if (this.props.activeKey != null) {
      if (child.props.eventKey === this.props.activeKey) {
        return true;
      }
    }
    if (this.props.activeHref != null) {
      if (child.props.href === this.props.activeHref) {
        return true;
      }
    }

    return child.props.active;
  }

  getTabProps(child, idx, isActive, onSelect) {
    let {
        linkId
      , 'aria-controls': controls
      , eventKey
      , role
      , onKeyDown
      , tabIndex = 0 } = child.props;

    let navRole = this.getNavRole();
    let context = this.getContext('$bs_tabcontainer');

    if (context.getId) {
      warning(!(linkId || controls),
        'In the context of a TabContainer, NavItems are given generated `linkId` and `aria-controls` ' +
        'attributes for the sake of proper component accessibility. Any provided ones will be ignored. ' +
        'To control these attributes directly provide a `generateChildId` prop to the parent TabContainer.'
      );

      linkId = context.getId(eventKey, TAB) || null;
      controls = context.getId(eventKey, PANE) || null;
      onSelect = chain(onSelect, context.onSelect);
    }

    if (navRole === 'tablist') {
      role = role || 'tab';
      onKeyDown = chain(
        this.handleTabKeyDown.bind(this, onSelect || (()=>{})),
        onKeyDown
      );
    }

    return {
      onSelect,
      linkId,
      role,
      onKeyDown,
      'aria-controls': controls,
      tabIndex: isActive ? tabIndex : -1
    };
  }

  handleTabKeyDown(onSelect, event) {
    let keys = this.eventKeys();
    let currentKey = this.getActiveKey() || keys[0];
    let next;

    switch (event.keyCode) {

    case keycode.codes.left:
    case keycode.codes.up:
      next = nextEnabled(this.props.children, currentKey, keys, false);

      if (next && next !== currentKey) {
        event.preventDefault();
        onSelect(next);
        this._needsRefocus = true;
      }
      break;
    case keycode.codes.right:
    case keycode.codes.down:
      next = nextEnabled(this.props.children, currentKey, keys, true);

      if (next && next !== currentKey) {
        event.preventDefault();
        onSelect(next);
        this._needsRefocus = true;
      }
      break;
    default:
    }
  }

  eventKeys() {
    let keys = [];
    ValidComponentChildren.forEach(this.props.children,
      ({props: { eventKey }}) => keys.push(eventKey));
    return keys;
  }

  getNavRole() {
    return this.props.role || (this.context.$bs_tabcontainer ? 'tablist' : null);
  }

  getContext(key) {
    return this.context[key] || {};
  }
}

Nav.propTypes = {

  /**
   * Marks the child NavItem with a matching `href` prop as active.
   */
  activeHref: React.PropTypes.string,

  /**
   * Marks the NavItem with a matching `eventKey` as active. Has a
   * higher precedence over `activeHref`.
   */
  activeKey: React.PropTypes.any,

  /**
   * NavItems are be positioned vertically.
   */
  stacked: React.PropTypes.bool,

  justified: all(
    React.PropTypes.bool,
    ({justified, navbar}) => (
      justified && navbar ?
        Error('justified navbar `Nav`s are not supported') : null
    )
  ),

  /**
   * A callback fired when a NavItem is selected.
   *
   * ```js
   * function (
   * 	Any eventKey,
   * 	SyntheticEvent event?
   * )
   * ```
   */
  onSelect: React.PropTypes.func,

  /**
   * CSS classes for the wrapper `nav` element
   */
  className: React.PropTypes.string,
  /**
   * HTML id for the wrapper `nav` element
   */
  id: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),

  /**
   * ARIA role for the Nav, in the context of a TabContainer, the default will be set
   * to "tablist", but can be overridden by the Nav when set explicitly.
   *
   * When the role is set to "tablist" NavItem focus is managed according to the
   * ARIA authoring practices for tabs: https://www.w3.org/TR/2013/WD-wai-aria-practices-20130307/#tabpanel
   */
  role: React.PropTypes.string,

  /**
   * Apply styling an alignment for use in a Navbar. This prop will be set
   * automatically when the Nav is used inside a Navbar.
   */
  navbar: React.PropTypes.bool,

  /**
   * Float the Nav to the right. When `navbar` is `true` the appropriate
   * contextual classes are added as well.
   */
  pullRight: React.PropTypes.bool,

  /**
   * Float the Nav to the left. When `navbar` is `true` the appropriate
   * contextual classes are added as well.
   */
  pullLeft: React.PropTypes.bool,
};

Nav.contextTypes = {
  $bs_navbar: React.PropTypes.bool,
  $bs_navbar_bsClass: React.PropTypes.string,

  $bs_tabcontainer: React.PropTypes.shape({
    activeKey: React.PropTypes.any,
    onSelect: React.PropTypes.func,
    getId: React.PropTypes.func
  })
};

Nav.defaultProps = {
  justified: false,
  pullRight: false,
  pullLeft: false,
  stacked: false
};

export default _bsClass('nav',
  bsStyles(['tabs', 'pills'],
    Nav
  )
);
<commit_msg>Fix handling of tab props in <commit_after>import React, { cloneElement } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import all from 'react-prop-types/lib/all';
import warning from 'warning';
import keycode from 'keycode';
import tbsUtils, { bsStyles, bsClass as _bsClass } from './utils/bootstrapUtils';
import { nextEnabled, TAB, PANE } from './utils/tabUtils';

import ValidComponentChildren from './utils/ValidComponentChildren';
import chain from './utils/createChainedFunction';

class Nav extends React.Component {

  componentDidUpdate() {
    if (this._needsRefocus) {
      let ul = this.refs.ul && ReactDOM.findDOMNode(this.refs.ul);
      let tabs = ul ? ul.children || [] : [];
      let tabIdx = this.eventKeys().indexOf(this.getActiveKey());

      this._needsRefocus = false;

      if (tabIdx !== -1) {
        let tabNode = tabs[tabIdx];

        if (tabNode && tabNode.firstChild) {
          tabNode.firstChild.focus();
        }
      }
    }
  }

  render() {
    const { className } = this.props;
    const isNavbar = this.props.navbar != null ? this.props.navbar : this.context.$bs_navbar;

    const classes = tbsUtils.getClassSet(this.props);

    classes[tbsUtils.prefix(this.props, 'stacked')] = this.props.stacked;
    classes[tbsUtils.prefix(this.props, 'justified')] = this.props.justified;

    if (isNavbar) {
      let bsClass = this.context.$bs_navbar_bsClass || 'navbar';

      classes[tbsUtils.prefix({ bsClass }, 'nav')] = true;
      classes[tbsUtils.prefix({ bsClass }, 'right')] = this.props.pullRight;
      classes[tbsUtils.prefix({ bsClass }, 'left')] = this.props.pullLeft;
    } else {
      classes['pull-right'] = this.props.pullRight;
      classes['pull-left'] = this.props.pullLeft;
    }

    let list = (

        {ValidComponentChildren.map(this.props.children, this.renderNavItem, this)}

    );

    return list;
  }

  renderNavItem(child, index) {
    let onSelect = chain(child.props.onSelect, this.props.onSelect);
    let active = this.isChildActive(child);
    let tabProps = this.getTabProps(child, active, onSelect);

    return cloneElement(
      child,
      {
        active,
        onSelect,
        key: child.key || index,
        navItem: true,
        ...tabProps
      }
    );
  }

  getActiveKey() {
    const context = this.context.$bs_tabcontainer;
    if (!context) {
      return this.props.activeKey;
    }

    warning(!(this.props.activeKey != null || this.props.activeHref),
      'Specifing a Nav `activeKey` or `activeHref` prop in the context of a `TabContainer` is not supported. ' +
      'Instead use `<TabContainer activeKey={' + this.props.activeKey + '} />`');

    return context.activeKey;
  }

  isChildActive(child) {
    let activeKey = this.getActiveKey();

    if (this.context.$bs_tabcontainer) {
      warning(!child.props.active,
        'Specifing a NavItem `active` prop in the context of a `TabContainer` is not supported. Instead ' +
        'use `<TabContainer activeKey={' + child.props.eventKey + '} />`');

      return child.props.eventKey === activeKey;
    }

    if (child.props.active) {
      return true;
    }
    if (this.props.activeKey != null) {
      if (child.props.eventKey === this.props.activeKey) {
        return true;
      }
    }
    if (this.props.activeHref != null) {
      if (child.props.href === this.props.activeHref) {
        return true;
      }
    }

    return child.props.active;
  }

  getTabProps(child, isActive, onSelect) {
    const navRole = this.getNavRole();
    const context = this.context.$bs_tabcontainer;

    if (!context && navRole !== 'tablist') {
      // No tab props here.
      return null;
    }

    let {
        linkId
      , 'aria-controls': controls
      , eventKey
      , role
      , onKeyDown
      , tabIndex = 0 } = child.props;

    if (context && context.getId) {
      warning(!(linkId || controls),
        'In the context of a TabContainer, NavItems are given generated `linkId` and `aria-controls` ' +
        'attributes for the sake of proper component accessibility. Any provided ones will be ignored. ' +
        'To control these attributes directly provide a `generateChildId` prop to the parent TabContainer.'
      );

      linkId = context.getId(eventKey, TAB) || null;
      controls = context.getId(eventKey, PANE) || null;
      onSelect = chain(onSelect, context.onSelect);
    }

    if (navRole === 'tablist') {
      role = role || 'tab';
      onKeyDown = chain(
        this.handleTabKeyDown.bind(this, onSelect || (()=>{})),
        onKeyDown
      );
      tabIndex = isActive ? tabIndex : -1;
    }

    return {
      onSelect,
      linkId,
      role,
      onKeyDown,
      'aria-controls': controls,
      tabIndex,
    };
  }

  handleTabKeyDown(onSelect, event) {
    let keys = this.eventKeys();
    let currentKey = this.getActiveKey() || keys[0];
    let next;

    switch (event.keyCode) {

    case keycode.codes.left:
    case keycode.codes.up:
      next = nextEnabled(this.props.children, currentKey, keys, false);

      if (next && next !== currentKey) {
        event.preventDefault();
        onSelect(next);
        this._needsRefocus = true;
      }
      break;
    case keycode.codes.right:
    case keycode.codes.down:
      next = nextEnabled(this.props.children, currentKey, keys, true);

      if (next && next !== currentKey) {
        event.preventDefault();
        onSelect(next);
        this._needsRefocus = true;
      }
      break;
    default:
    }
  }

  eventKeys() {
    let keys = [];
    ValidComponentChildren.forEach(this.props.children,
      ({props: { eventKey }}) => keys.push(eventKey));
    return keys;
  }

  getNavRole() {
    return this.props.role || (this.context.$bs_tabcontainer ? 'tablist' : null);
  }
}

Nav.propTypes = {

  /**
   * Marks the child NavItem with a matching `href` prop as active.
   */
  activeHref: React.PropTypes.string,

  /**
   * Marks the NavItem with a matching `eventKey` as active. Has a
   * higher precedence over `activeHref`.
   */
  activeKey: React.PropTypes.any,

  /**
   * NavItems are be positioned vertically.
   */
  stacked: React.PropTypes.bool,

  justified: all(
    React.PropTypes.bool,
    ({justified, navbar}) => (
      justified && navbar ?
        Error('justified navbar `Nav`s are not supported') : null
    )
  ),

  /**
   * A callback fired when a NavItem is selected.
   *
   * ```js
   * function (
   * 	Any eventKey,
   * 	SyntheticEvent event?
   * )
   * ```
   */
  onSelect: React.PropTypes.func,

  /**
   * CSS classes for the wrapper `nav` element
   */
  className: React.PropTypes.string,
  /**
   * HTML id for the wrapper `nav` element
   */
  id: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),

  /**
   * ARIA role for the Nav, in the context of a TabContainer, the default will be set
   * to "tablist", but can be overridden by the Nav when set explicitly.
   *
   * When the role is set to "tablist" NavItem focus is managed according to the
   * ARIA authoring practices for tabs: https://www.w3.org/TR/2013/WD-wai-aria-practices-20130307/#tabpanel
   */
  role: React.PropTypes.string,

  /**
   * Apply styling an alignment for use in a Navbar. This prop will be set
   * automatically when the Nav is used inside a Navbar.
   */
  navbar: React.PropTypes.bool,

  /**
   * Float the Nav to the right. When `navbar` is `true` the appropriate
   * contextual classes are added as well.
   */
  pullRight: React.PropTypes.bool,

  /**
   * Float the Nav to the left. When `navbar` is `true` the appropriate
   * contextual classes are added as well.
   */
  pullLeft: React.PropTypes.bool,
};

Nav.contextTypes = {
  $bs_navbar: React.PropTypes.bool,
  $bs_navbar_bsClass: React.PropTypes.string,

  $bs_tabcontainer: React.PropTypes.shape({
    activeKey: React.PropTypes.any,
    onSelect: React.PropTypes.func,
    getId: React.PropTypes.func
  })
};

Nav.defaultProps = {
  justified: false,
  pullRight: false,
  pullLeft: false,
  stacked: false
};

export default _bsClass('nav',
  bsStyles(['tabs', 'pills'],
    Nav
  )
);
<|endoftext|>


<commit_before>function ToAppWindow(title, TiTwilio){
  var self = Ti.UI.createWindow({
    backgroundColor: '#CCEAEE',
    barImage: '/images/navBar.png',
    barColor: "#99cccc",
    layout: 'vertical',
    title: title });

  var me = Ti.UI.createTextField({
    top: 10,
    hintText: '自分の名前(アルファベット)',
    borderStyle : Titanium.UI.INPUT_BORDERSTYLE_BEZEL,
    left: 10,
    right: 10
  });
  self.add(me);

  var login = Ti.UI.createButton({
    title: 'ログイン',
    width: Ti.UI.SIZE,
    height: Ti.UI.SIZE,
    top: 10
  });
  var pendingIntent;
  if(Ti.Platform.osname === 'android'){
    var intent = Ti.Android.createServiceIntent({url:'service.js', twilio: TiTwilio});
    pendingIntent = Ti.Android.createPendingIntent({intent: intent});
  }
  function login_func(){
    TiTwilio.login({
      url: 'http://dev.voidoid.com/auth?name=' + me.value,
      params: {name: Ti.App.Properties.getString('username'), type: 'login'},
      pendingIntent: pendingIntent
    });
  }
  login.addEventListener('click', function(){
    login_func();
  });
  if(Ti.Platform.osname === 'android'){
    self.add(login);
  }else{
    self.leftNavButton = login;
  }

  var you = Ti.UI.createTextField({
    top: 10,
    hintText: '相手の名前(アルファベット)',
    borderStyle : Titanium.UI.INPUT_BORDERSTYLE_BEZEL,
    left: 10,
    right: 10
  });
  self.add(you);

  var call = Ti.UI.createButton({
    title: '電話する',
    width: Ti.UI.SIZE,
    height: Ti.UI.SIZE,
    top: 10
  });
  call.addEventListener('click', function(){
    var dialog = Ti.UI.createAlertDialog({
      buttonNames: ['Disconnect'],
      title: '電話中',
      message: 'ボタンを押して切ってね'
    });
    dialog.show();
    dialog.addEventListener('click', function(){
      TiTwilio.disconnect();
    });
    TiTwilio.connect({
      url: 'http://dev.voidoid.com/auth',
      params: {name: me.value, to: you.value, type: 'call_to_app'}
    });
  });
  if(Ti.Platform.osname === 'android'){
    self.add(call);
  }else{
    self.rightNavButton = call;
  }

  return self;
}

module.exports = ToAppWindow;
<commit_msg>initial release<commit_after>function ToAppWindow(title, TiTwilio){
  var self = Ti.UI.createWindow({
    backgroundColor: '#CCEAEE',
    barImage: '/images/navBar.png',
    barColor: "#99cccc",
    layout: 'vertical',
    title: title });

  var me = Ti.UI.createTextField({
    top: 10,
    hintText: '自分の名前(アルファベット)',
    borderStyle : Titanium.UI.INPUT_BORDERSTYLE_BEZEL,
    backgroundColor: 'White',
    left: 10,
    right: 10
  });
  self.add(me);

  var login = Ti.UI.createButton({
    title: 'ログイン',
    width: Ti.UI.SIZE,
    height: Ti.UI.SIZE,
    top: 10
  });
  var pendingIntent;
  if(Ti.Platform.osname === 'android'){
    var intent = Ti.Android.createServiceIntent({url:'service.js', twilio: TiTwilio});
    pendingIntent = Ti.Android.createPendingIntent({intent: intent});
  }
  function login_func(){
    TiTwilio.login({
      url: 'http://dev.voidoid.com/auth?name=' + me.value,
      params: {name: Ti.App.Properties.getString('username'), type: 'login'},
      pendingIntent: pendingIntent
    });
  }
  login.addEventListener('click', function(){
    login_func();
  });
  if(Ti.Platform.osname === 'android'){
    self.add(login);
  }else{
    self.leftNavButton = login;
  }

  var you = Ti.UI.createTextField({
    top: 10,
    hintText: '相手の名前(アルファベット)',
    borderStyle : Titanium.UI.INPUT_BORDERSTYLE_BEZEL,
    backgroundColor: 'White',
    left: 10,
    right: 10
  });
  self.add(you);

  var call = Ti.UI.createButton({
    title: '電話する',
    width: Ti.UI.SIZE,
    height: Ti.UI.SIZE,
    top: 10
  });
  call.addEventListener('click', function(){
    var dialog = Ti.UI.createAlertDialog({
      buttonNames: ['Disconnect'],
      title: '電話中',
      message: 'ボタンを押して切ってね'
    });
    dialog.show();
    dialog.addEventListener('click', function(){
      TiTwilio.disconnect();
    });
    TiTwilio.connect({
      url: 'http://dev.voidoid.com/auth',
      params: {name: me.value, to: you.value, type: 'call_to_app'}
    });
  });
  if(Ti.Platform.osname === 'android'){
    self.add(call);
  }else{
    self.rightNavButton = call;
  }

  return self;
}

module.exports = ToAppWindow;
<|endoftext|>


<commit_before>
((module) => {
	'use strict';

	var createClassFromSuper = require('simple-class-utils').createClass.super;
	var createClass = require('./create-class.js');
	var isIterable = require('./utils/is-iterable.js');
	var Root = require('./root.js').class;

	var _key_iterator = Symbol.iterator;

	class ProductIterable extends Root {

		constructor(iterable, ...rest) {

			super();

			if (!rest.length) {
				return {
					* [_key_iterator]() {
						for (let element of iterable) {
							yield new ProductIterable.Result(element);
						}
					}
				};
			}

			this.first = iterable;
			this.second = new ProductIterable(...rest);

		}

		* [_key_iterator]() {
			for (let i of this.first) {
				for (let j of this.second) {
					yield new ProductIterable.Result(i, ...j);
				}
			}
		}

		static createXIterable(...classes) {
			return createClass(class extends ProductIterable.createXIterable.Root {

				constructor(...args) {
					this.args = args;
				}

				* [_key_iterator]() {

				}

			});
		}

	}

	module.exports = createClass(ProductIterable);

	ProductIterable.Result = createClassFromSuper(Array);

	ProductIterable.createXIterable.Root = createClassFromSuper(Root);

})(module);
<commit_msg>improve product-iterable<commit_after>
((module) => {
	'use strict';

	var createClassFromSuper = require('simple-class-utils').createClass.super;
	var createClass = require('./create-class.js');
	var isIterable = require('./utils/is-iterable.js');
	var Root = require('./root.js').class;
	var recursiveConstructor = require('./utils/recursive-constructor.js');

	var _key_iterator = Symbol.iterator;

	class ProductIterable extends Root {

		constructor(...args) {
			super();
			return recursiveConstructor(this, this.constructor, ...args);
		}

		* [_key_iterator]() {
			for (let i of this.first) {
				for (let j of this.second) {
					yield new ProductIterable.Result(i, ...j);
				}
			}
		}

		static createXIterable(...classes) {
			return createClass(class extends ProductIterable.createXIterable.Root {

				constructor(...args) {
					this.args = args;
				}

				* [_key_iterator]() {

				}

			});
		}

	}

	module.exports = createClass(ProductIterable);

	ProductIterable.Result = createClassFromSuper(Array);

	ProductIterable.createXIterable.Root = createClassFromSuper(Root);

})(module);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    watch = require('gulp-watch'),
    newer = require('gulp-newer'),
    concat = require('gulp-concat'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    uglify = require('gulp-uglify'),
    notifier = require("node-notifier"),
    gutil = require('gulp-util'),
    cssnano = require('gulp-cssnano'),
    debug = require('gulp-debug'),
    connect = require('gulp-connect'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    rimraf = require('gulp-rimraf'),
    browserify = require('browserify'),
    babelify = require('babelify'),
    iconfont = require('gulp-iconfont'),
    iconfontCss = require('gulp-iconfont-css'),

    imgDest = 'build/images',
    imgSource = './images/**/*';

  /**
   * Build custom js
   */
  gulp.task('buildCustomJS', function () {
    browserify({entries: './js/app.js', debug: true})
      .transform('babelify', {presets: ['es2015']})
      .bundle().on('error', function (err) {
        showError.apply(this, ['JS error', err])
      })
      .pipe(source('app.js'))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build js vendor (concatenate vendor array)
   */
  gulp.task('buildJsVendors', function () {
    gulp.src(require('./vendor_entries/vendor.js'))
      .pipe(concat('vendor.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build styles for application from SASS
   */
  gulp.task('buildSass', function () {
    gulp.src('./scss/app.scss')
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(sass().on('error', function (err) {
        showError.apply(this, ['Sass compile error', err]);
      }))
      .pipe(cssnano({safe: true}))
      .pipe(autoprefixer('last 2 versions'))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build styles for vendor from SASS
   */
  gulp.task('buildStylesVendors', function () {
    gulp.src('./vendor_entries/vendor.scss')
      .pipe(sass().on('error', function (err) {
        showError.apply(this, ['Sass compile error (vendor)', err]);
      }))
      .pipe(cssnano({safe: true}))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Images minification
   */
  gulp.task('imageMin', function () {
    gulp.src(imgSource)
      .pipe(newer(imgDest))
      .pipe(imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [pngquant()]
      }))
      .pipe(gulp.dest(imgDest));
  });

  /**
   * Clean image build directory
   */
  gulp.task('imageClean', function () {
    gulp.src(imgDest).pipe(rimraf());
  });

  /**
   * Watch for file changes
   */
  gulp.task('watch', function () {
    gulp.watch('./js/**/*', ['buildCustomJS']);
    gulp.watch('./vendor_entries/vendor.js', ['buildJsVendors']);
    watch('./scss/**/*', function () {
      gulp.run('buildSass');
    });
    gulp.watch('./vendor_entries/vendor.scss', ['buildStylesVendors']);
    watch('./images/**/*', function () {
      gulp.run('imageMin');
    });
    gulp.watch(['./build/*', './*.html']).on('change', function (file) {
      gulp.src(file.path).pipe(connect.reload());
    });
  });

  /**
   * Starting local server
   */
  gulp.task('startLocalhost', function () {
    connect.server({
      livereload: true
    });
  });

  /**
   * Creating production folder without unnecessary files
   */
  gulp.task('production', ['cleanProduction'], function () {
    gulp.src(['./**/*',
      '!vendor_entries',
      '!vendor_entries/**/*',
      '!images/',
      '!images/**/*',
      '!bower/',
      '!bower/**/*',
      '!js/',
      '!js/**/*',
      '!node_modules/**/*',
      '!node_modules/',
      '!scss/**/*',
      '!scss/',
      '!build/**.map',
      '!.bowerrc',
      '!bower.json',
      '!.gitignore',
      '!gulpfile.js',
      '!LICENSE',
      '!package.json',
      '!production',
      '!README.md'])
          .pipe(gulp.dest('./production'));
  });

  /**
   * Clean production folder
   */
  gulp.task('cleanProduction', function () {
    return gulp.src('./production/', {read: false})
      .pipe(rimraf());
  });

  /**
   * Make iconfont from svg icons
   */
  gulp.task('makeIconFont', function () {
    var fontName = 'iconfont';
    gulp.src(['./fonts/icons/*.svg'])
      .pipe(iconfontCss({
        fontName: fontName,
        fontPath: 'fonts/iconfont/'
      }))
      .pipe(iconfont({
        fontName: fontName,
        formats: ['ttf', 'eot', 'woff', 'svg', 'woff2'],
        normalize: true
       }))
      .pipe(gulp.dest('./scss/fonts/iconfont/'));
  });

  /**
   * Copy iconfont to the build folder
   */
  gulp.task('iconFont', ['makeIconFont'], function() {
    gulp.src('./scss/fonts/**/*')
      .pipe(gulp.dest('./build/fonts/'));
  });

  /**
   * Show error in console
   * @param  {String} preffix Title of the error
   * @param  {String} err     Error message
   */
  function showError(preffix, err) {
    gutil.log(gutil.colors.white.bgRed(' ' + preffix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
    notifier.notify({title:preffix, message: err.message });
    this.emit("end");
  }

  // Default Gulp Task
  gulp.task('default', ['buildCustomJS', 'buildSass', 'buildJsVendors', 'buildStylesVendors', 'imageMin', 'startLocalhost', 'watch']);
  gulp.task('dev', ['buildCustomJS', 'buildSass', 'buildJsVendors', 'buildStylesVendors', 'imageMin', 'watch']);

}());<commit_msg>Make makeIconfont task async<commit_after>(function () {
  'use strict';

  var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    watch = require('gulp-watch'),
    newer = require('gulp-newer'),
    concat = require('gulp-concat'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    uglify = require('gulp-uglify'),
    notifier = require("node-notifier"),
    gutil = require('gulp-util'),
    cssnano = require('gulp-cssnano'),
    debug = require('gulp-debug'),
    connect = require('gulp-connect'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    rimraf = require('gulp-rimraf'),
    browserify = require('browserify'),
    babelify = require('babelify'),
    iconfont = require('gulp-iconfont'),
    iconfontCss = require('gulp-iconfont-css'),

    imgDest = 'build/images',
    imgSource = './images/**/*';

  /**
   * Build custom js
   */
  gulp.task('buildCustomJS', function () {
    browserify({entries: './js/app.js', debug: true})
      .transform('babelify', {presets: ['es2015']})
      .bundle().on('error', function (err) {
        showError.apply(this, ['JS error', err])
      })
      .pipe(source('app.js'))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build js vendor (concatenate vendor array)
   */
  gulp.task('buildJsVendors', function () {
    gulp.src(require('./vendor_entries/vendor.js'))
      .pipe(concat('vendor.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build styles for application from SASS
   */
  gulp.task('buildSass', function () {
    gulp.src('./scss/app.scss')
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(sass().on('error', function (err) {
        showError.apply(this, ['Sass compile error', err]);
      }))
      .pipe(cssnano({safe: true}))
      .pipe(autoprefixer('last 2 versions'))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build styles for vendor from SASS
   */
  gulp.task('buildStylesVendors', function () {
    gulp.src('./vendor_entries/vendor.scss')
      .pipe(sass().on('error', function (err) {
        showError.apply(this, ['Sass compile error (vendor)', err]);
      }))
      .pipe(cssnano({safe: true}))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Images minification
   */
  gulp.task('imageMin', function () {
    gulp.src(imgSource)
      .pipe(newer(imgDest))
      .pipe(imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [pngquant()]
      }))
      .pipe(gulp.dest(imgDest));
  });

  /**
   * Clean image build directory
   */
  gulp.task('imageClean', function () {
    gulp.src(imgDest).pipe(rimraf());
  });

  /**
   * Watch for file changes
   */
  gulp.task('watch', function () {
    gulp.watch('./js/**/*', ['buildCustomJS']);
    gulp.watch('./vendor_entries/vendor.js', ['buildJsVendors']);
    watch('./scss/**/*', function () {
      gulp.run('buildSass');
    });
    gulp.watch('./vendor_entries/vendor.scss', ['buildStylesVendors']);
    watch('./images/**/*', function () {
      gulp.run('imageMin');
    });
    gulp.watch(['./build/*', './*.html']).on('change', function (file) {
      gulp.src(file.path).pipe(connect.reload());
    });
  });

  /**
   * Starting local server
   */
  gulp.task('startLocalhost', function () {
    connect.server({
      livereload: true
    });
  });

  /**
   * Creating production folder without unnecessary files
   */
  gulp.task('production', ['cleanProduction'], function () {
    gulp.src(['./**/*',
      '!vendor_entries',
      '!vendor_entries/**/*',
      '!images/',
      '!images/**/*',
      '!bower/',
      '!bower/**/*',
      '!js/',
      '!js/**/*',
      '!node_modules/**/*',
      '!node_modules/',
      '!scss/**/*',
      '!scss/',
      '!build/**.map',
      '!.bowerrc',
      '!bower.json',
      '!.gitignore',
      '!gulpfile.js',
      '!LICENSE',
      '!package.json',
      '!production',
      '!README.md'])
          .pipe(gulp.dest('./production'));
  });

  /**
   * Clean production folder
   */
  gulp.task('cleanProduction', function () {
    return gulp.src('./production/', {read: false})
      .pipe(rimraf());
  });

  /**
   * Make iconfont from svg icons
   */
  gulp.task('makeIconFont', function () {
    var fontName = 'iconfont';
    return gulp.src(['./fonts/icons/*.svg'])
      .pipe(iconfontCss({
        fontName: fontName,
        fontPath: 'fonts/iconfont/'
      }))
      .pipe(iconfont({
        fontName: fontName,
        formats: ['ttf', 'eot', 'woff', 'svg', 'woff2'],
        normalize: true
       }))
      .pipe(gulp.dest('./scss/fonts/iconfont/'));
  });

  /**
   * Copy iconfont to the build folder
   */
  gulp.task('iconFont', ['makeIconFont'], function() {
    gulp.src('./scss/fonts/**/*')
      .pipe(gulp.dest('./build/fonts/'));
  });

  /**
   * Show error in console
   * @param  {String} preffix Title of the error
   * @param  {String} err     Error message
   */
  function showError(preffix, err) {
    gutil.log(gutil.colors.white.bgRed(' ' + preffix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
    notifier.notify({title:preffix, message: err.message });
    this.emit("end");
  }

  // Default Gulp Task
  gulp.task('default', ['buildCustomJS', 'buildSass', 'buildJsVendors', 'buildStylesVendors', 'imageMin', 'startLocalhost', 'watch']);
  gulp.task('dev', ['buildCustomJS', 'buildSass', 'buildJsVendors', 'buildStylesVendors', 'imageMin', 'watch']);

}());<|endoftext|>


<commit_before>//
// Vote Template Helpers

Template.vote.helpers({

	isAdmin : function(){
		if(Meteor.user()){
			return Meteor.user().isAdmin;
		}
	},

	activeUsers : function(){
		if( Meteor.user() ){
			var returnArr = [];

			Meteor.users.find().forEach(function(user){
				var nameArr = user.profile.name.split(' ');
				returnArr.push( {name : nameArr[0] + ' ' + nameArr[1].substr(0, 1) } );
			});

			return returnArr;
		}
	},

	nominees : function(){
		return Nominees.find({}, {sort : [['name', 'asc']]});
	},

	results : function(){
		return Nominees.find({}, {sort : [['votes', 'desc']]});
	},

	title : function(){
		var setting = Settings.findOne({name : 'title'});

		if(setting){
			return setting.value;
		}	else {
		return 'Vote on...';
		}
	},

	votesPerUser : function(){
		var setting = Settings.findOne({name : 'votesPerUser'});

		if(setting){
			return setting.value;
		} else {
			return 5;
		}

	},

	allowDownVotes : function(){
		var setting = Settings.findOne({name : 'allowDownVotes'});

		if(setting){
			return setting.value;
		} else {
			return true;
		}

	},

	userVotes : function(){
		if(Meteor.user()){
			return Meteor.user().votes;
		}
	},

	canVote : function(){
		if(Session.get("meteor_loggedin")){
			return Meteor.user().votes > 0;
		} else {
			return false;
		}
	},

	canVoteUp : function(){
		if(Session.get("meteor_loggedin")){
			var user = Meteor.user(),
			nomineeVotes = NomineeVotes.findOne({nominee : this._id, user : user._id});

			if(user.votes > 0 ) return true;

			if(nomineeVotes && nomineeVotes.votes < 0){
				return true;
			} else {
				return false;
			}
		} else {
			return false
		}
	},

	canVoteDown : function(){
		if(Session.get("meteor_loggedin")){
			var user = Meteor.user(),
				nomineeVotes = NomineeVotes.findOne({nominee : this._id, user : user._id}),
				allowDownVotesSetting = Settings.findOne({name : 'allowDownVotes'});

			if(nomineeVotes.votes < 1 && !allowDownVotesSetting.value){
				return false;
			}

			if(user.votes > 0 ) return true;

			if(nomineeVotes && nomineeVotes.votes >=1){
				return true;
			} else {
				return false;
			}

		} else {
			return false;
		}
	},

	userVotesForNominee : function(){
		var str = '',
		user = Meteor.user();

		if(user){
			var nomineeVotesList = NomineeVotes.find({ nominee: this._id });
		} else {
			return null;
		}

		nomineeVotesList.forEach(function(nomineeVotes) {
			const votesTotal = nomineeVotes.votes;
			const user = Meteor.users.findOne({ _id: nomineeVotes.user });
			if (votesTotal !== 0) {
				str += '
' + user.profile.name + '-' + votesTotal +'
';
			}
		});

		return new Handlebars.SafeString(str);
	},

	voters : function(){
		return Users = Users.find({}, {sort : [['name', 'asc']]});
	},

});

//
// Handlebars Helpers
Handlebars.registerHelper('session',function(input){
	return Session.get(input);
});

Handlebars.registerHelper('votesCast',function(votesRemaining){

	var votesPerUser = Settings.findOne({name : 'votesPerUser'});

	return votesPerUser.value - votesRemaining;

});
<commit_msg>Change voter to picture and on hover title and vote count<commit_after>//
// Vote Template Helpers

Template.vote.helpers({

	isAdmin : function(){
		if(Meteor.user()){
			return Meteor.user().isAdmin;
		}
	},

	activeUsers : function(){
		if( Meteor.user() ){
			var returnArr = [];

			Meteor.users.find().forEach(function(user){
				var nameArr = user.profile.name.split(' ');
				returnArr.push( {name : nameArr[0] + ' ' + nameArr[1].substr(0, 1) } );
			});

			return returnArr;
		}
	},

	nominees : function(){
		return Nominees.find({}, {sort : [['name', 'asc']]});
	},

	results : function(){
		return Nominees.find({}, {sort : [['votes', 'desc']]});
	},

	title : function(){
		var setting = Settings.findOne({name : 'title'});

		if(setting){
			return setting.value;
		}	else {
		return 'Vote on...';
		}
	},

	votesPerUser : function(){
		var setting = Settings.findOne({name : 'votesPerUser'});

		if(setting){
			return setting.value;
		} else {
			return 5;
		}

	},

	allowDownVotes : function(){
		var setting = Settings.findOne({name : 'allowDownVotes'});

		if(setting){
			return setting.value;
		} else {
			return true;
		}

	},

	userVotes : function(){
		if(Meteor.user()){
			return Meteor.user().votes;
		}
	},

	canVote : function(){
		if(Session.get("meteor_loggedin")){
			return Meteor.user().votes > 0;
		} else {
			return false;
		}
	},

	canVoteUp : function(){
		if(Session.get("meteor_loggedin")){
			var user = Meteor.user(),
			nomineeVotes = NomineeVotes.findOne({nominee : this._id, user : user._id});

			if(user.votes > 0 ) return true;

			if(nomineeVotes && nomineeVotes.votes < 0){
				return true;
			} else {
				return false;
			}
		} else {
			return false
		}
	},

	canVoteDown : function(){
		if(Session.get("meteor_loggedin")){
			var user = Meteor.user(),
				nomineeVotes = NomineeVotes.findOne({nominee : this._id, user : user._id}),
				allowDownVotesSetting = Settings.findOne({name : 'allowDownVotes'});

			if(nomineeVotes.votes < 1 && !allowDownVotesSetting.value){
				return false;
			}

			if(user.votes > 0 ) return true;

			if(nomineeVotes && nomineeVotes.votes >=1){
				return true;
			} else {
				return false;
			}

		} else {
			return false;
		}
	},

	userVotesForNominee : function(){
		var str = '',
		user = Meteor.user();

		if(user){
			var nomineeVotesList = NomineeVotes.find({ nominee: this._id });
		} else {
			return null;
		}

		nomineeVotesList.forEach(function(nomineeVotes) {
			const votesTotal = nomineeVotes.votes;
			const user = Meteor.users.findOne({ _id: nomineeVotes.user });
			if (votesTotal !== 0) {
				str += '';
			}
		});

		return new Handlebars.SafeString(str);
	},

	voters : function(){
		return Users = Users.find({}, {sort : [['name', 'asc']]});
	},

});

//
// Handlebars Helpers
Handlebars.registerHelper('session',function(input){
	return Session.get(input);
});

Handlebars.registerHelper('votesCast',function(votesRemaining){

	var votesPerUser = Settings.findOne({name : 'votesPerUser'});

	return votesPerUser.value - votesRemaining;

});
<|endoftext|>