Example #1
0
  /**
   * Return a formatted value according to the
   * data type and value stored in database
   *
   * @param type  {String} Data type
   * @param value {*}      Value stored in database
   * @returns {*}
   */
  getDisplayedValue(type, value, name) {
    switch (toLower(type)) {
      case 'string':
      case 'text':
      case 'email':
      case 'enumeration':
        return (value && !isEmpty(toString(value))) || name === 'id' ? toString(value) : '-';
      case 'float':
      case 'integer':
      case 'biginteger':
      case 'decimal':
        return !isNull(value) ? toString(value) : '-';
      case 'boolean':
        return value !== null ? toString(value) : '-';
      case 'date':
      case 'time':
      case 'datetime':
      case 'timestamp': {
        if (value === null) {
          return '-';
        }

        const date = value && isObject(value) && value._isAMomentObject === true ?
          value :
          moment.utc(value);

        return date.format('YYYY-MM-DD HH:mm:ss');
      }
      case 'password':
        return '••••••••';
      default:
        return '-';
    }
  }
Example #2
0
/**
 * Extracts the entry's `returns` data.
 *
 * @memberOf Entry
 * @returns {array} Returns the entry's `returns` data.
 */
function getReturns() {
  var tag = getTag(this, 'returns'),
      desc = _.toString(_.get(tag, 'description')),
      type = _.toString(_.get(tag, 'type.name')) || '*';

  return tag ? [type, desc] : [];
}
Example #3
0
CartOrder.prototype._deliveryPrice = function (current_order) {
  var self = this;
  var delivery_price = _.toString(current_order.delivery_price) || _.toString(current_order.order.delivery_price);

  self.delivery_price = parseFloat(delivery_price);

  return;
};
Example #4
0
function getLocalDateAndTime(){
	var date = getLocalDate();   // 2016-5-4
	var weekday = getWeekday(); //星期三

	if(_.isString(date)){
		return date+"  "+weekday;    //2016年5月4日  星期三
	}
	return _.toString(date)+ _.toString(weekday);

}
Example #5
0
function processChangelogEntity(newState, location, mediaType, entityPayload, mtPart, deletedAtKey, entitiesKey, entityIdKey) {
    if (mediaType.includes(mtPart)) {
        if (entityPayload[deletedAtKey] != null) {
            _.unset(newState, ["_embedded", entitiesKey, _.toString(entityPayload[entityIdKey])])
        } else {
            _.set(newState, ["_embedded", entitiesKey, _.toString(entityPayload[entityIdKey]), "location"], location)
            _.set(newState, ["_embedded", entitiesKey, _.toString(entityPayload[entityIdKey]), "media-type"], mediaType)
            _.set(newState, ["_embedded", entitiesKey, _.toString(entityPayload[entityIdKey]), "payload"], entityPayload)
        }
    }
}
Example #6
0
	/**
	 * @private
	 * @param {Magister} magister
	 * @param {Object} raw
	 */
	constructor(magister, raw) {
		super(magister)

		/**
		 * @type {Number}
		 * @private
		 * @readonly
		 */
		this._type = raw.Verantwoordingtype

		/**
		 * @type {String}
		 * @readonly
		 */
		this.id = toString(raw.Id)
		/**
		 * @type {Date}
		 * @readonly
		 */
		this.begin = parseDate(raw.Start)
		/**
		 * @type {Date}
		 * @readonly
		 */
		this.end = parseDate(raw.Eind)
		/**
		 * @type {Number}
		 * @readonly
		 */
		this.schoolHour = raw.Lesuur
		/**
		 * @type {Boolean}
		 * @readonly
		 */
		this.isPermitted = raw.Geoorloofd
		/**
		 * @type {String}
		 * @readonly
		 */
		this.description = _.toString(raw.Omschrijving).trim()
		/**
		 * @type {String}
		 * @readonly
		 */
		this.code = _.toString(raw.Code)
		/**
		 * @type {Appointment}
		 * @readonly
		 */
		this.appointment = new Appointment(magister, raw.Afspraak) // REVIEW: do we want (and need) this?
	}
