'use strict';

var assign = require('object-assign');
var debug = require('debug')('duosass');
var sass = require('node-sass').renderSync;

/**
 * Compile Sass to CSS
 *
 * @param {Object} [opts]
 * @api public
 * @return {Function}
 */

module.exports = function (opts) {
  opts = opts || {};

  return function (file) {
    if (file.type !== 'scss' && file.type !== 'sass') {
      return;
    }

    debug('compiling %s to css', file.id);

    var imports = file.src.match(/@import[^;]*;/gi) || [];
    var src = '';

    file.src = file.src.replace(/@import[^;]*;/gi, '');
    file.src = sass(assign(opts, {
      data: file.src,
      indentedSyntax: file.type === 'sass'
    }));

    imports.forEach(function (file) {
      src += file;
    });

    file.src = src + file.src;
    file.type = 'css';
  };
};

'use strict';

var assign = require('object-assign');
var debug = require('debug')('duosass');
var sass = require('node-sass').renderSync;

/**
 * Compile Sass to CSS
 *
 * @param {Object} [opts]
 * @api public
 * @return {Function}
 */

module.exports = function (opts) {
  opts = opts || {};

  return function (file) {
    if (file.type !== 'scss' && file.type !== 'sass') {
      return;
    }

    debug('compiling %s to css', file.id);

    var imports = file.src.match(/@import[^;]*;/gi) || [];
    var src = '';

    file.src = file.src.replace(/@import[^;]*;/gi, '');
    file.src = sass(assign({
      data: file.src,
      indentedSyntax: file.type === 'sass'
    }, opts));

    imports.forEach(function (file) {
      src += file;
    });

    file.src = src + file.src;
    file.type = 'css';
  };
};

Remove possibility to overwrite default options


"use strict";

/**
 * pretty json middleware.
 *
 *  - `always`: prettify response without query, if it's specified true. (default: false)
 *  - `query`: query-string parameter name for pretty response. (default: none)
 *  - `spaces`: pretty print spaces. (default: 2)
 *
 * @param {object} option
 * @return {function}
 */
module.exports = function(option) {
  option = option || {};
  var always = option.always || false;
  var query = option.query;
  var spaces = option.spaces || 2;

  return function(req, res, next) {
    if (always === true || typeof req.query[query] !== 'undefined') {
      res.json = function(body) {
        // content-type
        if (!res.get('Content-Type')) {
          res.set('Content-Type', 'application/json');
        }
        res.send(JSON.stringify(body, null, spaces));
      }
    }
    next();
  }
};

"use strict";

/**
 * pretty json middleware.
 *
 *  - `always`: prettify response without query, if it's specified true. (default: false)
 *  - `query`: query-string parameter name for pretty response. (default: none)
 *  - `spaces`: pretty print spaces. (default: 2)
 *
 * @param {object} option
 * @return {function}
 */
module.exports = function(option) {
  option = option || {};
  var always = option.always || false;
  var query = option.query;
  var spaces = option.spaces || 2;

  return function(req, res, next) {
    if (always === true || typeof req.query[query] !== 'undefined') {
      res.json = function(body) {
        // content-type
        if (!res.get('Content-Type')) {
          res.set('Content-Type', 'application/json');
        }
        return res.send(JSON.stringify(body, null, spaces));
      }
    }
    next();
  }
};

Add a return value to overwritten res.json() for chaining.


'use strict';

const fs = require("fs");

if (fs.existsSync('./build/Release/cppmap.node')) {
    module.exports = require('./build/Release/cppmap').WeakValueMap;
} else if (fs.existsSync('./build/Debug/cppmap.node')) {
    console.log("weak-value-map loaded debug build");
    module.exports = require('./build/Debug/cppmap').WeakValueMap;
} else {
    console.error("weak-value-map not built!");
    process.exit(1);
}

'use strict';

const fs = require('fs');
const path = require('path');

if (fs.existsSync(path.join(__dirname, 'build/Release/cppmap.node'))) {
    module.exports = require('./build/Release/cppmap').WeakValueMap;
} else if (fs.existsSync(path.join(__dirname, 'build/Debug/cppmap.node'))) {
    console.log("weak-value-map loaded debug build");
    module.exports = require('./build/Debug/cppmap').WeakValueMap;
} else {
    console.error("weak-value-map not built!");
    process.exit(1);
}

Fix bug introduced in a353681


module.exports = {
	domain_name: "kekeke.com",
	bind_port: 8000,
	work_dir: './work_dir',
	dst_dir: './dst_dir',
	fork_num: 8,
	idle_time: 5 * 60 * 1000,
	buffer_size: 64 * 1024,
	mail_data_max: 10 * 1024 * 1024,
	rcpt_max: 100
};

module.exports = {
	domain_name: "kekeke.com",
	bind_port: 8000,
	work_dir: './work_dir',
	dst_dir: './dst_dir',
	fork_num: (require('os').cpus().length / 2) + 1,
	idle_time: 5 * 60 * 1000,
	buffer_size: 64 * 1024,
	mail_data_max: 10 * 1024 * 1024,
	rcpt_max: 100
};

Change default fork num to cpu_num / 2 + 1.


// Copyright (c) 2018, Frappe Technologies and contributors
// For license information, please see license.txt

frappe.ui.form.on('Energy Point Rule', {
	refresh: function(frm) {
		frm.events.set_user_and_multiplier_field_options(frm);
	},
	reference_doctype(frm) {
		frm.events.set_user_and_multiplier_field_options(frm);
	},
	set_user_and_multiplier_field_options(frm) {
		const reference_doctype = frm.doc.reference_doctype;
		if (!reference_doctype) return;

		frappe.model.with_doctype(reference_doctype, () => {
			const map_for_options = df => ({ label: df.label, value: df.fieldname });
			const fields = frappe.meta.get_docfields(frm.doc.reference_doctype);
			const user_fields = fields.filter(df => (df.fieldtype === 'Link' && df.options === 'User')
				|| df.fieldtype === 'Data')
				.map(map_for_options)
				.concat([{label: __('Owner'), value: 'owner'}]);

			const multiplier_fields = fields.filter(df => ['Int', 'Float'].includes(df.fieldtype))
				.map(map_for_options);

			frm.set_df_property('user_field', 'options', user_fields);
			frm.set_df_property('multiplier_field', 'options', multiplier_fields);
		});
	}
});

// Copyright (c) 2018, Frappe Technologies and contributors
// For license information, please see license.txt

frappe.ui.form.on('Energy Point Rule', {
	refresh: function(frm) {
		frm.events.set_user_and_multiplier_field_options(frm);
	},
	reference_doctype(frm) {
		frm.events.set_user_and_multiplier_field_options(frm);
	},
	set_user_and_multiplier_field_options(frm) {
		const reference_doctype = frm.doc.reference_doctype;
		if (!reference_doctype) return;

		frappe.model.with_doctype(reference_doctype, () => {
			const map_for_options = df => ({ label: df.label, value: df.fieldname });
			const fields = frappe.meta.get_docfields(frm.doc.reference_doctype);
			const user_fields = fields.filter(df => (df.fieldtype === 'Link' && df.options === 'User')
				|| df.fieldtype === 'Data')
				.map(map_for_options)
				.concat([
					{ label: __('Owner'), value: 'owner' },
					{ label: __('Modified By'), value: 'modified_by' }
				]);

			const multiplier_fields = fields.filter(df => ['Int', 'Float'].includes(df.fieldtype))
				.map(map_for_options);

			frm.set_df_property('user_field', 'options', user_fields);
			frm.set_df_property('multiplier_field', 'options', multiplier_fields);
		});
	}
});

Append modified_field to the user_feilds of energy point rule


const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
const { set, get, assign } = require('lodash')

defineSupportCode(({ Given, When }) => {
  const Company = client.page.Company()

  Given(/^a company is created$/, async function () {
    await client
      .url(this.urls.companies.search)

    await Company
      .createUkNonPrivateOrNonPublicLimitedCompany({}, (company) => {
        set(this.state, 'company', company)
      })
      .wait() // wait for backend to sync
  })

  When(/^the Account management details are updated$/, async function () {
    await Company
      .updateAccountManagement((accountManagement) => {
        const company = get(this.state, 'company')
        set(this.state, 'company', assign({}, company, accountManagement))
      })
  })

  When(/^the Exports details are updated$/, async function () {
    await Company
      .updateExports((exports) => {
        const company = get(this.state, 'company')
        set(this.state, 'company', assign({}, company, exports))
      })
  })
})

const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
const { set, get, assign } = require('lodash')

defineSupportCode(({ When }) => {
  const Company = client.page.Company()

  When(/^the Account management details are updated$/, async function () {
    await Company
      .updateAccountManagement((accountManagement) => {
        const company = get(this.state, 'company')
        set(this.state, 'company', assign({}, company, accountManagement))
      })
  })

  When(/^the Exports details are updated$/, async function () {
    await Company
      .updateExports((exports) => {
        const company = get(this.state, 'company')
        set(this.state, 'company', assign({}, company, exports))
      })
  })
})

Remove redundant company create step


// Whether given error is an error thrown by require internals in case module
// (at given path) was not found

"use strict";

var pathToken = ":path", pattern;

try { require(pathToken); }
catch (e) { pattern = e.message; }

module.exports = function (error, path) {
	return error.message === pattern.replace(pathToken, path);
};

// Whether given error is an error thrown by require internals in case module
// (at given path) was not found

"use strict";

var pathToken = ":path", pattern;

var resolveMessage = function (error) {
	var newLineIndex = error.message.indexOf("\n");
	return newLineIndex > 0 ? error.message.slice(0, newLineIndex) : error.message;
};

try { require(pathToken); }
catch (e) { pattern = resolveMessage(e); }

module.exports = function (error, path) {
	return resolveMessage(error) === pattern.replace(pathToken, path);
};

Fix isModuleNotFound crash in Node.js v12


'use strict';
var Memcached = require('memcached'),
    replify = require('replify'),
    Promise = require('rsvp').Promise;

module.exports = function(connection) {

  var memcachedstore = new Memcached(connection);

  var API = {

    get: function(id){
      return new Promise(function(resolve, reject) {
        memcachedstore.get(id, function(err, val) {
          if (err || val === false) {
            reject(err);
          } else {
            resolve(val);
          }
        });
      });
    },

    set: function(id, val, lifetime) {
      lifetime = lifetime || 365 * 24 * 60 * 60 * 1000;
      return new Promise(function(resolve, reject) {
        memcachedstore.set(id, val, lifetime, function(err) {
          if (err) {
            reject(err);
          } else {
            resolve(val);
          }
        });
      });
    },

    items: memcachedstore.items.bind(memcachedstore),

  };

  replify('memcache', API);

  return API;

};

'use strict';
var Memcached = require('memcached'),
    replify = require('replify'),
    Promise = require('rsvp').Promise;

module.exports = function(connection) {

  var memcachedstore = new Memcached(connection);

  var API = {

    get: function(id){
      return new Promise(function(resolve, reject) {
        memcachedstore.get(id, function(err, val) {
          if (err || val === false) {
            reject(err);
          } else {
            resolve(val);
          }
        });
      });
    },

    set: function(id, val, lifetime) {
      lifetime = lifetime || 7 * 24 * 60 * 60 * 1000;
      return new Promise(function(resolve, reject) {
        memcachedstore.set(id, val, lifetime, function(err) {
          if (err) {
            reject(err);
          } else {
            resolve(val);
          }
        });
      });
    },

    items: memcachedstore.items.bind(memcachedstore),

  };

  replify('memcache', API);

  return API;

};

