render: function(options) {
        _.defaults(options, this.defaults);

        return _.trim(`
daemon off;

worker_processes ${options.worker_processes};
events {
    worker_connections ${options.worker_connections};
}

error_log stderr info;

stream {
    include /etc/nginx/stream.d/*.conf;
}
        `);
    }
Example #2
0
export default function validatePostData (userId, data) {
  if (!trim(data.name)) {
    throw new Error('title can\'t be blank')
  }
  const allowedTypes = [Post.Type.REQUEST, Post.Type.OFFER, Post.Type.DISCUSSION, Post.Type.PROJECT, Post.Type.EVENT]
  if (data.type && !includes(allowedTypes, data.type)) {
    throw new Error('not a valid type')
  }
  if (isEmpty(data.community_ids)) {
    throw new Error('no communities specified')
  }
  if (data.topicNames && data.topicNames.length > 3) {
    throw new Error('too many topics in post, maximum 3')
  }

  return Group.allHaveMember(data.community_ids, userId, Community)
  .then(ok => ok ? Promise.resolve() : Promise.reject(new Error('unable to post to all those communities')))
}
Example #3
0
export function shouldDisplay(label: any, searchKeyword: string) {
  if (!_.trim(searchKeyword)) {
    return true;
  }
  const keyword = searchKeyword.toLocaleLowerCase();
  if (typeof label === 'string') {
    return label.toLocaleLowerCase().indexOf(keyword) >= 0;
  } else if (React.isValidElement(label)) {
    const nodes = reactToString(label);
    return (
      nodes
        .join('')
        .toLocaleLowerCase()
        .indexOf(keyword) >= 0
    );
  }
  return false;
}
Example #4
0
        TemplateLiteral : function(path, state){
            var rawCode = _.trim(this.file.code.substring(path.node.start, path.node.end), '`');

            var defaultOptions = {
                prefix : 'sql:',
                mode:'lodash'
            };

            var options = _.assign({}, defaultOptions, state.opts);

            //如果不命中则直接返回
            if(rawCode.substring(0, options.prefix.length).toLowerCase() != options.prefix.toLowerCase()){
                return;
            }else{
                rawCode = rawCode.substring(options.prefix.length);
            }



            //parse and gen code
            var ast = SQLParser.parse(rawCode);
            ast.yy = SQLParser.yy;
            ast.yy.clear();

            var code = SQLComplile.exec(ast, {
                mode:options.mode,
                rawCode:rawCode
            }, path);


            if(options.debug){
                console.log(rawCode, '==>', code);
            }


            //save the TemplateLiteral expressions
            var preexp = path.node.expressions;
            var replacement = babylon.parse( '(' + code + ')' , {plugins:['objectRestSpread']});
            replacement = replacement.program.body[0].expression;
            //path.replaceWithSourceString(code);
            path.replaceWith(
                t.callExpression(replacement, [t.arrayExpression(preexp)])
            );
        }