Example #7
0
function Filter({ filter, index, onClick, onClickOpen, schema }) {
  let value = filter.value;

  if (get(schema, [filter.attr, 'type']) === 'date') {
    const date = moment(filter.value.slice(0, -1), moment.ISO_8601);
    const format = date.valueOf() === date.startOf('day').valueOf() ?
      'MMMM Do YYYY' :'MMMM Do YYYY, h:mm:ss a' ;
    value = date.format(format);
  }

  return (
    <Flex
      onClick={(e) => {
        e.preventDefault();
        e.stopPropagation();
        onClickOpen(index);
      }}
    >
      <span>{upperFirst(filter.attr)}&nbsp;</span>
      <FormattedMessage id={`content-manager.components.FilterOptions.FILTER_TYPES.${filter.filter}`} />
      <span>&nbsp;{toString(value)}</span>
      <Separator />
      <Remove
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          onClick(index);
        }}
      />
    </Flex>
  );
}
Example #8
0
    _.each(columns, function each(columnKey) {
        var message = '',
            strVal = _.toString(model[columnKey]);

        // check nullable
        if (model.hasOwnProperty(columnKey) && schema[tableName][columnKey].hasOwnProperty('nullable')
                && schema[tableName][columnKey].nullable !== true) {
            if (validator.empty(strVal)) {
                message = i18n.t('notices.data.validation.index.valueCannotBeBlank', {tableName: tableName, columnKey: columnKey});
                validationErrors.push(new errors.ValidationError({message: message, context: tableName + '.' + columnKey}));
            }
        }

        // validate boolean columns
        if (model.hasOwnProperty(columnKey) && schema[tableName][columnKey].hasOwnProperty('type')
                && schema[tableName][columnKey].type === 'bool') {
            if (!(validator.isBoolean(strVal) || validator.empty(strVal))) {
                message = i18n.t('notices.data.validation.index.valueMustBeBoolean', {tableName: tableName, columnKey: columnKey});
                validationErrors.push(new errors.ValidationError({message: message, context: tableName + '.' + columnKey}));
            }
        }

        // TODO: check if mandatory values should be enforced
        if (model[columnKey] !== null && model[columnKey] !== undefined) {
            // check length
            if (schema[tableName][columnKey].hasOwnProperty('maxlength')) {
                if (!validator.isLength(strVal, 0, schema[tableName][columnKey].maxlength)) {
                    message = i18n.t('notices.data.validation.index.valueExceedsMaxLength',
                        {
                            tableName: tableName,
                            columnKey: columnKey,
                            maxlength: schema[tableName][columnKey].maxlength
                        });
                    validationErrors.push(new errors.ValidationError({
                        message: message,
                        context: tableName + '.' + columnKey
                    }));
                }
            }

            // check validations objects
            if (schema[tableName][columnKey].hasOwnProperty('validations')) {
                validationErrors = validationErrors.concat(validate(strVal, columnKey, schema[tableName][columnKey].validations, tableName));
            }

            // check type
            if (schema[tableName][columnKey].hasOwnProperty('type')) {
                if (schema[tableName][columnKey].type === 'integer' && !validator.isInt(strVal)) {
                    message = i18n.t('notices.data.validation.index.valueIsNotInteger', {
                        tableName: tableName,
                        columnKey: columnKey
                    });
                    validationErrors.push(new errors.ValidationError({
                        message: message,
                        context: tableName + '.' + columnKey
                    }));
                }
            }
        }
    });
Example #9
0
/**
 * Gets an `entry` tag value by `tagName`.
 *
 * @private
 * @param {Object} entry The entry to inspect.
 * @param {string} tagName The name of the tag.
 * @returns {string} Returns the tag value.
 */
function getValue(entry, tagName) {
  var parsed = entry.parsed,
      result = parsed.description,
      tag = getTag(entry, tagName);

  if (tagName == 'alias') {
    result = _.get(tag, 'name') ;

    // Doctrine can't parse alias tags containing multiple values so extract
    // them from the error message.
    var error = _.first(_.get(tag, 'errors'));
    if (error) {
      result += error.replace(/^[^']*'|'[^']*$/g, '');
    }
  }
  else if (tagName == 'type') {
    result = _.get(tag, 'type.name');
  }
  else if (tagName != 'description') {
    result = _.get(tag, 'name') || _.get(tag, 'description');
  }
  return tagName == 'example'
    ? _.toString(result)
    : util.format(result);
}
Example #10
0
function stringify(str) {
  if (str && typeof str.text === "function") str = str.text();
  if (_.isElement(str) || (_.isObject(str) && str.type === "tag")) {
    str = cheerio(str).text();
  }
  return _.toString(str);
}
Example #11
0
validate = function validate(value, key, validations) {
    var validationErrors = [];
    value = _.toString(value);

    _.each(validations, function each(validationOptions, validationName) {
        var goodResult = true;

        if (_.isBoolean(validationOptions)) {
            goodResult = validationOptions;
            validationOptions = [];
        } else if (!_.isArray(validationOptions)) {
            validationOptions = [validationOptions];
        }

        validationOptions.unshift(value);

        // equivalent of validator.isSomething(option1, option2)
        if (validator[validationName].apply(validator, validationOptions) !== goodResult) {
            validationErrors.push(new errors.ValidationError(i18n.t('notices.data.validation.index.validationFailed',
                                                                    {validationName: validationName, key: key})));
        }

        validationOptions.shift();
    }, this);

    return validationErrors;
};
Example #12
0
  getPluginHeaderTitle = () => {
    if (this.isCreating()) {
      return toString(this.props.editPage.pluginHeaderTitle);
    }

    return this.props.match.params.id;
  }