Change lifetime to 1 week


var path = require('path');
var fs = require('fs');
var isUrl = require('is-url');

var notFound = function (settings, store) {
  return function (req, res, next) {
    res.statusCode = 404;
    res.send(getErrorPage(req.config, settings), true);
  };

  function getErrorPage (config, settings) {
    return (pathExists(config, settings))
      ? pathWithRoot(config, settings)
      : path.resolve(__dirname, '../templates/not_found.html');
  }

  function pathExists (config, settings) {
    if (!config || !config.error_page) return false;
    if (isUrl(config.error_page)) return true;

    // NOTE: If this becomes a bottleneck, convert
    // to async version of fs.exists()
    return settings.isFile(config.error_page);
  }

  function pathWithRoot (config, settings) {
    if (isUrl(config.error_page)) return config.error_page;
    // return settings.rootPathname(config.error_page);
    console.log('path with root', store.getPath(config.error_page));
    return store.getPath(config.error_page);
  }
};

module.exports = notFound;

var path = require('path');
var fs = require('fs');
var isUrl = require('is-url');

var notFound = function (settings, store) {
  return function (req, res, next) {
    res.statusCode = 404;
    res.send(getErrorPage(req.config, settings), true);
  };

  function getErrorPage (config, settings) {
    return (pathExists(config, settings))
      ? pathWithRoot(config, settings)
      : path.resolve(__dirname, '../templates/not_found.html');
  }

  function pathExists (config, settings) {
    if (!config || !config.error_page) return false;
    if (isUrl(config.error_page)) return true;

    // NOTE: If this becomes a bottleneck, convert
    // to async version of fs.exists()
    return settings.isFile(config.error_page);
  }

  function pathWithRoot (config, settings) {
    if (isUrl(config.error_page)) return config.error_page;
    // return settings.rootPathname(config.error_page);
    console.log('path with root', store.getPath(path.join('/', req.config.cwd, config.error_page)));
    return store.getPath(path.join('/', req.config.cwd, config.error_page));
  }
};

module.exports = notFound;

Correct remote path for error page


var express = require('express');
var cardsets = require('./libs/cardsets');
var path = require('path');

var app = express();
var httpServer = app.listen(process.env.PORT || 8080);

app.use('/sets', cardsets);
app.use(express.static(__dirname + '/public'));

var express = require('express');
var cardsets = require('./libs/cardsets');
var path = require('path');

var app = express();
var httpServer = app.listen(process.env.PORT || 8080);

app.use('/sets', cardsets);
app.use(express.static(path.join(__dirname, '/public')));

Change handling of a path


AT.prototype.atOauthHelpers = {
    oauthService: function() {
        return AccountsTemplates.oauthServices();
    },
};

Convert indentation to 2 spaces


let del = require('del');

del(['public/**']).then(function () {
    console.log('/public dir is deleted');
});

var del = require('del');

del(['public/**']).then(function () {
    console.log('/public dir is deleted');
});

Make it run on Node 4


"use strict";
// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE
angular.module('publisherApp')

.constant('ENV', 'dev')

.constant('VERSION', '1.1.1-SNAPSHOT')

;

"use strict";
// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE
angular.module('publisherApp')

.constant('ENV', 'dev')

.constant('VERSION', '1.1.3-SNAPSHOT')

;

Update ngconstant for app version


/*!
 * TemplateLayout Wef plugin
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */

//requires: cssParser
var parser = wef.fn.cssParser; //TODO: loader
//exports: templateLayout

(function () {
    var templateLayout = {
        name:"templateLayout",
        version:"0.0.1",
        description:"W3C CSS Template Layout Module",
        authors:["Pablo Escalada <uo1398@uniovi.es>"],
        licenses:["MIT"], //TODO: Licenses

        init:function () {
            document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
                // e.target matches the elem from above
                lastEvent = e;
                //TODO populate TemplateDOM
            }, false);
            return templateLayout;
        },

        getLastEvent:function () {
            return lastEvent;
        }
    };

    var lastEvent = null;

    wef.plugins.register("templateLayout", templateLayout);
})();

/*!
 * TemplateLayout Wef plugin
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */

//requires: cssParser
var parser = wef.fn.cssParser; //TODO: loader
//exports: templateLayout

(function () {
    var templateLayout = {
        name:"templateLayout",
        version:"0.0.1",
        description:"W3C CSS Template Layout Module",
        authors:["Pablo Escalada <uo1398@uniovi.es>"],
        licenses:["MIT"], //TODO: Licenses

        init:function () {
            document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
                //console.log(e.data.selectorText, e.data.declaration);
                lastEvent = e;
                //TODO populate TemplateDOM

            }, false);
            return templateLayout;
        },

        getLastEvent:function () {
            return lastEvent;
        }
    };

    var lastEvent = null;

    wef.plugins.register("templateLayout", templateLayout);
})();

Move StyleDeclaration outside main function


/** @babel */

import {spawnSync} from 'child_process'

const ENVIRONMENT_VARIABLES_TO_PRESERVE = new Set(['NODE_ENV', 'NODE_PATH'])

export default function updateProcessEnv (launchEnv) {
  let envToAssign
  if (launchEnv.PWD) {
    envToAssign = launchEnv
  } else {
    if (process.platform === 'darwin') {
      envToAssign = getEnvFromShell()
    }
  }

  if (envToAssign) {
    for (let key in process.env) {
      if (!ENVIRONMENT_VARIABLES_TO_PRESERVE.has(key)) {
        delete process.env[key]
      }
    }

    for (let key in envToAssign) {
      if (!ENVIRONMENT_VARIABLES_TO_PRESERVE.has(key)) {
        process.env[key] = envToAssign[key]
      }
    }
  }
}

function getEnvFromShell () {
  let shell = process.env.SHELL
  if (shell && (shell.endsWith('/bash') || shell.endsWith('/sh'))) {
    let {stdout} = spawnSync(shell, ['-ilc', 'env'], {encoding: 'utf8'})
    if (stdout) {
      let result = {}
      for (let line of stdout.split('\n')) {
        if (line.includes('=')) {
          let components = line.split('=')
          let key = components.shift()
          let value = components.join('=')
          result[key] = value
        }
      }
      return result
    }
  }
}

/** @babel */

import {spawnSync} from 'child_process'

const ENVIRONMENT_VARIABLES_TO_PRESERVE = new Set(['NODE_ENV', 'NODE_PATH'])

export default function updateProcessEnv (launchEnv) {
  let envToAssign
  if (launchEnv && launchEnv.PWD) {
    envToAssign = launchEnv
  } else {
    if (process.platform === 'darwin') {
      envToAssign = getEnvFromShell()
    }
  }

  if (envToAssign) {
    for (let key in process.env) {
      if (!ENVIRONMENT_VARIABLES_TO_PRESERVE.has(key)) {
        delete process.env[key]
      }
    }

    for (let key in envToAssign) {
      if (!ENVIRONMENT_VARIABLES_TO_PRESERVE.has(key)) {
        process.env[key] = envToAssign[key]
      }
    }
  }
}

function getEnvFromShell () {
  let shell = process.env.SHELL
  if (shell && (shell.endsWith('/bash') || shell.endsWith('/sh'))) {
    let {stdout} = spawnSync(shell, ['-ilc', 'env'], {encoding: 'utf8'})
    if (stdout) {
      let result = {}
      for (let line of stdout.split('\n')) {
        if (line.includes('=')) {
          let components = line.split('=')
          let key = components.shift()
          let value = components.join('=')
          result[key] = value
        }
      }
      return result
    }
  }
}

Handle null env load setting


const path = require('path');
const webpack = require('webpack');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

module.exports = {
    context: path.resolve(__dirname, './src'),
    entry: {
        'babylonjs-materials': path.resolve(__dirname, './src/legacy/legacy.ts'),
    },
    output: {
        path: path.resolve(__dirname, '../dist/preview release/materialsLibrary'),
        filename: 'babylonjs.materials.min.js',
        libraryTarget: 'umd',
        library: {
            root: ["MATERIALS"],
            amd: "babylonjs-materials",
            commonjs: "babylonjs-materials"
        },
        umdNamedDefine: true
    },
    resolve: {
        extensions: ['.ts']
    },
    externals: [
        {
            babylonjs: {
                root: "BABYLON",
                commonjs: "babylonjs",
                commonjs2: "babylonjs",
                amd: "babylonjs"
            }
        },
        /^babylonjs.*$/i,
    ],
    devtool: "souce-map",
    module: {
        rules: [{
            test: /\.tsx?$/,
            exclude: /node_modules/,
            use: [
            {
                loader: 'awesome-typescript-loader',
                options: {
                    configFileName: path.resolve(__dirname, './tsconfig.json'),
                    declaration: false
                }
            }]
        }]
    },
    mode: "production",
    plugins: [
        new HardSourceWebpackPlugin(),
        new webpack.WatchIgnorePlugin([
            /\.js$/,
            /\.d\.ts$/,
            /\.fx$/
        ])
    ],
}

const path = require('path');
const webpack = require('webpack');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

module.exports = {
    context: path.resolve(__dirname, './src'),
    entry: {
        'babylonjs-materials': path.resolve(__dirname, './src/legacy/legacy-grid.ts'),
    },
    output: {
        path: path.resolve(__dirname, '../dist/preview release/materialsLibrary'),
        filename: 'babylonjs.materials.min.js',
        libraryTarget: 'umd',
        library: {
            root: ["MATERIALS"],
            amd: "babylonjs-materials",
            commonjs: "babylonjs-materials"
        },
        umdNamedDefine: true
    },
    resolve: {
        extensions: ['.ts']
    },
    externals: [
        function(_, request, callback) {
            if (/^babylonjs.*$/i.test(request)) {
                callback(null, {
                    root: "BABYLON",
                    commonjs: "babylonjs",
                    commonjs2: "babylonjs",
                    amd: "babylonjs"
                });
            }
            else {
                callback();
            }
        },
    ],
    devtool: "souce-map",
    module: {
        rules: [{
            test: /\.tsx?$/,
            exclude: /node_modules/,
            use: [
            {
                loader: 'awesome-typescript-loader',
                options: {
                    configFileName: path.resolve(__dirname, './tsconfig.json'),
                    declaration: false
                }
            }]
        }]
    },
    mode: "production",
    plugins: [
        new HardSourceWebpackPlugin(),
        new webpack.WatchIgnorePlugin([
            /\.js$/,
            /\.d\.ts$/,
            /\.fx$/
        ])
    ],
}

Build mat lib relative path


/*!
 * jQuery UI Effects Transfer @VERSION
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Transfer Effect
//>>group: Effects
//>>description: Displays a transfer effect from one element to another.
//>>docs: http://api.jqueryui.com/transfer-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}( function( $ ) {

if ( $.uiBackCompat !== false ) {
	return $.effects.define( "transfer", function( options, done ) {
		$( this ).transfer( options, done );
	} );
}

} ) );

/*!
 * jQuery UI Effects Transfer @VERSION
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Transfer Effect
//>>group: Effects
//>>description: Displays a transfer effect from one element to another.
//>>docs: http://api.jqueryui.com/transfer-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}( function( $ ) {

var effect;
if ( $.uiBackCompat !== false ) {
	effect = $.effects.define( "transfer", function( options, done ) {
		$( this ).transfer( options, done );
	} );
}
return effect;

} ) );

Refactor transfer back compat to avoid bad nested return


import Trie from 'triejs';
import { forEach, addIndex, toLower } from 'ramda';

const forEachIndex = addIndex(forEach);

/**
 * Remove trailing newlines
 */