Example #5
0
ActionContainer.prototype._getOptional = function( args, options ) {
	var prefixChars = this.prefixChars;
	var optionStrings = [];
	var optionStringsLong = [];

	// determine short and long option strings
	args.forEach( function( optionString ) {
		// error on strings that don't start with an appropriate prefix
		if( prefixChars.indexOf( optionString[0] ) < 0 ) {
			throw new Error( format( 'Invalid option string "%s": must start with a "%s".',
				optionString,
				prefixChars
			) );
		}

		// strings starting with two prefix characters are long options
		optionStrings.push( optionString );
		if( optionString.length > 1 && prefixChars.indexOf( optionString[1] ) >= 0 ) {
			optionStringsLong.push( optionString );
		}
	} );

	// infer dest, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
	var dest = options.dest || null;
	delete options.dest;

	if( !dest ) {
		var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0];
		dest = _.trim( optionStringDest, this.prefixChars );

		if( dest.length === 0 ) {
			throw new Error(
				format( 'dest= is required for options like "%s"', optionStrings.join( ', ' ) )
			);
		}
		dest = dest.replace( /-/g, '_' );
	}

	// return the updated keyword arguments
	options.dest = dest;
	options.optionStrings = optionStrings;

	return options;
};
Example #6
0
function reply(event, callback) {
  var msg = lodash.trim(event.query.Body || '')
  var txt = 'sorry, eh'
  if (msg === 'hi') {
    txt = 'hello world'
  }
  if (msg === 'status') {
    txt = 'systems nominal'
  }
  if (msg === '') {
    txt = '...'
  }
  event.reply = {
    to: event.query.From,
    from: event.query.To,
    body: txt
  }
  callback(null, event)
}
Example #7
0
 _.each(env.settings.enable, function eachEnable(enable) {
   if (_.trim(enable)) {
     _.forIn(envs, function eachEnvPair (value, key) {
       var env = normalizeEnv(key);
       if (_.startsWith(env, enable.toUpperCase() + '_')) {
         var split = env.indexOf('_');
         if (split > -1 && split <= env.length) {
           var exts = extended[enable] || {};
           extended[enable] = exts;
           var ext = _.camelCase(env.substring(split + 1).toLowerCase());
           if (!isNaN(value)) { value = Number(value); }
           if (typeof value === 'string' && (value.toLowerCase() === 'on' || value.toLowerCase() === 'true')) { value = true; }
           if (typeof value === 'string' && (value.toLowerCase() === 'off' || value.toLowerCase() === 'false')) { value = false; }
           exts[ext] = value;
         }
       }
     });
   }
 });