Example #13
0
/**
* Counts repeated characters in a string. When 50% or more characters are the same,
* we return false and therefore invalidate the string.
* @param {String} stringToTest The password string to check.
* @return {Boolean}
*/
function characterOccurance(stringToTest) {
    var chars = {},
        allowedOccurancy,
        valid = true;

    stringToTest = _.toString(stringToTest);
    allowedOccurancy = stringToTest.length / 2;

    // Loop through string and accumulate character counts
    _.each(stringToTest, function (char) {
        if (!chars[char]) {
            chars[char] = 1;
        } else {
            chars[char] += 1;
        }
    });

    // check if any of the accumulated chars exceed the allowed occurancy
    // of 50% of the words' length.
    _.forIn(chars, function (charCount) {
        if (charCount >= allowedOccurancy) {
            valid = false;
        }
    });

    return valid;
}
Example #14
0
        zeroFill: function(string, size) {
            if (getThis().isEmpty(string)) {
                return '';
            }

            string = _.toString(string);
            return _.padStart(string, (size - string.length), '0');
        },
Example #15
0
    add: function add(data, options) {
        var self = this,
            userData = this.filterData(data),
            roles;

        userData.password = _.toString(userData.password);

        options = this.filterOptions(options, 'add');
        options.withRelated = _.union(options.withRelated, options.include);

        // check for too many roles
        if (data.roles && data.roles.length > 1) {
            return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.onlyOneRolePerUserSupported')));
        }

        if (!validatePasswordLength(userData.password)) {
            return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.passwordDoesNotComplyLength')));
        }

        function getAuthorRole() {
            return ghostBookshelf.model('Role').findOne({name: 'Author'}, _.pick(options, 'transacting')).then(function then(authorRole) {
                return [authorRole.get('id')];
            });
        }

        roles = data.roles || getAuthorRole();
        delete data.roles;

        return generatePasswordHash(userData.password).then(function then(hash) {
            // Assign the hashed password
            userData.password = hash;
            // LookupGravatar
            return gravatar.lookup(userData);
        }).then(function then(userData) {
            // Save the user with the hashed password
            return ghostBookshelf.Model.add.call(self, userData, options);
        }).then(function then(addedUser) {
            // Assign the userData to our created user so we can pass it back
            userData = addedUser;
            // if we are given a "role" object, only pass in the role ID in place of the full object
            return Promise.resolve(roles).then(function then(roles) {
                roles = _.map(roles, function mapper(role) {
                    if (_.isString(role)) {
                        return parseInt(role, 10);
                    } else if (_.isNumber(role)) {
                        return role;
                    } else {
                        return parseInt(role.id, 10);
                    }
                });

                return addedUser.roles().attach(roles, options);
            });
        }).then(function then() {
            // find and return the added user
            return self.findOne({id: userData.id, status: 'all'}, options);
        });
    },
Example #16
0
    return _.mapValues(params, (value, key) => {
        switch (rawModel[key].dataType) {
            case String:
                return _.toString(value);

            case Number:
                return _.toNumber(value);

            case Date:
                return new Date(value);

            case Boolean:
                return Boolean(value);

            default:
                return _.toString(value);
        }
    });
 var insert10Tasks = async function(myns) {
   var expiry = new Date();
   expiry.setDate(expiry.getDate() + 10);
   var res = [];
   for (var i = 1; i <= 10; i++) {
     let taskId = slugid.nice();
     await helper.index.insertTask(myns + '.my-task' + _.toString(i) + '.new' + _.toString(i), {
       taskId:     taskId,
       rank:       i,
       data:       {hello: 'world ' + _.toString(i)},
       expires:    expiry.toJSON(),
     });
     let result = await helper.index.findTask(myns + '.my-task' + _.toString(i) + '.new' + _.toString(i));
     res.push(result);
     assert(result.taskId === taskId, 'Wrong taskId');
   }
   return res;
 };