export const normalize = (rawText) =>
  rawText.replace(/(.)(\r\n|\n|\r)/gm, '$1');

/**
 * Keep words and punctuation separate
 */
export const tokenizer = (rawText) =>
  normalize(rawText).match(
    /([A-Za-zА-Яа-я0-9_\$%#@]+|[,\?\.'";&\(\)!\-\+=\n\r])/g);

export const buildTrie = (tokenizedText) => {
  const auto = new Trie();
  forEachIndex((token, i) =>
               auto.add(toLower(token), { i, token }), tokenizedText);
  return auto;
};

import Trie from 'triejs';
import { forEach, addIndex, toLower } from 'ramda';

const forEachIndex = addIndex(forEach);

/**
 * Remove trailing newlines
 */
export const normalize = (rawText) =>
  rawText.replace(/(.)(\r\n|\n|\r)/gm, '$1 ');

/**
 * Keep words and punctuation separate
 */
export const tokenizer = (rawText) =>
  normalize(rawText).match(
    /([A-Za-zА-Яа-я0-9_\$%#@]+|[,\?\.'";&\(\)!\-\+=\n\r])/g);

export const buildTrie = (tokenizedText) => {
  const auto = new Trie();
  forEachIndex((token, i) =>
               auto.add(toLower(token), { i, token }), tokenizedText);
  return auto;
};

Replace trailing newlines with spaces


var Namespace = (function (global) {

  'use strict';

  return {

    /**
     * Creates a global object in a single line.
     * // example
     * Namespace.create('foo.bar'); // -> foo.bar
     *
     * @param {string} namespace
     */
    create: function (namespace) {
      var parent = global,
        parts = namespace.split('.'),
        len = parts.length,
        part,
        i
      ;

      for (i = 0; i < len; i++) {
        part = parts[i];
        parent = (parent[part] = parent[part] || {});
      }
    },

    /**
     * Check for global object.
     * // example
     * Namespace.is('foo.bar'); // -> false
     * Namespace.create('foo.bar'); // -> foo.bar
     * Namespace.is('foo.bar'); // -> true
     *
     * @param {string} namespace
     */
    is: function (namespace) {
      var parent = global,
        result = false,
        parts = namespace.split('.'),
        len = parts.length,
        part,
        i
      ;
      for (i = 0; i < len; i++) {
        part = parts[i];

        if (!parent[part]) {
          result = false;
          return false;
        }
        parent = parent[part];
        result = true;
      }

      return result;
    }

  };

}());

var Namespace = (function (global) {

  'use strict';

  return {

    /**
     * Creates a global object in a single line.
     * // example
     * Namespace.create('foo.bar'); // -> foo.bar
     *
     * @param {string} namespace
     */
    create: function (namespace) {
      var parent = global,
        parts = namespace.split('.'),
        len = parts.length,
        part,
        i
      ;

      for (i = 0; i < len; i++) {
        part = parts[i];
        parent = (parent[part] = parent[part] || {});
      }
    },

    /**
     * Check for global object.
     * // example
     * Namespace.is('foo.bar'); // -> false
     * Namespace.create('foo.bar'); // -> foo.bar
     * Namespace.is('foo.bar'); // -> true
     *
     * @param {string} namespace
     */
    is: function (namespace) {
      var parent = global,
        result = false,
        parts = namespace.split('.'),
        len = parts.length,
        part,
        i
      ;
      for (i = 0; i < len; i++) {
        part = parts[i];

        if (!parent[part]) {
          result = false;
          return false;
        }
        parent = parent[part];
        result = true;
      }

      return result;
    }

  };

}(this));

Add missing global object to fix broken reference assignment


/**
 * Composes single-argument functions from right to left.
 *
 * @param {...Function} funcs The functions to compose.
 * @returns {Function} A function obtained by composing functions from right to
 * left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))).
 */
export default function compose(...funcs) {
  return (...args) => {
    if (funcs.length === 0) {
      // We weren't given any functions, just return the first passed in arg.
      return args[0]
    }

    const last = funcs[funcs.length - 1]
    const rest = funcs.slice(0, -1)

    return rest.reduceRight((composed, f) => f(composed), last(...args))
  }
}

/**
 * Composes single-argument functions from right to left.
 *
 * @param {...Function} funcs The functions to compose.
 * @returns {Function} A function obtained by composing functions from right to
 * left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))).
 */
export default function compose(...funcs) {
  return (...args) => {
    if (funcs.length === 0) {
      return args[0]
    }

    const last = funcs[funcs.length - 1]
    const rest = funcs.slice(0, -1)

    return rest.reduceRight((composed, f) => f(composed), last(...args))
  }
}

Remove the comment duplicating the code


import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';

import App from './components/App';
import FriendListApp from './containers/FriendListApp/FriendListApp';
import MonsterFinderApp from './containers/MonsterFinderApp';
import MoveFinderApp from './containers/MoveFinderApp';
import MonsterMakerApp from './containers/MonsterMakerApp';
import NotFoundView from './views/NotFoundView';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={MonsterMakerApp} />
    <Route path="move-finder" component={MoveFinderApp} />
    <Route path="monster-maker" component={MonsterMakerApp} />
    <Route path="monster-finder" component={MonsterFinderApp} />
    <Route path="404" component={NotFoundView} />
    <Redirect from="*" to="404" />
  </Route>
);

import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';

import App from './components/App';
import FriendListApp from './containers/FriendListApp/FriendListApp';
import MonsterFinderApp from './containers/MonsterFinderApp';
import MoveFinderApp from './containers/MoveFinderApp';
import MonsterMakerApp from './containers/MonsterMakerApp';
import NotFoundView from './views/NotFoundView';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={MonsterFinderApp} />
    <Route path="move-finder" component={MoveFinderApp} />
    <Route path="monster-maker" component={MonsterMakerApp} />
    <Route path="monster-finder" component={MonsterFinderApp} />
    <Route path="404" component={NotFoundView} />
    <Redirect from="*" to="404" />
  </Route>
);

Change root component to MonsterFinder


/**
 * Copyright (c) Ajay Sreedhar. All rights reserved.
 *
 * Licensed under the MIT License.
 * Please see LICENSE file located in the project root for more information.
 */

/**
 * @typedef {Object} App_ServiceModel - The service model object
 *
 * @property {string} [name] - The Service name.
 * @property {number} [retries] - The number of retries to execute upon failure to proxy. Default: 5.
 * @property {string} protocol - The protocol used to communicate with the upstream.
 * @property {string} host - The host of the upstream server. Note that the host value is case-sensitive.
 * @property {number} port - The upstream server port.
 * @property {string} [path] - Optional: The path to be used in requests to the upstream server.
 * @property {string} [client_certificate] - Certificate to be used as client certificate while TLS handshaking to the upstream server.
 */

'use strict';

/**
 *
 * @type App_ServiceModel
 */
const ServiceModel = {
    name: '',
    retries: 5,
    protocol: 'http',
    host: '',
    port: 80,
    path: '/',
    connect_timeout: 60000,
    write_timeout: 60000,
    read_timeout: 60000,
    tags: [],
    client_certificate: '',
    tls_verify: 'default',
    tls_verify_depth: -1,
    ca_certificates: [],
    enabled: true
};

export default ServiceModel;

/**
 * Copyright (c) Ajay Sreedhar. All rights reserved.
 *
 * Licensed under the MIT License.
 * Please see LICENSE file located in the project root for more information.
 */

'use strict';

/**
 * @typedef {Object} App_ServiceModel - The service model object
 *
 * @property {string} [name] - The Service name.
 * @property {number} [retries] - The number of retries to execute upon failure to proxy. Default: 5.
 * @property {string} protocol - The protocol used to communicate with the upstream.
 * @property {string} host - The host of the upstream server. Note that the host value is case-sensitive.
 * @property {number} port - The upstream server port.
 * @property {string} [path] - Optional: The path to be used in requests to the upstream server.
 * @property {string} [client_certificate] - Certificate to be used as client certificate while TLS handshaking to the upstream server.
 * @property {string[]} [tags] - An optional set of strings associated with the Service for grouping and filtering.
 */

/**
 * Defines the service object.
 *
 * @type App_ServiceModel
 */
const ServiceModel = {
    name: '',
    retries: 5,
    protocol: 'http',
    host: '',
    port: 80,
    path: '/',
    connect_timeout: 60000,
    write_timeout: 60000,
    read_timeout: 60000,
    tags: [],
    client_certificate: '',
    tls_verify: 'default',
    tls_verify_depth: -1,
    ca_certificates: [],
    enabled: true
};

export default ServiceModel;

Set tls_verify as null string


(function (exports) {
    'use strict';

    function BrowserMusicPlayer () {
        var AudioContext = window.AudioContext || window.webkitAudioContext;
        this.ctx = new AudioContext();
    }

    BrowserMusicPlayer.prototype.loadingMusic = function () {
    };

    /**
     * 指定されたファイルが音楽ファイルかどうか調べ、その結果を真偽値で返します
     * @param file
     * @returns {boolean}
     */
    BrowserMusicPlayer.prototype.isMusicFile = function (file) {
        var type = file.type.substring(6, 9);
        return /(mp3|wav|ogg|wma|m4a)/.test(type);
    };

    BrowserMusicPlayer.prototype.play = function () {
    };

    BrowserMusicPlayer.prototype.stop = function () {
    };

    BrowserMusicPlayer.prototype.rewind = function () {
    };

    BrowserMusicPlayer.prototype.forward = function () {
    };

    exports.BrowserMusicPlayer = BrowserMusicPlayer;
})(window);

(function (exports) {
    'use strict';

    function BrowserMusicPlayer () {
        var AudioContext = window.AudioContext || window.webkitAudioContext;
        this.ctx = new AudioContext();
    }

    /**
     * ファイルをFileReader.readAsDataURL()を使って読み込み、FileReaderオブジェクトを返します
     * @param file {File}
     * @returns {FileReader}
     */
    BrowserMusicPlayer.prototype.loadingMusic = function (file) {
        if (!this.isMusicFile(file)) {
            throw new Error('Not a music file');
        }

        var reader = new FileReader();
        reader.readAsDataURL(file);
        return reader;
    };

    /**
     * 指定されたファイルが音楽ファイルかどうか調べ、その結果を真偽値で返します
     * @param file {File}
     * @returns {boolean}
     */
    BrowserMusicPlayer.prototype.isMusicFile = function (file) {
        var type = file.type.substring(6, 9);
        return /(mp3|wav|ogg|wma|m4a)/.test(type);
    };

    BrowserMusicPlayer.prototype.play = function () {
    };

    BrowserMusicPlayer.prototype.stop = function () {
    };

    BrowserMusicPlayer.prototype.rewind = function () {
    };

    BrowserMusicPlayer.prototype.forward = function () {
    };

    exports.BrowserMusicPlayer = BrowserMusicPlayer;
})(window);

Add a method: File object specified argument, returns FileReader object


export const BASE = 'https://online.ntnu.no/';
export const API_BASE = `${BASE}api/v1/`;
export const API_AUTH = 'auth/';
export const API_USERS = 'usersaldo/';
export const API_INVENTORY = 'inventory/';
export const API_RFID = 'rfid/';
export const API_ORDER = 'orderline/';
export const API_TRANSACTIONS = 'transactions/';

export const CLIENT_SECRET = '';
export const CLIENT_ID = '';

export const MOCK = true;
export const LOGOUT_TIMER = 120;

export const saldoList = [50, 100, 200, 500];

Remove unnecessary variable (saldoList) from constants.js


import React from 'react';
import { map } from 'lodash';

const MetaInformation = (props) => (

    {props.title ?
{props.title}
 : null}
    {
      map(props.details, (item, key) => {
        return {key}: {item}

      })
    }

);

export default MetaInformation;

import React from 'react';
import { map } from 'lodash';
import PropTypes from 'prop-types';

const MetaInformation = props => (

    {props.title ?
{props.title}
 : null}
    {
      map(props.details, (item, key) => {key}: {item}
)
    }

);

MetaInformation.propTypes = {
  title: PropTypes.string,
  details: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};

MetaInformation.defaultProps = {
  title: null,
};

export default MetaInformation;

Add proptype validation to MetaInformation component


var express = require('express');

// Create our app
var   app   = express();
const PORT  = process.env.PORT || 3100;

app.use(function (req, resp, next) {
  if(req.headers['x-forwarded-proto'] === 'http') {
    next;
  }
  else {
    resp.redirect('http://' + req.hostname + req.url)
  }
});

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

app.listen(PORT, function () {
    console.log("Express loaded at port " + PORT);
})

var express = require('express');

// Create our app
var   app   = express();
const PORT  = process.env.PORT || 3100;

app.use(function (req, resp, next) {
  if(req.headers['x-forwarded-proto'] === 'https') {
    resp.redirect('http://' + req.hostname + req.url)
  }
  else {
    next();
  }
});

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

app.listen(PORT, function () {
    console.log("Express loaded at port " + PORT);
})

Fix Heroku re-direct for localhost


// Only create a server if we are in an environment with a HTTP server
// (as opposed to, eg, a command-line tool).
//
if (Package.webapp) {
  if (process.env.DDP_DEFAULT_CONNECTION_URL) {
    __meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL =
      process.env.DDP_DEFAULT_CONNECTION_URL;
  }

  Meteor.server = new Server;

  Meteor.refresh = function (notification) {
    DDPServer._InvalidationCrossbar.fire(notification);
  };

  // Proxy the public methods of Meteor.server so they can
  // be called directly on Meteor.
  _.each(['publish', 'methods', 'call', 'apply', 'onConnection'],
         function (name) {
           Meteor[name] = _.bind(Meteor.server[name], Meteor.server);
         });
} else {
  // No server? Make these empty/no-ops.
  Meteor.server = null;
  Meteor.refresh = function (notification) {
  };
}

// Meteor.server used to be called Meteor.default_server. Provide
// backcompat as a courtesy even though it was never documented.
// XXX COMPAT WITH 0.6.4
Meteor.default_server = Meteor.server;

// Only create a server if we are in an environment with a HTTP server
// (as opposed to, eg, a command-line tool).
//
if (Package.webapp) {
  if (process.env.DDP_DEFAULT_CONNECTION_URL) {
    __meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL =
      process.env.DDP_DEFAULT_CONNECTION_URL;
  }

  Meteor.server = new Server;

  Meteor.refresh = function (notification) {
    DDPServer._InvalidationCrossbar.fire(notification);
  };

  // Proxy the public methods of Meteor.server so they can
  // be called directly on Meteor.
  _.each(['publish', 'methods', 'call', 'apply', 'onConnection'],
         function (name) {
           Meteor[name] = _.bind(Meteor.server[name], Meteor.server);
         });
} else {
  // No server? Make these empty/no-ops.
  Meteor.server = null;
  Meteor.refresh = function (notification) {
  };

  // Make these empty/no-ops too, so that non-webapp apps can still
  // depend on/use packages that use those functions.
  _.each(['publish', 'methods', 'onConnection'],
      function (name) {
        Meteor[name] = function () { };
      });
}

// Meteor.server used to be called Meteor.default_server. Provide
// backcompat as a courtesy even though it was never documented.
// XXX COMPAT WITH 0.6.4
Meteor.default_server = Meteor.server;

Add no-ops for Meteor.publish, methods, and onConnection if no webapp


const TEST_TYPE = ((argv) => {
    let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/);

    return match && match[1] || '';
})(process.argv);

function configOverrides(testType) {
    switch (testType) {
        case 'unit':
            return {
                statements: 60,
                branches: 40,
                functions: 40,
                lines: 60
            };
        default:
            return {}
    }
}

module.exports = {
    // @todo cover `all` files by writing unit test for bundled lib/sandbox files
    // all: true,
    'check-coverage': true,
    'report-dir': '.coverage',
    'temp-dir': '.nyc_output',
    include: ['lib/**/*.js'],
    reporter: ['lcov', 'json', 'text', 'text-summary'],
    ...configOverrides(TEST_TYPE),
};

const TEST_TYPE = ((argv) => {
    let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/);

    return match && match[1] || '';
})(process.argv);

function configOverrides(testType) {
    switch (testType) {
        case 'unit':
            return {
                statements: 55,
                branches: 40,
                functions: 40,
                lines: 60
            };
        default:
            return {}
    }
}

module.exports = {
    // @todo cover `all` files by writing unit test for bundled lib/sandbox files
    // all: true,
    'check-coverage': true,
    'report-dir': '.coverage',
    'temp-dir': '.nyc_output',
    include: ['lib/**/*.js'],
    reporter: ['lcov', 'json', 'text', 'text-summary'],
    ...configOverrides(TEST_TYPE),
};

Reduce test coverage target for statements


import { EditAnnotationCommand } from 'substance'
import SpellError from './SpellError'
import CorrectionTool from './CorrectionTool'
import SpellCheckCommand from './SpellCheckCommand'

export default {
  name: 'spell-check',
  configure: function(config) {
    config.addNode(SpellError)
    config.addCommand('correction', SpellCheckCommand)
    config.addTool('correction', CorrectionTool, {target: 'context-menu'})
  }
}

import { EditAnnotationCommand } from 'substance'
import SpellError from './SpellError'
import CorrectionTool from './CorrectionTool'
import SpellCheckCommand from './SpellCheckCommand'

export default {
  name: 'spell-check',
  configure: function(config) {
    config.addToolGroup('context-menu-spell-check')
    config.addNode(SpellError)
    config.addCommand('correction', SpellCheckCommand)
    config.addTool('correction', CorrectionTool, {toolGroup: 'context-menu-spell-check'})
  }
}

Put correction tool into context-menu-spell-check.


module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({
        // Create the webfont files:
        webfont: {
                icons: {
                        src: '../icons/actions/22@2x/*.svg',
                        dest: './dist',
                        options: {
                            stylesheet: 'scss',
                            types:  'eot,woff2,ttf,svg',
                            optimize: false
                        }
                }
        }
    });
    grunt.loadNpmTasks('grunt-webfont');

    // Run the default task by executing "grunt" in the CLI:
    grunt.registerTask('default', ['webfont']);
};

module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({
        // Create the webfont files:
        webfont: {
                icons: {
                        src: '../icons/actions/22@2x/*.svg',
                        dest: './dist',
                        options: {
                            stylesheet: 'css',
                            types:  'eot,woff2,ttf,svg',
                            optimize: false
                        }
                }
        }
    });
    grunt.loadNpmTasks('grunt-webfont');

    // Run the default task by executing "grunt" in the CLI:
    grunt.registerTask('default', ['webfont']);
};