function formatStyle(style) {
  if (!_.trim(style)) {
    return '';
  }

  const formattedStyle = _(style.split(';'))
    .map(_.trim)
    .filter()
    .map((styleItem) => {
      const styleItemArray = styleItem.split(':').map(_.trim);
      const styleItemName = formatStyleName(styleItemArray[0]);
      const styleItemValue = styleItemArray[1];
      return `${styleItemName}: '${styleItemValue}'`;
    })
    .value()
    .join(', ');

  return formattedStyle;
}
    axios.get('http://mockbin.org/bin/3f1037be-88f3-4e34-a8ec-d602779bf2d6').then(data => {
      let records = [];
      let rows = _.split(_.trim(data.data), '\n');
      //let dataHeaders = _.split(_.head(rows), ',');
      let dataRows = _.tail(rows);

      _(dataRows).forEach(function (row) {
        let cells = _.split(row, ',');
        records.push({
          campaign: cells[0],
          channel: cells[1],
          clicks: _.toInteger(cells[2]),
          impressions: _.toInteger(cells[3])
        });
      });
      this.updateRecords(records);
      this.convertChannelsToOptions(records);

    }).catch(function (error) {
Example #10
0
  socket.on('data', function(data) {

    var cmd = data.toString().replace(/(\r?\n)+$/, '');
    debug('receive command: %s', cmd);

    // heart
    if (cmd === 'ping') return socket.write('pong\n');

    // hello world
    if (cmd === 'hello') return socket.write('world\n');

    if (/^file /.test(cmd)) {
      var file = _.trim(cmd.slice(5));
      file = __dirname + '/public/send/' + file;
      if (fs.existsSync(file)) {
        sendFile(socket, file);
      }
    }
  });
Example #11
0
module.exports.pickTableName = function(sql) {
  var tmpSql = _.trim(sql).replace(/\t|\n/g, ' ').replace(/ +/g, ' ');
  tmpSql = tmpSql.replace(/\?/g, '0'); // for node-mysql tplsql
  if (/^delete/i.test(tmpSql)) {
    return [tmpSql.split(' ')[2]];
  }
  try {
    var ast = nQuery.parse(tmpSql);
  } catch(e) {
    console.log('XXXXXXXX', tmpSql, e);
    return ['wrongSql'];
  }
  if (_.includes(['insert', 'update'], ast.type)) {
    return [ast.db ? [ast.db, ast.table].join('.') : ast.table];
  }
  return _.map(ast.from, function(f) {
    return f.db ? [f.db, f.table].join('.') : f.table;
  });
};
Example #12
0
/**
 * Performs common string formatting operations.
 *
 * @private
 * @param {string} string The string to format.
 * @returns {string} The formatted string.
 */
function format(string) {
  var snippets = [];

  // Replace all code snippets with a token.
  string = string.replace(reCode, function(match) {
    snippets.push(match);
    return token;
  });

  return _.trim(string
    // Italicize parentheses.
    .replace(/(^|\s)(\([^)]+\))/g, '$1*$2*')
    // Mark numbers as inline code.
    .replace(/[\t ](-?\d+(?:.\d+)?)(?!\.[^\n])/g, ' `$1`')
    // Replace all tokens with code snippets.
    .replace(reToken, function(match) {
      return snippets.shift();
    }));
}
Example #13
0
 //function that takes the body, finds the page info section at the bottom
 //parses it, and returns information about it
 function pageInfo(body){
    var pageSummary = _.trim(body('nobr').text());
    if(pageSummary){
        var pattern = /\[(.*)\/(.*)\]/;
        var matches = pageSummary.match(pattern);
        var currentPage = Number(matches[1]);
        var totalPages = Number(matches[2]);
    } else {
        var currentPage = 1;
        var totalPages = 1;
    }
    
    return {
        currentPage: currentPage,
        totalPages: totalPages,
        pagesLeft: totalPages - currentPage
    }
    
 }  
Example #14
0
export async function unblockAndGetVersionAsync(projectRoot?: string) {
  if (!isPlatformSupported()) {
    return null;
  }

  try {
    // `watchman version` returns:
    // {
    //  "version": "4.7.0"
    // }
    let result = await _unblockAndVersionAsync(projectRoot);
    let watchmanVersion = JSON.parse(_.trim(result.stdout)).version;
    return watchmanVersion;
  } catch (e) {
    // TODO: Maybe check to make sure this is ENOENT (which means watchman isn't installed)
    // We might want to report other errors
    return null;
  }
}
Example #15
0
/**
 * Extracts the entry's description.
 *
 * @memberOf Entry
 * @returns {string} The entry's description.
 */
function getDesc() {
  var result = getMultilineValue(this.entry, 'description');
  if (!result) {
    return result;
  }
  result = _.trim(result
    .replace(/:\n(?=[\t ]*\S)/g, ':<br>\n')
    .replace(/(?:^|\n)[\t ]*\*\n[\t ]*\*[\t ]*/g, '\n\n')
    .replace(/(?:^|\n)[\t ]*\*[\t ]/g, ' ')
    .replace(/\n( *)[-*](?=[\t ]+\S)/g, '\n<br>\n$1*')
    .replace(/^[\t ]*\n/gm, '<br>\n<br>\n')
  );

  var type = this.getType();
  if (type != 'unknown') {
    result = (type == 'Function' ? '' : '(' + type.replace(/\|/g, ', ') + '): ') + result;
  }
  return result;
}
Example #16
0
function fixSnippet(snippet, options, type) {
    var t = _.trim(snippet);
    if (_.startsWith(t, '{') || _.startsWith(t, '"') || _.endsWith(t, '}') || _.endsWith(t, '"') || _.endsWith(t, ','))
        return snippet;
    if (!options.hasLeadingQuote)
        snippet = '"' + snippet;
    if (!options.hasTrailingQuote && !_.endsWith(snippet, '.'))
        snippet = snippet + '"';
    if (type === "string") {
        snippet = snippet += ': ""';
    }
    else if (type === "object") {
        snippet = snippet += ': {}';
    }
    else if (type === "array") {
        snippet = snippet += ': []';
    }
    return snippet;
}
Example #17
0
module.exports = (scope, cb) => {
  if (!scope.rootPath || !scope.id) {
    return cb.invalid('Usage: `$ strapi generate:controller controllerName --api apiName --plugin pluginName`');
  }

  // `scope.args` are the raw command line arguments.
  _.defaults(scope, {
    id: _.trim(_.deburr(scope.id)),
    api: scope.id
  });

  // Determine default values based on the available scope.
  _.defaults(scope, {
    globalID: _.upperFirst(_.camelCase(scope.id)),
    ext: '.js'
  });

  // Determine the destination path.
  let filePath;
  if (scope.args.api) {
    filePath = `./api/${scope.args.api}/controllers`;
  } else if (scope.args.plugin) {
    filePath = `./plugins/${scope.args.plugin}/controllers`;
  } else {
    filePath = `./api/${scope.id}/controllers`;
  }

  // Take another pass to take advantage of the defaults absorbed in previous passes.
  _.defaults(scope, {
    rootPath: scope.rootPath,
    filePath,
    filename: scope.globalID + scope.ext
  });

  // Humanize output.
  _.defaults(scope, {
    humanizeId: _.camelCase(scope.id).toLowerCase(),
    humanizedPath: '`' + scope.filePath + '`'
  });

  // Trigger callback with no error to proceed.
  return cb();
};
Example #18
0
      })(function(error, results) {
        if(_.isEmpty(_.trim(commodity.sid))) commodity.sid = null;

        if(id && id.length > 0 && source && source.length > 0) {
          domain = null;
          // 亚马逊
          if(source.indexOf('amazon') > -1) {
            var awsClient;
            // 卓越亚马逊
            if(source.indexOf('amazon.cn') > -1 && source.indexOf('moretao-23') < 0) {
              awsClient = awsClients.cn;
              domain = awsOptopns.cn.domain;
            }
            // 日亚
            if(source.indexOf('amazon.jp') > -1 && source.indexOf('moretao-22') < 0) {
              awsClient = awsClients.jp;
              domain = awsOptopns.jp.domain;
            }
            // 美亚
            if(source.indexOf('amazon.com') > -1 && source.indexOf('moretao-20') < 0) {
              awsClient = awsClients.us;
              domain = awsOptopns.us.domain;
            }

            // 亚马逊统一处理
            if(awsClient) {
              awsClient.itemLookup({
                idType: 'ASIN',
                itemId: id,
                domain: domain,
                truncateReviewsAt: '2000',
                responseGroup: 'ItemAttributes,Offers,Images'
              }).then(function(results) {
                var full = results[0].DetailPageURL[0];
                if(full && full.length > 0) commodity.url = decodeURIComponent(full);
                cb(null, null);
              }).catch(function(err) { cb(err, null); });
            } else cb(null, null);
          } else cb(null, null);

            // TODO 其他
        } else cb(null, null);
      });