Example #18
0
              .then(answers => {
                if (hasDatabaseConfig) {
                  answers = _.merge((_.omit(scope.database.settings, ['client'])), scope.database.options);
                }

                scope.database.settings.host = answers.host;
                scope.database.settings.srv = _.toString(answers.srv) === 'true';
                scope.database.settings.port = answers.port;
                scope.database.settings.database = answers.database;
                scope.database.settings.username = answers.username;
                scope.database.settings.password = answers.password;
                scope.database.options.authenticationDatabase = answers.authenticationDatabase;
                scope.database.options.ssl = _.toString(answers.ssl) === 'true';

                console.log();
                console.log('⏳ Testing database connection...');

                resolve();
              });
Example #19
0
 setNeed = function(need) {
     let needString = _.toString(need);
     if(needString === "hostel") {
     this.setState({need : needString});
     } else if (needString === "food bank") {
     this.setState({need : "food%20bank"})
     }   else {
     this.setState({need : "advice%20centre"})
     }
 };
Example #20
0
        Object.keys(params.Environment.Variables).forEach((key) => {
          // taken from the bash man pages
          if (!key.match(/^[A-Za-z_][a-zA-Z0-9_]*$/)) {
            const errorMessage = 'Invalid characters in environment variable';
            throw new this.serverless.classes.Error(errorMessage);
          }

          if (!_.isString(params.Environment.Variables[key])) {
            params.Environment.Variables[key] = _.toString(params.Environment.Variables[key]);
          }
        });
Example #21
0
TubeLineList.findById = function(id) {

  console.log("id-"+_.toString(id))
  var ele = _.find(new TubeLineList().list(), function(line) {
     return line.id() == id
  })

  if(_.isEmpty(ele))
    return new TubeLine("error","error no line found for ".concat(id),"")
    else
    return ele
};
Example #22
0
/**
 * ## Get Error Template Hierarchy
 *
 * Fetch the ordered list of templates that can be used to render this error statusCode.
 *
 * The default is the
 *
 * @param {integer} statusCode
 * @returns {String[]}
 */
function getErrorTemplateHierarchy(statusCode) {
    var errorCode = _.toString(statusCode),
        templateList = ['error'];

    // Add error class template: E.g. error-4xx.hbs or error-5xx.hbs
    templateList.unshift('error-' + errorCode[0] + 'xx');

    // Add statusCode specific template: E.g. error-404.hbs
    templateList.unshift('error-' + errorCode);

    return templateList;
}
Example #23
0
        const onSlicerFailure = async (err) => {
            cleanup();
            logger.warn('slicer failed', _.toString(err));

            logger.debug(`draining the remaining ${this.pendingSlicerCount} from the slicer`);
            await this._drainPendingSlices(false);

            // before removing listeners make sure we've received all of the events
            await Promise.delay(100);

            events.emit('slicers:finished', err);
        };
Example #24
0
				_.each(filters, (filter) => {
					const {path, value, date} = JSON.parse(filter);

					if (!_.isEmpty(date)) {
						includesDate = true;
						// If Date comparison still pending to be found.
						// If the entry found the filter criteria, then it will select the entry as valid
						if (!matchDate) {
							const year = date[0];
							const month = date[1];

							matchDate = _.toString(_.get(entry, year.path)) === _.toString(year.value) &&
								_.toString(_.get(entry, month.path)) === _.toString(month.value);

							if (matchDate) {
								matchEntry = true;
							}

						}

					} else {

						// Check if Entry does match with the Standard filter criteria
						if (!matchEntry) {
							if (_.toString(_.get(entry, path)) === _.toString(value)) {
								matchEntry = true;
							}
						}

					}
				});