Use css instead of scss as output format


'use strict';

const { exec } = require('child_process');

const get = () => {
    return new Promise((resolve, reject) => {
        exec('git symbolic-ref --short HEAD', (err, stdout, stderr) => {
            if (err) {
                err.stderr = stderr;
                reject(err);
                return;
            }
            resolve(stdout.trimRight());
        });
    });
};

// Get the current branch name, unless one is not available, in which case
// return the provided branch as a fallback.
const assume = (assumedName) => {
    return get().catch((err) => {
        const problem = err.stderr.substring('fatal; '.length);

        const noBranchErrors = [
            'Not a git repository',
            'ref HEAD is not a symbolic ref'
        ];

        const matchProblem = (scenario) => {
            return problem.startsWith(scenario);
        };

        if (noBranchErrors.some(matchProblem)) {
            return assumedName;
        }

        throw err;
    });
};

// Master is a nice fallback assumption because it is
// the default branch name in git.
const assumeMaster = () => {
    return assume('master');
};

module.exports = {
    get,
    assume,
    assumeMaster
};

'use strict';

const { exec } = require('child_process');

const branchName = (option) => {
    const config = Object.assign({}, option);
    return new Promise((resolve, reject) => {
        exec('git symbolic-ref --short HEAD', { cwd : config.cwd }, (err, stdout, stderr) => {
            if (err) {
                err.stderr = stderr;
                reject(err);
                return;
            }
            resolve(stdout.trimRight());
        });
    });
};

// Get the current branch name, unless one is not available, in which case
// return the provided branch as a fallback.
branchName.assume = (assumedName, option) => {
    return branchName(option).catch((err) => {
        const problem = err.stderr.substring('fatal; '.length);

        const noBranchErrors = [
            'Not a git repository',
            'ref HEAD is not a symbolic ref'
        ];

        const matchProblem = (scenario) => {
            return problem.startsWith(scenario);
        };

        if (noBranchErrors.some(matchProblem)) {
            return assumedName;
        }

        throw err;
    });
};

// Master is a nice fallback assumption because it is
// the default branch name in git.
branchName.assumeMaster = (option) => {
    return branchName.assume('master', option);
};

module.exports = branchName;

Allow the user to set the working directory.


var path = require('path');
var fs   = require('fs');

var mimetypes = {
  '.gif':  'image/gif',
  '.jpeg': 'image/jpeg',
  '.jpg':  'image/jpeg',
  '.jpe':  'image/jpeg',
  '.png':  'image/png',
  '.bmp':  'image/bmp'
};

var encode = function( filePath ) {
  return new Buffer(fs.readFileSync(filePath)).toString('base64');
};