Example #19
0
File: user.js Project: qious/proxy
User.searchAsync = function* (key) {
  key = '%' + _.trim(key, '%') + '%';
  let users = yield UserModel.findAll({
    where: {
      $or: {
        user_id: {$like: key},
        name: {$like: key},
      },
    },
    order: 'regist_at',
  });

  let res = [];
  for (let user of users) {
    res.push(user.get({plain: true}));
  }

  return res;
};
Example #20
0
Git.prototype.loadBranches = function () {
  var self = this;

  var gitCommand = gitExec + ' branch --list';

  var stdout = execSync(gitCommand);

  this.branches = _.trim(stdout.toString()).split('\n')
    .map(function (line, index) {
      if (line.charAt(0) === '*') {
        self.currentBranchIndex = index;
        return _.trim(line.slice(2));
      } else {
        return _.trim(line);
      }
    });

  return this.branches;
};
Example #21
0
let getSzPagingInfo = function getSzPagingInfo(html){
    let $    = cheerio.load(html, { decodeEntities:false });
    let text = _.trim($('td[colspan="12"]',this).text());
    if(text === MSG.NO_DATA_FROM_SZ){ return { totalPg: 0, totalCount: 0 }; }

    let pgUrlNext = $('input.cls-navigate-next', this).attr('onclick') || '';
    let pgUrlPrev = $('input.cls-navigate-prev', this).attr('onclick') || '';
    if(!pgUrlNext && !pgUrlPrev) { return { totalPg:1, totalCount: $('tr.cls-data-tr', this).length }; }

    let pgIdxNext = pgUrlNext.indexOf('&tab1PAGECOUNT=') + '&tab1PAGECOUNT='.length;
    let pgIdxPrev = pgUrlPrev.indexOf('&tab1PAGECOUNT=') + '&tab1PAGECOUNT='.length;
    let totalSzPg = _.parseInt(pgUrlNext.substr(pgIdxNext)) || _.parseInt(pgUrlPrev.substr(pgIdxPrev));

    let totalIdxNext = pgUrlNext.indexOf('&tab1RECORDCOUNT=') + '&tab1RECORDCOUNT='.length;
    let totalIdxPrev = pgUrlPrev.indexOf('&tab1RECORDCOUNT=') + '&tab1RECORDCOUNT='.length;
    let totalCount   = _.parseInt(pgUrlNext.substr(totalIdxNext)) || _.parseInt(pgUrlPrev.substr(totalIdxPrev));

    return { totalPg: totalSzPg, totalCount };
};
    vm.validateForm = () => {
        const proposedName = _.trim(vm.form.name);
        const existingNames = _.map(vm.candidates, 'name');

        const nameDefined = _.size(proposedName) > 0;
        const nameUnique = ! _.includes(existingNames, proposedName);
        const formatDefined = _.size(vm.form.format) > 0;

        const message = (nameDefined ? "" : "Name cannot be empty. ")
            +
            (nameUnique ? "" : "Name must be unique. ")
            +
            (formatDefined ? "" : "Format must be supplied");

        vm.validation = {
            canSubmit: nameDefined && nameUnique && formatDefined,
            message
        };
    };