Example #25
0
  render() {
    const { editPage } = this.props;

    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <BackHeader onClick={() => this.props.history.goBack()} />
          <div className={cn('container-fluid', styles.containerFluid)}>
            <PluginHeader
              actions={this.pluginHeaderActions()}
              title={{ id: toString(editPage.pluginHeaderTitle) }}
            />
            <div className="row">
              <div className={this.isRelationComponentNull() ? 'col-lg-12' : 'col-lg-9'}>
                <div className={styles.main_wrapper}>
                  <Edit
                    attributes={this.getModelAttributes()}
                    didCheckErrors={editPage.didCheckErrors}
                    formValidations={editPage.formValidations}
                    formErrors={editPage.formErrors}
                    layout={this.getLayout()}
                    modelName={this.getModelName()}
                    onBlur={this.handleBlur}
                    onChange={this.handleChange}
                    record={editPage.record}
                    resetProps={editPage.resetProps}
                    schema={this.getSchema()}
                  />
                </div>
              </div>
              {!this.isRelationComponentNull() && (
                <div className={cn('col-lg-3')}>
                  <div className={styles.sub_wrapper}>
                    {!this.isRelationComponentNull() && (
                      <EditRelations
                        currentModelName={this.getModelName()}
                        location={this.props.location}
                        changeData={this.props.changeData}
                        record={editPage.record}
                        schema={this.getSchema()}
                      />
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </form>
      </div>
    );
  }
Example #26
0
      .map(function(tag) {
        var defaultValue = tag['default'],
            desc = util.format(tag.description),
            name = _.toString(tag.name),
            type = getParamType(tag.type);

        if (defaultValue != null) {
          name += '=' + defaultValue;
        }
        if (_.get(tag, 'type.type') == 'OptionalType') {
          name = '[' + name + ']';
        }
        return [type, name,  desc];
      })
Example #27
0
  generateEntry: function (entry, transLocaleId) {
    let srcTerm =
      this.getTermByLocale(entry.glossaryTerms, entry.srcLang)
    srcTerm.reference = entry.sourceReference
    const srcDate = toString(srcTerm.lastModifiedDate)
    if (!isEmpty(srcDate)) {
      srcTerm.lastModifiedDate =
        DateHelpers.shortDate(DateHelpers.getDate(srcDate))
    }

    let transTerm
    if (transLocaleId) {
      transTerm = this.getTermByLocale(entry.glossaryTerms, transLocaleId)
      if (transTerm) {
        const transDate = toString(transTerm.lastModifiedDate)
        if (!isEmpty(transDate)) {
          transTerm.lastModifiedDate =
            DateHelpers.shortDate(DateHelpers.getDate(transDate))
        }
        if (isEmpty(transTerm.comment)) {
          transTerm.comment = ''
        }
      } else {
        transTerm = this.generateEmptyTerm(transLocaleId)
      }
    }

    return {
      id: entry.id,
      pos: defined(entry.pos, ''),
      description: defined(entry.description, ''),
      termsCount: entry.termsCount > 0 ? entry.termsCount - 1 : 0,
      srcTerm: srcTerm,
      transTerm: transTerm,
      status: this.getDefaultEntryStatus()
    }
  },
Example #28
0
 this.props.records.map((record, key) => (
   <TableRow
     enableBulkActions={this.props.enableBulkActions}
     onChange={this.props.onClickSelect}
     key={key}
     destination={`${this.props.route.path.replace(':slug', this.props.routeParams.slug)}/${record[this.props.primaryKey]}`}
     headers={this.props.headers}
     record={record}
     history={this.props.history}
     primaryKey={this.props.primaryKey}
     onDelete={this.props.handleDelete}
     redirectUrl={this.props.redirectUrl}
     value={this.props.entriesToDelete.indexOf(toString(record.id)) !== -1}
   />
 ));
Example #29
0
module.exports = function (user) {
  let salt = keygen._({ length: 126 }),
      key = salt + signature;

  let grant = new this({
    salt,
    token: jwt.encode({
      type: user.constructor.modelName,
      user: toString(user._id)
    }, key),
    expires:        moment().add(expiration, 'seconds').toDate(),
    grantedToModel: user.constructor.modelName
  });

  return grant.save();
};
Example #30
0
 (message): IUserUpdateEnvelope => {
   return {
     message,
     // TODO: extract to attributes-mapper-util
     mailchimpNewMember: {
       email_type: "html",
       merge_fields: this.userMappingAgent.getMergeFields(message),
       interests: this.interestsMappingAgent.getInterestsForSegments(
         _.get(message, "segments", []).map(s => s.id)
       ),
       email_address: _.toString(message.user.email),
       status_if_new: "subscribed"
     },
     staticSegmentsToAdd: [],
     staticSegmentsToRemove: []
   };
 }