module.exports = function( inputText, inputName ) {
  var transformedText = inputText,
      regex = /url\((?:\\?['"])?(.*?)([\w-_]+\.\w{3,4})\\?['"]?\)/g,
      found = inputText.match(regex);

  if (found) {
    transformedText = inputText.replace(regex, function( match, cg1, cg2 ) {
      // cg1 = capture group $1 (path)
      // cg2 = capture group $2 (filename)
      var filePath = path.dirname(inputName) + '/' + (cg1 ? cg1 : '') + cg2,
          prefix = 'data:' + mimetypes[path.extname(cg2)] + ';base64,';

      return 'url(' + prefix + encode(filePath) + ')';
    });
  }
  return transformedText;
};

var path = require('path');
var fs   = require('fs');

var mimetypes = {
  '.gif':  'image/gif',
  '.jpeg': 'image/jpeg',
  '.jpg':  'image/jpeg',
  '.jpe':  'image/jpeg',
  '.png':  'image/png'
};

var encode = function( filePath ) {
  return new Buffer(fs.readFileSync(filePath)).toString('base64');
};

module.exports = function( inputText, inputName, outputName ) {
  if (!inputText || !inputName) {
    return inputText;
  }

  var transformedText = inputText,
      regex = /url\((?:\\?['"])?([\w\/\\._-]*?)([\w-_]+\.\w{3,4})\\?['"]?\)/g,
      // capture group $1 (path)
      // capture group $2 (filename)
      found = inputText.match(regex);

  if (found) {
    transformedText = inputText.replace(regex, function( match, filePath, fileName ) {
      var fullPath = path.resolve('test/assets/' + filePath + fileName),
          prefix = 'data:' + mimetypes[path.extname(fileName.toLowerCase())] + ';base64,',
          falseFind = match.charAt === '#';
      var encodedFile = encode(fullPath);
      return falseFind ? match : 'url(' + prefix + encodedFile + ')';
    });
  }
  return transformedText;
};

Update regex and path resolution for test image files.


var basicAuth = require('basic-auth');

var unauthorized = function(res, realm) {
  var realm = realm || 'Authorization Required';
  res.set('WWW-Authenticate', 'Basic realm=' + realm);

  return res.sendStatus(401);
};

module.exports = function(username, password, realm) {
  return function(req, res, next) {
    var user = basicAuth(req);
    if (!user) {
      return unauthorized(res, realm);
    }

    var authorized = null;
    if (typeof username === 'function') {
      var checkFn = username;
      authorized = checkFn(user.name, user.pass, function(authentified) {
        if (authentified) {
          return next();
        }

        return unauthorized(res, realm);
      });
    } else {
      authorized = !(!user || user.name !== username || user.pass !== password);
    }

    if (authorized === false) {
      return unauthorized(res, realm);
    }

    if (authorized === true) {
      return next();
    }
  };
};

var basicAuth = require('basic-auth');

function unauthorized(res, realm) {
  var realm = realm || 'Authorization Required';
  res.set('WWW-Authenticate', 'Basic realm=' + realm);

  return res.sendStatus(401);
};

function isPromiseLike(obj) {
  return obj && typeof obj.then === 'function';
}

module.exports = function(username, password, realm) {
  return function(req, res, next) {
    var user = basicAuth(req);
    if (!user) {
      return unauthorized(res, realm);
    }

    var authorized = null;
    if (typeof username === 'function') {
      var checkFn = username;
      try {
        authorized = checkFn(user.name, user.pass, function checkFnCallback(err, authentified) {
          if (err) {
            return next(err);
          }

          if (authentified) {
            return next();
          }

          return unauthorized(res, realm);
        });
      } catch(err) {
        next(err);
      }
    } else {
      authorized = !(!user || user.name !== username || user.pass !== password);
    }

    if (isPromiseLike(authorized)) {
      return authorized
        .then(function(authorized) {
          if (authorized === true) {
            return next();
          }

          return unauthorized(res, realm);
        }, next);
    }

    if (authorized === false) {
      return unauthorized(res, realm);
    }

    if (authorized === true) {
      return next();
    }
  };
};

Allow for promise and nodejs style callback


module.exports = function (babel) {
  var exportIds = [];
  var t = babel.types;
  return new babel.Transformer("babel-jsm-plugin", {
    ExportNamedDeclaration: {
      enter: function(node, parent) {
        exportIds.push(node.declaration.id.name);
        // Replace with declarations, which removes the export
        return node.declaration;
      },
    },
    Program: {
      exit: function(node, parent) {
        var arrayOfSymbols = t.ArrayExpression([]);
        exportIds.forEach(function(exportedId) {
          // Create an array of strings with the export identifier names
          arrayOfSymbols.elements.push(t.literal(exportedId));

          // Add in this.identifier = identifier for each export and add it to the end
          var assignmentStatement = t.ExpressionStatement(
            t.assignmentExpression('=', t.Identifier('this.' + exportedId), t.Identifier(exportedId)));
          this.pushContainer('body', assignmentStatement);
        }.bind(this));

        // Create an assignment for this.EXPORTED_SYMBOLS = ['export1', 'export2', ...]
        var exportsVar = t.ExpressionStatement(
          t.assignmentExpression('=', t.Identifier('this.EXPORTED_SYMBOLS'), arrayOfSymbols));
        this.unshiftContainer('body', exportsVar);
      },
    },
  });
};

module.exports = function (babel) {
  var exportIds = [];
  var t = babel.types;
  return new babel.Transformer("babel-jsm-plugin", {
    ExportNamedDeclaration: {
      enter: function(node, parent) {
        // For variable declarations since exports will have multiple id names in one
        if (node.declaration.declarations) {
          node.declaration.declarations.forEach(function(declaration) {
            exportIds.push(declaration.id.name);
          }.bind(this));
          return node.declaration;
        }
        exportIds.push(node.declaration.id.name);
        // Replace with declarations, which removes the export
        return node.declaration;
      },
    },
    Program: {
      exit: function(node, parent) {
        var arrayOfSymbols = t.ArrayExpression([]);
        exportIds.forEach(function(exportedId) {
          // Create an array of strings with the export identifier names
          arrayOfSymbols.elements.push(t.literal(exportedId));

          // Add in this.identifier = identifier for each export and add it to the end
          var assignmentStatement = t.ExpressionStatement(
            t.assignmentExpression('=', t.Identifier('this.' + exportedId), t.Identifier(exportedId)));
          this.pushContainer('body', assignmentStatement);
        }.bind(this));

        // Create an assignment for this.EXPORTED_SYMBOLS = ['export1', 'export2', ...]
        var exportsVar = t.ExpressionStatement(
          t.assignmentExpression('=', t.Identifier('this.EXPORTED_SYMBOLS'), arrayOfSymbols));
        this.unshiftContainer('body', exportsVar);
      },
    },
  });
};

Add support for variable declaration exports


var Transpiler = require('./transpiler');

module.exports = {
	name: 'ember-cli-6to5',
	included: function(app) {
		this._super.included.apply(this, arguments);

		var options = getOptions(app.options['6to5']);
		var plugin = {
			name: 'ember-cli-6to5',
			ext: 'js',
			toTree: function(tree) {
				return new Transpiler(tree, options);
			}
		};

		app.registry.add('js', plugin);
	}
};

function getOptions(options) {
	options = options || {};

	// Ensure modules aren't compiled unless explicitly set to compile
	options.blacklist = options.blacklist || ['modules'];

	if (options.compileModules === true) {
		if (options.blacklist.indexOf('modules') >= 0) {
			options.blacklist.splice(options.indexOf('modules'), 1);
		}
	} else {
		if (options.blacklist.indexOf('modules') < 0) {
			options.blacklist.push('modules');
		}
	}

	return options;
}

var Transpiler = require('./transpiler');

module.exports = {
	name: 'ember-cli-6to5',
	included: function(app) {
		this._super.included.apply(this, arguments);

		var options = getOptions(app.options['6to5']);
		var plugin = {
			name: 'ember-cli-6to5',
			ext: 'js',
			toTree: function(tree) {
				return new Transpiler(tree, options);
			}
		};

		app.registry.add('js', plugin);
	}
};

function getOptions(options) {
	options = options || {};

	// Ensure modules aren't compiled unless explicitly set to compile
	options.blacklist = options.blacklist || ['modules'];

	if (options.compileModules === true) {
		if (options.blacklist.indexOf('modules') >= 0) {
			options.blacklist.splice(options.indexOf('modules'), 1);
		}
	} else {
		if (options.blacklist.indexOf('modules') < 0) {
			options.blacklist.push('modules');
		}
	}

	// Ember-CLI inserts its own 'use strict' directive
	options.blacklist.push('useStrict');

	return options;
}

Add useStrict to the blacklist.


var ids = ['yeka52', 'maboyong', 'datouma', 'gaizhilizcw', 'tianhao', 'qinnan', 'lianghuan', 'talich',
'loveletter', 'zenithdie', 'Glasschurch', 'nosensedigit', 'oldplusnew', 'negative2',
'taosay', 'DKLearnsPop', 'mactalk', 'lswlsw', 'rosicky311', 'zhimovie', 'liangbianyao',
'bianzhongqingnianxingdongzhinan', 'phos-study'];

var rssPath = 'out/zhuanlanrss.xml';

require('./lib/rss')(ids, rssPath);

Revert "Revert "Revert "trigger update"""


"use strict";

const express = require("express");
const app = express();

const isProduction = process.env.NODE_ENV === "production";

/* MIDDLEWARE */

app
  .use(require("helmet")())
  .use(require("compression")())
  .use(require("cors")())
  .use(require('morgan')(isProduction ? 'combined' : 'dev'))
  .disable("x-powered-by");

require("./routes.js")(app);

app.get("*", (req, res) => res.status(404).send("error: code not found!"));

app.listen(process.env.PORT || 3000, () =>
  console.info(`Express server running on port 3000`)
);

"use strict";

const express = require("express");
const app = express();

const isProduction = process.env.NODE_ENV === "production";

/* MIDDLEWARE (stack inspired by kikobeats) */

app
  .use(require("helmet")())
  .use(require("compression")())
  .use(require("cors")())
  .use(require('morgan')(isProduction ? 'combined' : 'dev'))
  .disable("x-powered-by");

require("./routes.js")(app);

app.get("*", (req, res) => res.status(404).send("error: code not found!"));

app.listen(process.env.PORT || 3000, () =>
  console.info(`Express server running on port 3000`)
);

Add comment about the Middleware stack


'use strict';
var angularMeteorSession = angular.module('angular-meteor.session', []);

angularMeteorSession.factory('$session', [
  function () {
    return function (session) {

      return {

        bind: function(scope, model) {
          Tracker.autorun(function(self) {
            scope[model] = Session.get(session);
            if (!scope.$root.$$phase) scope.$apply(); // Update bindings in scope.
            scope.$on('$destroy', function () {
              self.stop(); // Stop computation if scope is destroyed.
            });
          });

          scope.$watch(model, function (newItem, oldItem) {
            Session.set(session, scope[model]);
          }, true);

        }
      };
    }
  }
]);

'use strict';
var angularMeteorSession = angular.module('angular-meteor.session', ['angular-meteor.utils']);

angularMeteorSession.factory('$session', ['$meteorUtils',
  function ($meteorUtils) {
    return function (session) {

      return {

        bind: function(scope, model) {
          $meteorUtils.autorun(scope, function() {
            scope[model] = Session.get(session);
          });

          scope.$watch(model, function (newItem, oldItem) {
            Session.set(session, scope[model]);
          }, true);

        }
      };
    }
  }
]);

Use $meteorUtils.autorun instead of Tracker.autorun in $session


'use strict';

var bind = require('function-bind');
var define = require('define-properties');
var replace = bind.call(Function.call, String.prototype.replace);

var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*/;

var trimLeft = function trimLeft() {
	return replace(this, leftWhitespace, '');
};

var boundTrimLeft = bind.call(Function.call, trimLeft);
define(boundTrimLeft, {
	shim: function shimTrimLeft() {
		if (!String.prototype.trimLeft) {
			define(String.prototype, { trimLeft: trimLeft });
		}
		return String.prototype.trimLeft;
	}
});

module.exports = boundTrimLeft;

'use strict';

var bind = require('function-bind');
var define = require('define-properties');
var replace = bind.call(Function.call, String.prototype.replace);

var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*/;

var trimLeft = function trimLeft() {
	return replace(this, leftWhitespace, '');
};

var boundTrimLeft = bind.call(Function.call, trimLeft);
define(boundTrimLeft, {
	shim: function shimTrimLeft() {
		var zeroWidthSpace = '\u200b';
		define(String.prototype, { trimLeft: trimLeft }, {
			trimLeft: function () {
				return zeroWidthSpace.trimLeft() !== zeroWidthSpace;
			}
		});
		return String.prototype.trimLeft;
	}
});

module.exports = boundTrimLeft;

Fix a bug in node 0.10 (and presumably other browsers) where the zero-width space is erroneously trimmed.


'use strict';

import { NativeEventEmitter, NativeModules } from 'react-native';
const { RNPusherPushNotifications } = NativeModules
const rnPusherPushNotificationsEmitter = new NativeEventEmitter(RNPusherPushNotifications)

export default {
  setAppKey: (appKey) => {
    RNPusherPushNotifications.setAppKey(appKey)
  },
  subscribe: (channel, onError, onSuccess) => {
    RNPusherPushNotifications.subscribe(channel, onError, onSuccess)
  },
  unsubscribe: (channel, onError, onSuccess) => {
    RNPusherPushNotifications.unsubscribe(channel, onError, onSuccess)
  },
  on: (eventName, callback) => {
    rnPusherPushNotificationsEmitter.addListener(
      eventName,
      (payload) => callback(payload)
    )
  }
};

'use strict';

import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
const { RNPusherPushNotifications } = NativeModules
const rnPusherPushNotificationsEmitter = new NativeEventEmitter(RNPusherPushNotifications)

export default {
  setAppKey: (appKey) => {
    RNPusherPushNotifications.setAppKey(appKey)
  },
  subscribe: (channel, onError, onSuccess) => {
    if (Platform.os === 'ios') {
      RNPusherPushNotifications.subscribe(channel)
    } else {
      RNPusherPushNotifications.subscribe(channel, onError, onSuccess)
    }
  },
  unsubscribe: (channel, onError, onSuccess) => {
    if (Platform.os === 'ios') {
      RNPusherPushNotifications.unsubscribe(channel)
    } else {
      RNPusherPushNotifications.unsubscribe(channel, onError, onSuccess)
    }
  },
  on: (eventName, callback) => {
    rnPusherPushNotificationsEmitter.addListener(
      eventName,
      (payload) => callback(payload)
    )
  }
};

Remove iOS callbacks from wrapper


var path = require('path'),
    static = require('serve-static');

module.exports = {
    setup: function (app, assetpath, options) {

        if (arguments.length === 2 && typeof assetpath === 'object') {
            options = assetpath;
            assetpath = '';
        }

        assetpath = assetpath || '/govuk-assets';
        options = options || {};

        app.use(assetpath, static(path.join(__dirname, './node_modules/govuk_template_mustache/assets'), options));
        app.use(function (req, res, next) {
            res.locals.govukAssetPath = assetpath + '/';
            res.locals.partials = res.locals.partials || {};
            res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template');
            next();
        });

    }
};

var path = require('path'),
    static = require('serve-static');

module.exports = {
    setup: function (app, assetpath, options) {

        if (arguments.length === 2 && typeof assetpath === 'object') {
            options = assetpath;
            assetpath = '';
        }

        options = options || {};
        assetpath = assetpath || options.path || '/govuk-assets';

        app.use(assetpath, static(path.join(__dirname, './node_modules/govuk_template_mustache/assets'), options));
        app.use(function (req, res, next) {
            res.locals.govukAssetPath = assetpath + '/';
            res.locals.partials = res.locals.partials || {};
            res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template');
            next();
        });

    }
};

Allow for setting path as part of options object as well as as a function parameter


module.exports = {
  plugins: [
    [require('babel-plugin-dotenv'), {
      replacedModuleName: 'react-native-dotenv'
    }],
  ],
};

var config = require("react-native/packager/rn-cli.config");

module.exports = {
  plugins: [
    [require('babel-plugin-dotenv'), {
      replacedModuleName: 'react-native-dotenv',
      configDir: config.getProjectRoots()[0]
    }],
  ],
};

Use RN’s projectRoots resolver to set the correct configDir


/* eslint-env node */
'use strict';

module.exports = {
  name: require('./package').name,

  included() {
    this._super.included.apply(this, arguments);

    const addonOptions =
      (this.app.options && this.app.options.emberPikaday) || {};

    const dependencies = Object.keys(this.project.dependencies());
    const hasFastboot = dependencies.includes('ember-cli-fastboot');

    const importOptions = {};
    if (hasFastboot) {
      importOptions.using = [{ transformation: 'fastbootShim' }];
    }

    this.import('node_modules/pikaday/pikaday.js', importOptions);
    if (!addonOptions.excludePikadayAssets) {
      this.import('node_modules/pikaday/css/pikaday.css');
    }
  }
};

/* eslint-env node */
'use strict';

module.exports = {
  name: require('./package').name,

  included(app) {
    this._super.included.apply(this, arguments);

    let current = this;
    //Get the top most application where config will reside
    //ref: _findHost https://git.io/Jvi0N
    do {
      app = current.app || app;
    } while (current.parent.parent && (current = current.parent));

    const addonOptions = (app.options && app.options.emberPikaday) || {};

    const dependencies = Object.keys(this.project.dependencies());
    const hasFastboot = dependencies.includes('ember-cli-fastboot');

    const importOptions = {};
    if (hasFastboot) {
      importOptions.using = [{ transformation: 'fastbootShim' }];
    }

    this.import('node_modules/pikaday/pikaday.js', importOptions);
    if (!addonOptions.excludePikadayAssets) {
      this.import('node_modules/pikaday/css/pikaday.css');
    }
  }
};

Fix build when included in an addon


'use strict';
var generators = require('yeoman-generator');

module.exports = generators.Base.extend({
  writing: function () {
    this.fs.copy(
      this.templatePath('babelrc'),
      this.destinationPath('.babelrc')
    );

    var pkg = this.fs.readJSON(this.destinationPath('package.json'), {});
    pkg.script = pkg.script || {};
    pkg.script.prepublish = 'gulp babel';

    this.fs.writeJSON(this.destinationPath('package.json'), pkg);
  }
});

'use strict';
var generators = require('yeoman-generator');

module.exports = generators.Base.extend({
  writing: function () {
    this.fs.copy(
      this.templatePath('babelrc'),
      this.destinationPath('.babelrc')
    );

    var pkg = this.fs.readJSON(this.destinationPath('package.json'), {});
    pkg.scripts = pkg.scripts || {};
    pkg.scripts.prepublish = 'gulp babel';

    this.fs.writeJSON(this.destinationPath('package.json'), pkg);
  }
});

Fix typo in `babel` generator


jQuery(function($) {
  $('.tabify .tabs a').bind('click', function() {
    var href = $(this).attr('href');
    var tabContent = $(href);
    $('.tabify .tabs a').removeClass('active'); // clear the active tabs
    $('.tabify .tabs a[href=' + href + ']').addClass('active'); // activate the clicked tab
    $('.tabify .tabContent').removeClass('active'); // clear the active content
    tabContent.addClass('active'); // show the clicked content
    // Change the hash without scrolling
    tabContent.attr('id', '');
    window.location.hash = href;
    tabContent.attr('id', href.substr(1)); // remove the sharp
    return false;
  });

  //|
  //| If there's a #tab in the URL, CLICK ON THAT TAB!!!
  //|
  if(window.location.hash) {
    $('.tabs a[href="' + window.location.hash + '"]').click();
  }
});

jQuery(function($) {
  $('.tabify .tabs a').bind('click', function() {
    var href = $(this).attr('href'),
        tabify = $(this).closest('.tabify'),
        tabContent = tabify.find(href);
    tabify.find('.tabs a').removeClass('active'); // clear the active tabs
    tabify.find('.tabs a[href=' + href + ']').addClass('active'); // activate the clicked tab
    tabify.find('.tabContent').removeClass('active'); // clear the active content
    tabContent.addClass('active'); // show the clicked content
    // Change the hash without scrolling
    tabContent.attr('id', '');
    window.location.hash = href;
    tabContent.attr('id', href.substr(1)); // remove the sharp
    return false;
  });

  //|
  //| If there's a #tab in the URL, CLICK ON THAT TAB!!!
  //|
  if(window.location.hash) {
    $('.tabs a[href="' + window.location.hash + '"]').click();
  }
});

Fix pages containing multiple tab sets


'use strict'

var window = require('global/window')
var document = require('global/document')
var toArray = require('to-array')

var PREFIXES = /-(webkit|ms)-/

module.exports = detectVendorPrefix()

function detectVendorPrefix () {
  if (!window.getComputedStyle) return ''
  var styles = window.getComputedStyle(document.documentElement, '')
  return toArray(styles).join('').match(PREFIXES)[1]
}

'use strict'

var window = require('global/window')
var document = require('global/document')
var toArray = require('to-array')

var PREFIXES = /-(webkit|ms)-/

module.exports = detectVendorPrefix()

function detectVendorPrefix () {
  if (!window.getComputedStyle) return ''
  var styles = window.getComputedStyle(document.documentElement, '')
  var match = toArray(styles).join('').match(PREFIXES)
  return match ? match[1] : ''
}

Return an empty string when no matches are found, e.g. Firefox


var path = require('path');

module.exports = {
    context: path.join(__dirname, "src"),

    entry: { main: "./main" },
    devtool: "source-map",
    output: {
        path: path.join(__dirname, "dist"),
        filename: "[name].js"
    },

    resolve: {
        extensions: [".ts"]
    },

    module: {
        loaders: [
            { test: /\.ts$/, loader: "ts-loader" }
        ]
    }
};

var path = require('path');

module.exports = {
    context: path.join(__dirname, "src"),

    entry: { main: "./main" },
    devtool: "source-map",
    output: {
        path: path.join(__dirname, "dist"),
        filename: "[name].js"
    },

    resolve: {
        root: [
            path.resolve("."),
            path.resolve("./src")
        ],
        extensions: ["", ".ts", ".js"]
    },

    module: {
        loaders: [
            { test: /\.ts$/, loader: "ts-loader" }
        ]
    }
};

Allow require paths starting from the root


"use strict";

var charsNumbers = '0123456789';
var charsLower   = 'abcdefghijklmnopqrstuvwxyz';
var charsUpper   = charsLower.toUpperCase();

var chars = charsNumbers + charsLower + charsUpper;

exports.generate = function(length) {

  if (!length) length = 32;

  var string = '';

  for (var i = 0; i < length; i++) {
    var randomNumber = Math.floor(Math.random() * chars.length);
    string += chars.substring(randomNumber, randomNumber + 1);
  }

  return string;
}

"use strict";

var charsNumbers = '0123456789';
var charsLower   = 'abcdefghijklmnopqrstuvwxyz';
var charsUpper   = charsLower.toUpperCase();

var crypto = require('crypto');

var chars = charsNumbers + charsLower + charsUpper;

exports.generate = function(length) {

  length = length || 32;

  var string = '';

  while(string.length < length){
    var bf = crypto.randomBytes(length);
    for(var i = 0; i < bf.length; i++){
      var index = bf.readUInt8(i)%chars.length;
      string += chars.charAt(index);
    }
  }

  return string;
}

Use crypto.randomBytes instead of Math.random.


var es = require('event-stream');
var path = require('path');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var header = require('gulp-header');
var footer = require('gulp-footer');
var PluginError = gutil.PluginError;
var htmlJsStr = require('js-string-escape');

function templateCache(root) {
	return es.map(function(file, cb) {
		var template = '$templateCache.put("<%= url %>","<%= contents %>");';

		file.contents = new Buffer(gutil.template(template, {
			url: path.join(root, file.path.replace(file.base, '')),
			contents: htmlJsStr(file.contents),
			file: file
		}));

		cb(null, file);
	});
}

module.exports = function(filename, options) {
	if (!filename) {
		throw new PluginError('gulp-angular-templatecache', 'Missing filename option for gulp-angular-templatecache');
	}
	options = options || {};

	var templateHeader = 'angular.module("<%= module %>", []).run(["$templateCache", function($templateCache) {';
	var templateFooter = '}]);'

	return es.pipeline(
		templateCache(options.root || ''),
		concat(filename),
		header(templateHeader, {
			module: options.module || 'templates'
		}),
		footer(templateFooter)
	)
};

var es = require('event-stream');
var path = require('path');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var header = require('gulp-header');
var footer = require('gulp-footer');
var PluginError = gutil.PluginError;
var htmlJsStr = require('js-string-escape');

function templateCache(root) {
	return es.map(function(file, cb) {
		var template = '$templateCache.put("<%= url %>","<%= contents %>");';
		var url = path.join(root, file.path.replace(file.base, ''));

		if (process.platform === 'win32') {
			url = url.replace(/\\/g, '/');
		}

		file.contents = new Buffer(gutil.template(template, {
			url: url,
			contents: htmlJsStr(file.contents),
			file: file
		}));

		cb(null, file);
	});
}

module.exports = function(filename, options) {
	if (!filename) {
		throw new PluginError('gulp-angular-templatecache', 'Missing filename option for gulp-angular-templatecache');
	}
	options = options || {};

	var templateHeader = 'angular.module("<%= module %>", []).run(["$templateCache", function($templateCache) {';
	var templateFooter = '}]);'

	return es.pipeline(
		templateCache(options.root || ''),
		concat(filename),
		header(templateHeader, {
			module: options.module || 'templates'
		}),
		footer(templateFooter)
	)
};

Handle \ on Windows, normalize to /


var ytdl = require('youtube-dl-vimeo');
var url = 'http://vimeo.com/93491987';
var echojs = require('echojs');
var fs = require('fs'),
request = require('superagent');

var echo = echojs({
  key: process.env.ECHONEST_KEY
});

ytdl.getInfo(url, function(err, data) {
    if (err) throw err;

    var format = data[data.length - 1].split(' - ');
    var video = {
      title       : data[0],
      id          : data[1],
      url         : data[2],
      thumbnail   : data[3],
      description : data.slice(4, data.length - 2).join('\n'),
      filename    : data[data.length - 2],
      format        : format[0],
      resolution  : format[1]
    };

    console.log(video.url);
    var posted = echo('track/upload').post({
        filetype: 'mp3',
        format:'json'
      }, 'application/octet-stream', 'http://www.tonycuffe.com/mp3/girlwho.mp3', function (err, json) {
        // console.log(err, json);
      });

    // request.get(video.url).end(function(e, res){
    //     console.log(e, res.body)
    // });

    // fs.readFile(video.url, function (err, buffer) {
    //     console.log(err, buffer);

    //   echo('track/upload').post({
    //     filetype: 'mp4'
    //   }, 'application/octet-stream', buffer, function (err, json) {
    //     console.log(err, json);
    //   });
    // });

}
);

var ytdl = require('youtube-dl-vimeo');

var echojs = require('echojs'),
request = require('superagent');

var echo = echojs({
	key: process.env.ECHONEST_KEY
});

ytdl.getInfo('http://vimeo.com/45105236', function(err, data) {
	if (err) throw err;

	var format = data[data.length - 1].split(' - ');
	var video = {
		title: data[0],
		id: data[1],
		url: data[2],
		thumbnail: data[3],
		description: data.slice(4, data.length - 2).join('\n'),
		filename: data[data.length - 2],
		format: format[0],
		resolution: format[1]
	};

	request
		.post('http://developer.echonest.com/api/v4/track/upload')
		.send({
			api_key: '',
			url: video.url,
			filetype: 'mp4'
		})
		.type('form')
		.end(function(error, res) {
            if(res.body.response.status !== 0){
                return ;
            }
            console.log(res.body.response.track);
		});

});

Use superagent to request track information from vimeo video


exports.create = function(logger) {

  return function(req, res, next) {
    var rEnd = res.end;

    // To track response time
    req._rlStartTime = new Date();

    // Setup the key-value object of data to log and include some basic info
    req.kvLog = {
        date: req._rlStartTime.toISOString()
      , method: req.method
      , url: req.originalUrl
      , _rlLevel: 'info' // internal usage
      , type: 'reqlog'
    };

    // Proxy the real end function
    res.end = function(chunk, encoding) {
      // Do the work expected
      res.end = rEnd;
      res.end(chunk, encoding);

      // And do the work we want now (logging!)

      // Save a few more variables that we can only get at the end
      req.kvLog.status = res.statusCode;
      req.kvLog.response_time = (new Date() - req._rlStartTime);

      // Send the log off to winston
      var level = req.kvLog._rlLevel
        , msg   = req.kvLog.message || '';
      delete req.kvLog._rlLevel;
      if (msg.length) {
        delete req.kvLog.message;
      }
      logger.log(level, msg, req.kvLog);
    };

    next();
  };
};

var url = require('url')

exports.create = function(logger) {

  return function(req, res, next) {
    var rEnd = res.end;

    // To track response time
    req._rlStartTime = new Date();

    // Setup the key-value object of data to log and include some basic info
    req.kvLog = {
        date: req._rlStartTime.toISOString()
      , method: req.method
      , url: url.parse(req.originalUrl).pathname
      , _rlLevel: 'info' // internal usage
      , type: 'reqlog'
    };

    // Proxy the real end function
    res.end = function(chunk, encoding) {
      // Do the work expected
      res.end = rEnd;
      res.end(chunk, encoding);

      // And do the work we want now (logging!)

      // Save a few more variables that we can only get at the end
      req.kvLog.status = res.statusCode;
      req.kvLog.response_time = (new Date() - req._rlStartTime);

      // Send the log off to winston
      var level = req.kvLog._rlLevel
        , msg   = req.kvLog.message || '';
      delete req.kvLog._rlLevel;
      if (msg.length) {
        delete req.kvLog.message;
      }
      logger.log(level, msg, req.kvLog);
    };

    next();
  };
};

Use the url pathname so we don't include query args


// Load the node-ffi extensions
require('./ffi-extend')

// The main exports is the casting function
module.exports = $
$._ = $ // legacy. TODO: remove by 0.1.0

// export the exports from the 'import' module
var Import = require('./import')
$.import  = Import.import
$.resolve = Import.resolve

// This function accepts native JS types (String, Number, Date) and converts them
// to the proper Objective-C type (NSString, NSNumber, NSDate).
//   Syntax Sugar...
function $ (o) {
  var t = typeof o
  if (t == 'string') {
    return $.NSString('stringWithUTF8String', String(o))
  } else if (t == 'number') {
    return $.NSNumber('numberWithDouble', Number(o))
  } else if (isDate(o)) {
    return $.NSDate('dateWithTimeIntervalSince1970', o / 1000)
  }
  throw new Error('Unsupported object passed in to convert')
}

function isDate (d) {
  return d instanceof Date
      || Object.prototype.toString.call(d) == '[object Date]'
}

// Load the node-ffi extensions
require('./ffi-extend')

// The main exports is the casting function
module.exports = $
$._ = $ // legacy. TODO: remove by 0.1.0

// export the exports from the 'import' module
var Import = require('./import')
$.import  = Import.import
$.resolve = Import.resolve

// This function accepts native JS types (String, Number, Date) and converts them
// to the proper Objective-C type (NSString, NSNumber, NSDate).
//   Syntax Sugar...
function $ (o) {
  var t = typeof o
  if (t == 'string') {
    return $.NSString('stringWithUTF8String', String(o))
  } else if (t == 'number') {
    return $.NSNumber('numberWithDouble', Number(o))
  } else if (isDate(o)) {
    return $.NSDate('dateWithTimeIntervalSince1970', o / 1000)
  }
  throw new Error('Unsupported object passed in to convert: ' + o)
}

function isDate (d) {
  return d instanceof Date
      || Object.prototype.toString.call(d) == '[object Date]'
}

Print out the unsupported object when encountered.


'use strict'

var parseURI = require('parse-uri')
var encode = require('punycode2/encode')

// Illegal characters (anything which is not in between the square brackets):
var ILLEGALS = /[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i

// Incomplete HEX escapes:
var HEX1 = /%[^0-9a-f]/i
var HEX2 = /%[0-9a-f](:?[^0-9a-f]|$)/i

// Scheme must begin with a letter, then consist of letters, digits, '+', '.', or '-' => e.g., 'http', 'https', 'ftp'
var PROTOCOL = /^[a-z][a-z0-9\+\-\.]*$/

// If authority is not present, path must not begin with '//'
var PATH = /^\/\//

module.exports = function isURI (str, opts) {
  if (!str) return false

  str = encode(str)

  if (ILLEGALS.test(str)) return false
  if (HEX1.test(str) || HEX2.test(str)) return false

  var uri = parseURI(str, opts)

  if (!Boolean(uri.protocol) || !PROTOCOL.test(uri.protocol.toLowerCase())) return false
  if (!Boolean(uri.authority) && PATH.test(uri.path)) return false

  return true
}

'use strict'

var parseURI = require('parse-uri')
var encode = require('punycode2/encode')

// Illegal characters (anything which is not in between the square brackets):
var ILLEGALS = /[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i

// Incomplete HEX escapes:
var HEX1 = /%[^0-9a-f]/i
var HEX2 = /%[0-9a-f](:?[^0-9a-f]|$)/i

// Scheme must begin with a letter, then consist of letters, digits, '+', '.', or '-' => e.g., 'http', 'https', 'ftp'
var PROTOCOL = /^[a-z][a-z0-9\+\-\.]*$/

// If authority is not present, path must not begin with '//'
var PATH = /^\/\//

module.exports = function isURI (uri, opts) {
  if (!uri) return false

  if (typeof uri !== 'object') {
    uri = encode(uri)
    if (ILLEGALS.test(uri)) return false
    if (HEX1.test(uri) || HEX2.test(uri)) return false
    uri = parseURI(uri, opts)
  }

  if (!uri.protocol || !PROTOCOL.test(uri.protocol.toLowerCase())) return false
  if (!uri.authority && PATH.test(uri.path)) return false

  return true
}

Support provide a URI Object


'use strict';
var pkg = require('./package');
var gutil = require('gulp-util');
var through = require('through2');
var path = require('path');
var File = require('vinyl');

// consts
module.exports = function(out, options) {

  options = options || {};

  var files = [];
  var fileList = [];

  return through.obj(function(file, enc, cb) {
    if (file.isNull()) {
      cb(null, file);
      return;
    }

    if (file.isStream()) {
      cb(new gutil.PluginError(pkg.name, 'Streams not supported'));
      return;
    }

    files.push(file);

    var filePath;
    if (options.absolute) {
      filePath = path.normalize(file.path);
    } else if (options.flatten) {
      filePath = path.basename(file.path);
    } else {
      filePath = path.relative(process.cwd(), file.path);
    }
    if (options.removeExtensions) {
      var extension = path.extname(filePath);
      if (extension.length) {
        filePath = filePath.slice(0, -extension.length);
      }
    }
    filePath = filePath.replace(/\\/g, '/');
    fileList.push(filePath);

    this.push(file);
    cb();
  }, function(cb) {
    var fileListFile = new File({
      path: out,
      contents: new Buffer(JSON.stringify(fileList, null, '  '))
    });

    this.push(fileListFile);
    cb();
  });
};

'use strict';
var pkg = require('./package');
var gutil = require('gulp-util');
var through = require('through2');
var path = require('path');
var File = require('vinyl');

// consts
module.exports = function(out, options) {

  options = options || {};

  var files = [];
  var fileList = [];

  return through.obj(function(file, enc, cb) {
    if (file.isNull()) {
      cb(null, file);
      return;
    }

    if (file.isStream()) {
      cb(new gutil.PluginError(pkg.name, 'Streams not supported'));
      return;
    }

    files.push(file);

    var filePath;
    if (options.absolute) {
      filePath = path.normalize(file.path);
    } else if (options.flatten) {
      filePath = path.basename(file.path);
    } else {
      filePath = path.relative(process.cwd(), file.path);
    }
    if (options.removeExtensions) {
      var extension = path.extname(filePath);
      if (extension.length) {
        filePath = filePath.slice(0, -extension.length);
      }
    }
    filePath = filePath.replace(/\\/g, '/');
    fileList.push(filePath);

    // this.push(file);
    cb();
  }, function(cb) {
    var fileListFile = new File({
      path: out,
      contents: new Buffer(JSON.stringify(fileList, null, '  '))
    });

    this.push(fileListFile);
    cb();
  });
};

Comment the code that duplicates the files


#!/usr/bin/env node

"use strict";

const moment = require("moment");
const sugar = require("sugar");
const chalk = require("chalk");
const exec = require("child_process").exec;

// Throw a fatal error
const fatal = err => {
  console.error(`fatal: ${err}`);
}

process.argv.splice(0, 2);
if (process.argv.length > 0) {

  // Attempt to parse the date
  let date = process.argv.join(" ");
  let parsedDate = new sugar.Date.create(date);

  if (parsedDate != "Invalid Date") {

    // Date could be parsed, parse the date to git date format
    let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ");

    // Actually modify the dates
    let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit";
    exec(command, (err, stdout, stderr) => {
      if (err) {
        fatal("Could not change the previous commit");
      } else {
        console.log("\nModified previous commit:\n    AUTHOR_DATE " + chalk.grey(dateString) + "\n    COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n    " + chalk.bgWhite.black(command) + "\n");
      }
    });

  } else {
    fatal("Could not parse \"" + date + "\" into a valid date");
  }

} else {
  fatal("No date string given");
}

#!/usr/bin/env node

"use strict";

const moment = require("moment");
const sugar = require("sugar");
const chalk = require("chalk");
const exec = require("child_process").exec;

// Throw a fatal error
const fatal = err => {
  console.error(`fatal: ${err}`);
}

process.argv.splice(0, 2);
if (process.argv.length === 0) {
  fatal("No date string given");
} else {

  // Attempt to parse the date
  let date = process.argv.join(" ");
  let parsedDate = new sugar.Date.create(date);

  console.log(parsedDate);
  if (/Invalid Date/.test(parsedDate)) {
    fatal("Could not parse \"" + date + "\" into a valid date");
  } else {

    // Date could be parsed, parse the date to git date format
    let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ");

    // Actually modify the dates
    let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit";
    exec(command, (err, stdout, stderr) => {
      if (err) {
        fatal("Could not change the previous commit");
      } else {
        console.log("\nModified previous commit:\n    AUTHOR_DATE " + chalk.grey(dateString) + "\n    COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n    " + chalk.bgWhite.black(command) + "\n");
      }
    });
  }
}

Use regex to test date condition instead


'use strict';

var fnToStr = Function.prototype.toString;

module.exports = function isCallable(value) {
	try {
		fnToStr.call(value);
		return true;
	} catch (e) {
		return false;
	}
};

'use strict';

var fnToStr = Function.prototype.toString;

module.exports = function isCallable(value) {
	if (typeof value !== 'function') { return false; }
	try {
		fnToStr.call(value);
		return true;
	} catch (e) {
		return false;
	}
};

Add early exit for typeof not "function"


var Tokenizer = require("tokenizer")

module.exports = function (cb) {
  var t = new Tokenizer(cb)

  t.addRule(/^:([A-Za-z_=+\-*&?!$%|<>][A-Za-z0-9_=+\-*&?!$%|<>]*)$/, "keyword")
  t.addRule(/^([A-Za-z_=+\-*&?!$%|<>][A-Za-z0-9_=+\-*&?!$%|<>]*)$/, "symbol")

  t.addRule(/^;[^\n]*$/, "line comment")

  t.addRule(/^\($/, "open paren")
  t.addRule(/^\)$/, "close paren")
  t.addRule(/^\[$/, "open square")
  t.addRule(/^\]$/, "close square")
  t.addRule(/^{$/, "open curly")
  t.addRule(/^}$/, "close curly")

  t.addRule(/^(#|'|\^|\.|\/)$/, "operator")

  t.addRule(/^"([^"\n]|\\")*"?$/, "string")
  t.addRule(/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/, "number")
  t.addRule(Tokenizer.whitespace)

  return t
}

var Tokenizer = require("tokenizer")

module.exports = function (cb) {
  var t = new Tokenizer(cb)

  t.addRule(/^:([A-Za-z_=+\-*&?!$%|<>\./][A-Za-z0-9_=+\-*&?!$%|<>\./]*)$/, "keyword")
  t.addRule(/^([A-Za-z_=+\-*&?!$%|<>\./][A-Za-z0-9_=+\-*&?!$%|<>\./]*)$/, "symbol")

  t.addRule(/^;[^\n]*$/, "line comment")

  t.addRule(/^\($/, "open paren")
  t.addRule(/^\)$/, "close paren")
  t.addRule(/^\[$/, "open square")
  t.addRule(/^\]$/, "close square")
  t.addRule(/^{$/, "open curly")
  t.addRule(/^}$/, "close curly")

  t.addRule(/^(#|'|\^)$/, "macro")

  t.addRule(/^"([^"\n]|\\")*"?$/, "string")
  t.addRule(/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/, "number")
  t.addRule(Tokenizer.whitespace)

  return t
}

Move "." and "/" into symbol/keyword


module.exports = function() {
  var args    = Array.prototype.slice.call(arguments);
  var cursor  = args[0];
  var keys    = args.slice(1);

  for(var i = 0; i < keys.length; i++) {
    cursor = cursor[keys[i]];
    if (cursor === void 0)
      return void 0;
  }

  return cursor;
}

module.exports = function() {
  var args    = Array.prototype.slice.call(arguments);
  var cursor  = args[0];
  var keys    = args.slice(1);

  for(var i = 0; i < keys.length; i++) {
    cursor = cursor[keys[i]];
    if (cursor == null)
      return void 0;
  }

  return cursor;
}

Add support for null values


var toc = require('markdown-toc');

module.exports = {
    book: {
      assets: './assets',
      css: [
        "atoc.css"
      ],
      js: [
        "atoc.js"
      ]
    },
    hooks: {
        "page:before": function (page) {
            page.content = toc.insert(page.content, {
                slugify: function (str) {
                    return encodeURI(str.toLowerCase().replace(/[\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-]/g,'')).replace(/%20/g, '-');
                }
            });
            if (this.options.pluginsConfig.atoc.addClass) {
                var className = this.options.pluginsConfig.atoc.className || 'atoc';
                page.content = page.content + '\n\n\n<script type="text/javascript">var className=\'' + className + '\';</script>';
            }
            return page;
        }
    }
};

var toc = require('markdown-toc');

module.exports = {
    book: {
      assets: './assets',
      css: [
        "atoc.css"
      ],
      js: [
        "atoc.js"
      ]
    },
    hooks: {
        "page:before": function (page) {
            page.content = toc.insert(page.content, {
                slugify: function (str) {
                    return encodeURI(str.toLowerCase().replace(/[\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~]/g,'')).replace(/%20/g, '-');
                }
            });
            if (this.options.pluginsConfig.atoc.addClass) {
                var className = this.options.pluginsConfig.atoc.className || 'atoc';
                page.content = page.content + '\n\n\n<script type="text/javascript">var className=\'' + className + '\';</script>';
            }
            return page;
        }
    }
};

Remove the replacement of the hyphen becaue if the title includes a - it broke the links


'use strict';

var extend = require('xtend');

var fillopts = function (wrapped, opts) {
    opts = extend(wrapped.opts, opts);
    wrapped = wrapped.wrapped || wrapped;

    var fn = function (callOpts /*, args... */) {
        var newArgs,
            args = Array.prototype.slice.call(arguments, 1);
        newArgs = [extend(opts, callOpts)];
        newArgs.push(args);
        return wrapped.apply(this, newArgs);
    };

    fn.wrapped = wrapped;
    fn.opts = opts;

    fn.withOpts = function (moreOpts) {
        return fillopts(fn, moreOpts);
    };

    return fn;
};

module.exports = fillopts;

'use strict';

var extend = require('xtend');

var fillopts = function (wrapped, opts, position) {
    position = position || 0;
    var optsList = wrapped.optsList ? wrapped.optsList.slice(0) : [];
    optsList[position] = extend(optsList[position], opts);
    wrapped = wrapped.wrapped || wrapped;

    var fn = function () {
        var args = [],
            len = Math.max(arguments.length, optsList.length);
        for (var i = 0; i < len; i++) {
            var arg = arguments[i];
            args.push(optsList[i] ? extend(optsList[i], arg) : arg);
        }
        return wrapped.apply(this, args);
    };

    fn.wrapped = wrapped;
    fn.optsList = optsList;

    fn.withOpts = function (moreOpts, position) {
        return fillopts(fn, moreOpts, position);
    };

    return fn;
};

module.exports = fillopts;

Allow opts in any position


/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import Realm from 'realm';

/**
 * An abstract object which contains metadata describing an indicator row or column.
 *
 * @property  {string}            id
 * @property  {ProgramIndicator}  indicator
 * @property  {string}            description
 * @property  {string}            code
 * @property  {number}            index
 * @property  {boolean}           isRequired
 * @property  {string}            valueType
 * @property  {string}            valueDefault
 * @property  {string}            axis
 * @property  {boolean}           isActive
 */
export class IndicatorAttribute extends Realm.Object {}

export default IndicatorAttribute;

IndicatorAttribute.schema = {
  name: 'IndicatorAttribute',
  primaryKey: 'id',
  properties: {
    id: 'string',
    indicator: 'ProgramIndicator',
    description: { type: 'string', default: 'placeholderDescription' },
    code: { type: 'string', default: 'placeholderCode' },
    index: { type: 'int', default: 0 },
    isRequired: { type: 'bool', default: true },
    valueType: { type: 'string', default: 'string' },
    valueDefault: { type: 'string', default: 'string' },
    axis: { type: 'string', default: 'row' },
    isActive: { type: 'bool', default: false },
  },
};

/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import Realm from 'realm';

/**
 * An abstract object which contains metadata describing an indicator row or column.
 *
 * @property  {string}            id
 * @property  {ProgramIndicator}  indicator
 * @property  {string}            description
 * @property  {string}            code
 * @property  {number}            index
 * @property  {boolean}           isRequired
 * @property  {string}            valueType
 * @property  {string}            valueDefault
 * @property  {string}            axis
 * @property  {boolean}           isActive
 */
export class IndicatorAttribute extends Realm.Object {
  /**
   * Get if an attribute is a row.
   */
  get isRow() {
    return this.axis === 'row';
  }

  /**
   * Get if an attribute is a column.
   */
  get isColumn() {
    return this.axis === 'column';
  }
}

export default IndicatorAttribute;

IndicatorAttribute.schema = {
  name: 'IndicatorAttribute',
  primaryKey: 'id',
  properties: {
    id: 'string',
    indicator: 'ProgramIndicator',
    description: { type: 'string', default: 'placeholderDescription' },
    code: { type: 'string', default: 'placeholderCode' },
    index: { type: 'int', default: 0 },
    isRequired: { type: 'bool', default: true },
    valueType: { type: 'string', default: 'string' },
    valueDefault: { type: 'string', default: 'string' },
    axis: { type: 'string', default: 'row' },
    isActive: { type: 'bool', default: false },
  },
};

Add indicator attribute row, column helpers