Example #23
0
function getTimespanData( str ) {

	var tsType, gtPosition, dtStart, dtEnd;

	str = _.trim( str );

	gtPosition = str.indexOf(">");

	if( gtPosition === -1 ) {
		tsType = "point";
		dtStart = resolveDate( str );
		dtEnd = null;

		if( dtStart === null ) {
			return null;
		}

	} else {

		tsType = "span";
		dtStart = resolveDate( str.substr( 0, gtPosition ) );
		dtEnd = resolveDate( str.substr( ( gtPosition + 1 ) ) );

		if( dtStart === null || dtEnd === null ) {
			return null;
		}

		if( dtStart > dtEnd ) {
			var tmp = dtStart;
			dtStart = dtEnd;
			dtEnd = tmp;
		}

	}

	return {
		type: tsType,
		start: dtStart,
		end: dtEnd
	};

}
Example #24
0
ArgumentParser.prototype.addSubparsers = function( options ) {
	if( !!this._subparsers ) {
		this.error( 'Cannot have multiple subparser arguments.' );
	}

	options = options || {};
	options.debug = (this.debug === true);
	options.optionStrings = [];
	options.parserClass = (options.parserClass || ArgumentParser);


	if( !!options.title || !!options.description ) {

		this._subparsers = this.addArgumentGroup( {
			title: (options.title || 'subcommands'),
			description: options.description
		} );
		delete options.title;
		delete options.description;

	} else {
		this._subparsers = this._positionals;
	}

	// prog defaults to the usage message of this parser, skipping
	// optional arguments and with no "usage:" prefix
	if( !options.prog ) {
		var formatter = this._getFormatter();
		var positionals = this._getPositionalActions();
		var groups = this._mutuallyExclusiveGroups;
		formatter.addUsage( this.usage, positionals, groups, '' );
		options.prog = _.trim( formatter.formatHelp() );
	}

	// create the parsers action and add it to the positionals list
	var ParsersClass = this._popActionClass( options, 'parsers' );
	var action = new ParsersClass( options );
	this._subparsers._addAction( action );

	// return the created parsers action
	return action;
};
                    }, (response) => {
                        let issues = _.get(response, 'data._issues');

                        if (issues) {
                            if (angular.isDefined(issues['validator exception'])) {
                                var errors = issues['validator exception'];
                                var modifiedErrors = errors.replace(/\[/g, '')
                                    .replace(/\]/g, '')
                                    .split(',');

                                for (var i = 0; i < modifiedErrors.length; i++) {
                                    var message = _.trim(modifiedErrors[i]);
                                    // the message format is 'Field error text' (contains ')
                                    var field = message.split(' ')[0].substr(1);

                                    $scope.error[field.toLowerCase()] = true;
                                    notify.error(message);
                                }

                                if (errors.indexOf('9007') >= 0 || errors.indexOf('9009') >= 0) {
                                    authoring.open(item._id, true).then((res) => {
                                        $scope.origItem = res;
                                        $scope.dirty = false;
                                        $scope.item = _.create($scope.origItem);
                                    });
                                }

                                return $q.reject(false);
                            }

                            if (issues.unique_name && issues.unique_name.unique) {
                                notify.error(UNIQUE_NAME_ERROR);
                                return $q.reject(false);
                            }
                        } else if (response && response.status === 412) {
                            notifyPreconditionFailed();
                            return $q.reject(false);
                        }

                        notify.error(gettext('Unknown Error: Item not published.'));
                        return $q.reject(false);
                    });
Example #26
0
  getCurrentSha: function(opts, callback) {
    if (typeof opts === 'string') {
      opts = { cwd: opts };
    }
    else if (typeof opts === 'function' && typeof callback === 'undefined') {
      callback = opts;
      opts = null;
    }

    if (!opts) {
      opts = {};
    }
    if (!opts.cwd) {
      opts.cwd = process.cwd();
    }

    var async = typeof callback === 'function';
    var err = opts.cwd ? null : new Error('You did not provide `opts.cwd`');

    if (!err && !this.isLocalRepo(opts.cwd)) {
      err = new Error('Not a valid git repo: ' + opts.cwd);
    }

    var commitSha = null;
    var refName = opts.branch || 'HEAD';
    if (!err) {
      var result = execSync('git rev-parse ' + refName, { cwd: opts.cwd });
      commitSha = (!!result && result.status === 0 && _.trim(result.stdout)) || null;
    }

    if (async) {
      setImmediate(function() {
        callback(err, commitSha);
      });
    }
    else {
      if (err) {
        throw err;
      }
      return commitSha;
    }
  },
Example #27
0
function schemaGet(schema, path) {
    // ignore .data
    var p = (path || '').split('/');
    var rootSchema = schema;
    while (p.length) {
        var s = p.shift();
        if (schema.properties && schema.properties[s]) {
            schema = schema.properties[s];
        }
        else if (schema.additionalProperties) {
            schema = schema.additionalProperties;
        }
        if (schema.$ref) {
            // This is the most common def case, may not always work
            var childPath = _.trim(schema.$ref, '/#').split('/').join('.');
            schema = _.get(rootSchema, childPath);
        }
    }
    return schema;
}
Example #28
0
	return new Promise(function(resolve, reject){

		// private key is required
		if (!privateKey || !_.trim(privateKey).length) return reject(new Error("private key is required for signing"));

		// create new stone
		var stone = newStone();

		// validate meta block
		var err = Validator.validateMetaBlock(meta);
		if (err instanceof Error) return reject(err);

		// assign meta to stone.meta
		stone.meta = meta;

		// sign meta block
		stone.sign("meta", privateKey).then(function(signature){
			resolve(stone);
		}).catch(reject);
	});
Example #29
0
	return new Promise(function(resolve, reject){

		// public key is required
		if (!publicKey || !_.trim(publicKey).length) return reject(new Error("public key is required for verifying"));
		
		// check key validity
		if (!utility.isValidRSAPublickKey(publicKey)) return reject(new Error("public key is invalid"));

		// check if block name is valid
		if (_.indexOf(blockNames, blockName) === -1) return reject(new Error("block unknown"));

		// ensure block has signature
		if (!this.hasSignature(blockName)) return reject(new Error("block `"+blockName+"` has no signature"));

		// verify an RSA signature
		utility.verifyRSASig(publicKey, this.signatures[blockName]).then(function(result){
			return (result.verified) ? resolve(true) : resolve(false);
		}).catch(reject);

	}.bind(this));
Example #30
0
        .then(function(data) {
            var result = data[0];
            var roundtripsFormatted = data[1];
            var message = '';

            if (result.message) {
                message += `${result.message}\n\n`;
            }
            message += roundtripsFormatted;
            // Make sure bot message text is not empty.
            if (!message) {
                message = polyglot.t('noTicketsText');
            }
            message = _.trim(message);

            return {
                message: message,
                roundtrips: result.roundtrips
            };
        });