예제 #1
0
bool GenericType::toBool() const{
  if (isBool()) {
    return static_cast<const BoolType*>(get())->d_;
  } else if (isInt()) {
    return bool(toInt());
  } else {
    casadi_assert_message(isBool(),"type mismatch");
    return false;
  }
}
예제 #2
0
void CheckBool::checkComparisonOfBoolWithInt()
{
    if (!_settings->isEnabled("warning") || !_tokenizer->isCPP())
        return;

    const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase();
    const std::size_t functions = symbolDatabase->functionScopes.size();
    for (std::size_t i = 0; i < functions; ++i) {
        const Scope * scope = symbolDatabase->functionScopes[i];
        for (const Token* tok = scope->classStart->next(); tok != scope->classEnd; tok = tok->next()) {
            const Token* const left = tok->astOperand1();
            const Token* const right = tok->astOperand2();
            if (left && right && tok->isComparisonOp()) {
                if ((left->varId() && right->isNumber()) || (left->isNumber() && right->varId())) { // Comparing variable with number
                    const Token* varTok = left;
                    const Token* numTok = right;
                    if (left->isNumber() && right->varId()) // num with var
                        std::swap(varTok, numTok);
                    if (isBool(varTok->variable()) && // Variable has to be a boolean
                        ((tok->str() != "==" && tok->str() != "!=") ||
                         (MathLib::toLongNumber(numTok->str()) != 0 && MathLib::toLongNumber(numTok->str()) != 1))) { // == 0 and != 0 are allowed, for C also == 1 and != 1
                        comparisonOfBoolWithIntError(varTok, numTok->str(), tok->str() == "==" || tok->str() == "!=");
                    }
                } else if (left->isBoolean() && right->varId()) { // Comparing boolean constant with variable
                    if (isNonBoolStdType(right->variable())) { // Variable has to be of non-boolean standard type
                        comparisonOfBoolWithIntError(right, left->str(), false);
                    } else if (tok->str() != "==" && tok->str() != "!=") {
                        comparisonOfBoolWithInvalidComparator(right, left->str());
                    }
                } else if (left->varId() && right->isBoolean()) { // Comparing variable with boolean constant
                    if (isNonBoolStdType(left->variable())) { // Variable has to be of non-boolean standard type
                        comparisonOfBoolWithIntError(left, right->str(), false);
                    } else if (tok->str() != "==" && tok->str() != "!=") {
                        comparisonOfBoolWithInvalidComparator(right, left->str());
                    }
                } else if (left->isNumber() && right->isBoolean()) { // number constant with boolean constant
                    comparisonOfBoolWithIntError(left, right->str(), false);
                } else if (left->isBoolean() && right->isNumber()) { // number constant with boolean constant
                    comparisonOfBoolWithIntError(left, left->str(), false);
                } else if (left->varId() && right->varId()) { // Comparing two variables, one of them boolean, one of them integer
                    const Variable* var1 = right->variable();
                    const Variable* var2 = left->variable();
                    if (isBool(var1) && isNonBoolStdType(var2)) // Comparing boolean with non-bool standard type
                        comparisonOfBoolWithIntError(left, var1->name(), false);
                    else if (isNonBoolStdType(var1) && isBool(var2)) // Comparing non-bool standard type with boolean
                        comparisonOfBoolWithIntError(left, var2->name(), false);
                }
            }
        }
    }
}
예제 #3
0
char* handle_expr_single(char* op, ast* a)
{
	if (strcmp(op, "NOT") == 0)
	{
		if (!isBool(a))
		{
			char msg[100];
			strcpy(msg, "expected BOOL but got ");
			strcat(msg, a->type);
			error(msg, a);
			return "TYPE_ERROR";
		}
		return "BOOL";
	}
	else
	{
		if (!isInt(a) && !isReal(a))
		{
			char msg[100];
			strcpy(msg, "expected INTEGER or REAL but got ");
			strcat(msg, a->type);
			error(msg, a);
			return "TYPE_ERROR";
		}
		return a->type;
	}
}
예제 #4
0
// Metoda rzutuje na obiekt Boolowski
Json::Boolean Json::get(Boolean*) const
{
    if (!isBool())
        throw std::domain_error("type is not boolean");

    return value.boolean;
}
예제 #5
0
void JsonWrapper::get(const char* name, bool dflt, bool& param) const {
  auto val = m_config.get(name, dflt);

  // Do some simple type conversions that folly used to do
  if (val.isBool()) {
    param = val.asBool();
    return;
  } else if (val.isInt()) {
    auto valInt = val.asInt();
    if (valInt == 0 || valInt == 1) {
      param = (val.asInt() != 0);
      return;
    }
  } else if (val.isString()) {
    auto str = val.asString();
    std::transform(str.begin(), str.end(), str.begin(),
                   [](auto c) { return ::tolower(c); });
    if (str == "0" || str == "false" || str == "off" || str == "no") {
      param = false;
      return;
    } else if (str == "1" || str == "true" || str == "on" || str == "yes") {
      param = true;
      return;
    }
  }
  throw std::runtime_error("Cannot convert JSON value to bool: " +
                           val.asString());
}
ParameterWidget::ParameterWidget(Metabot::Component *instance_,
                                 std::string name_, QWidget *parent) :
    instance(instance_),
    name(name_),
    QWidget(parent),
    label(NULL), line(NULL), checkbox(NULL)
{
    auto param = instance->module->getParameter(name);
    std::string value = instance->get(param.name);

    label = new QLabel;
    label->setText(QString::fromStdString(param.description));

    this->setLayout(new QVBoxLayout());
    this->layout()->addWidget(label);

    if (param.isBool()) {
        checkbox = new QCheckBox;
        checkbox->setChecked(value=="true");
        this->layout()->addWidget(checkbox);
    } else {
        line = new QLineEdit;
        line->setText(QString::fromStdString(value));
        this->layout()->addWidget(line);
    }

    this->layout()->setSpacing(0);
    this->layout()->setMargin(0);
    this->layout()->update();
    this->adjustSize();
    this->update();
    this->show();
}
예제 #7
0
파일: JSON.cpp 프로젝트: eranif/codelite
bool JSONItem::toBool(bool defaultValue) const
{
    if(!_json) { return defaultValue; }

    if(!isBool()) { return defaultValue; }

    return _json->type == cJSON_True;
}
예제 #8
0
void CheckBool::checkComparisonOfBoolWithBool()
{
    // FIXME: This checking is "experimental" because of the false positives
    //        when self checking lib/tokenize.cpp (#2617)
    if (!_settings->experimental)
        return;

    if (!_settings->isEnabled("style"))
        return;

    if (!_tokenizer->isCPP())
        return;

    const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase();

    const std::size_t functions = symbolDatabase->functionScopes.size();
    for (std::size_t i = 0; i < functions; ++i) {
        const Scope * scope = symbolDatabase->functionScopes[i];
        for (const Token* tok = scope->classStart->next(); tok != scope->classEnd; tok = tok->next()) {
            if (tok->tokType() != Token::eComparisonOp || tok->str() == "==" || tok->str() == "!=")
                continue;
            bool firstTokenBool = false;

            const Token *firstToken = tok->previous();
            if (firstToken->varId()) {
                if (isBool(firstToken->variable())) {
                    firstTokenBool = true;
                }
            }
            if (!firstTokenBool)
                continue;

            bool secondTokenBool = false;
            const Token *secondToken = tok->next();
            if (secondToken->varId()) {
                if (isBool(secondToken->variable())) {
                    secondTokenBool = true;
                }
            }
            if (secondTokenBool) {
                comparisonOfBoolWithBoolError(firstToken->next(), secondToken->str());
            }
        }
    }
}
예제 #9
0
void VariantBase::xmlWrite(QDomDocument& doc, QDomNode& parent) const
{
  QString buf;
  if (isBool())
    buf.setNum(int(boolval));
  else
    buf.setNum(int(Error(*this)));
  xmlWriteText(doc, parent, buf);
}
예제 #10
0
/**
* @brief Converts the given LLVM boolean or integer constant @a cInt into
*        an expression in BIR.
*
* @par Preconditions
*  - @a cInt is non-null
*/
ShPtr<Expression> LLVMConstantConverter::convertToExpression(
		const llvm::ConstantInt *cInt) {
	PRECONDITION_NON_NULL(cInt);

	if (isBool(cInt)) {
		return ConstBool::create(cInt->isOne());
	}

	return ConstInt::create(cInt->getValue());
}
예제 #11
0
파일: xbnode.cpp 프로젝트: manumehta123/xbn
double	xbnode::getNumeric()
{
	if( isBool() )
		return getBool()? 1:0;
	if( isNumeric() )
		return stringToZahl( getText() );

	raiseError( "getNumeric() cant convert", __FILE__,__LINE__);
	return 0;
}
예제 #12
0
파일: parse.cpp 프로젝트: facebook/watchman
static void parse_benchmark(w_query* res, const json_ref& query) {
  // Preserve behavior by supporting a boolean value. Also support int values.
  auto bench = query.get_default("bench");
  if (bench) {
    if (bench.isBool()) {
      res->bench_iterations = 100;
    } else {
      res->bench_iterations = json_integer_value(bench);
    }
  }
}
예제 #13
0
파일: xbnode.cpp 프로젝트: manumehta123/xbn
bool	xbnode::getBool()
{
	if( isBool() )
		return (this->getText()=="true");
	if( isNumeric() )
		return getNumeric()!=0;
	if( isText() )
		return !getText().empty();

	raiseError( "getBool() cant convert", __FILE__,__LINE__);
	return false;
}
예제 #14
0
void MessagePackAdaptorTests::testBoolean() {
    // True
    {
        pack(Datum(true));
        auto o = unpack();
        CPPUNIT_ASSERT_EQUAL( msgpack::type::BOOLEAN, o.type );
        auto d = o.as<Datum>();
        CPPUNIT_ASSERT( d.isBool() );
        CPPUNIT_ASSERT_EQUAL( true, d.getBool() );
    }

    // False
    {
        pack(Datum(false));
        auto o = unpack();
        CPPUNIT_ASSERT_EQUAL( msgpack::type::BOOLEAN, o.type );
        auto d = o.as<Datum>();
        CPPUNIT_ASSERT( d.isBool() );
        CPPUNIT_ASSERT_EQUAL( false, d.getBool() );
    }
}
예제 #15
0
int GenericType::toInt() const{
  if(isDouble()){
    double v = toDouble();
    casadi_assert_message(v == std::floor(v),"The value is not an integer");
    return int(v);
  } else if (isBool()) {
    return int(toBool());
  } else {
    casadi_assert_message(isInt(),"type mismatch");
    return static_cast<const IntType*>(get())->d_;
  }
}
예제 #16
0
파일: cfg.cpp 프로젝트: facebook/watchman
bool Configuration::getBool(const char* name, bool defval) const {
  auto val = get(name);

  if (val) {
    if (!val.isBool()) {
      throw std::runtime_error(watchman::to<std::string>(
          "Expected config value ", name, " to be a boolean"));
    }
    return val.asBool();
  }

  return defval;
}
예제 #17
0
파일: cfg.cpp 프로젝트: facebook/watchman
bool cfg_get_bool(const char* name, bool defval) {
  auto val = cfg_get_json(name);

  if (val) {
    if (!val.isBool()) {
      throw std::runtime_error(watchman::to<std::string>(
          "Expected config value ", name, " to be a boolean"));
    }
    return val.asBool();
  }

  return defval;
}
예제 #18
0
	Optional<bool> TOMLValue::getOpt<bool>() const
	{
		if (!isBool()) {
			return none;
		}

		if (auto p = m_detail->ptr->as<bool>())
		{
			return p->get();
		}

		return none;
	}
예제 #19
0
bool GenericType::can_cast_to(opt_type other) const {
  switch (other) {
      case OT_BOOLEAN:
        return isBool() || isInt() || isDouble();
      case OT_BOOLVECTOR:
        return isIntVector() || isDoubleVector();
      case OT_INTEGER: case OT_REAL:
        return isInt() || isDouble();
      case OT_INTEGERVECTOR: case OT_REALVECTOR:
        return isDoubleVector() || isIntVector();
      default:
        return type_ == other;
  }
}
예제 #20
0
파일: util.c 프로젝트: suborb/reelvdr
bool Util::isBool(const char *string, int &flag)
{
    bool ok = true;
    bool boolVal;

    if (isBool(string, boolVal))
    {
        if (boolVal)
            flag = true;
        else
            flag = false;
    }

    return (ok);
}
예제 #21
0
bool JsonObjectQt::GetNamedBool(const std::string& name, bool bDefaultValue)
{
  QJsonObject jo = this->impl_.toObject();

  if (jo.contains(name.c_str()) && !jo[name.c_str()].isNull()) {
    auto obj = jo[name.c_str()];

    if (obj.isBool()) {
      return obj.toBool();
    }

    throw exceptions::RMSInvalidArgumentException(
            "JsonObjectQt::GetNamedBool: convertion error");
  }
  return bDefaultValue;
}
bool QTrackerDirectSyncResult::next()
{
    if (!cursor) {
        // The cursor may have been unreferenced because the connection was deleted
        // and now the user is calling next(), so set the row here
        updatePos(QSparql::AfterLastRow);
        return false;
    }

    GError * error = 0;
    const gboolean active = tracker_sparql_cursor_next(cursor, 0, &error);

    // if this is an ask query, get the result
    if (isBool() && active && tracker_sparql_cursor_get_value_type(cursor, 0) == TRACKER_SPARQL_VALUE_TYPE_BOOLEAN) {
        const gboolean value = tracker_sparql_cursor_get_boolean(cursor, 0);
        setBoolValue(value != FALSE);
    }

    if (error) {
        setLastError(QSparqlError(QString::fromUtf8(error->message),
                       errorCodeToType(error->code),
                       error->code));
        g_error_free(error);
        qWarning() << "QTrackerDirectSyncResult:" << lastError() << query();
        g_object_unref(cursor);
        cursor = 0;
        return false;
    }

    if (!active) {
        g_object_unref(cursor);
        cursor = 0;
        updatePos(QSparql::AfterLastRow);
        return false;
    }
    const int oldPos = pos();
    if (oldPos == QSparql::BeforeFirstRow)
        updatePos(0);
    else
        updatePos(oldPos + 1);
    return true;
}
int Inspect(char* str, int len, Object* object){
  if( isNil(object) )
    return InspectNil(str, len, object);

  if( isConsCell(object) )
    return InspectConsCell(str, len, object);

  if( isSymbol(object) )
    return InspectSymbol(str, len, object);

  if( isInteger(object) )
    return InspectInteger(str, len, object);

  if( isLambda(object) )
    return InspectLambda(str, len, object);

  if( isPrimitiveFunc(object) )
    return InspectPrimitiveFunc(str, len, object);

  if( isContinuation(object) )
    return InspectContinuation(str, len, object);

  if( isEnvironment(object) )
    return InspectEnvironment(str, len, object);

  if( isBool(object) )
    return InspectBool(str, len, object);

  if( isSpecialForm(object) )
    return InspectSpecialForm(str, len, object);

  if( isCondition(object) )
    return InspectCondition(str, len, object);

  if( isCharacter(object) )
    return InspectCharacter(str, len, object);

  else
    return InspectUnknown(str, len, object);
}
int Describe(char* str, int len, Object* object){
  if( isNil(object) )
    return DescribeNil(str, len, object);

  if( isConsCell(object) )
    return DescribeConsCell(str, len, object);

  if( isSymbol(object) )
    return DescribeSymbol(str, len, object);

  if( isInteger(object) )
    return DescribeInteger(str, len, object);

  if( isLambda(object) )
    return DescribeLambda(str, len, object);

  if( isPrimitiveFunc(object) )
    return DescribePrimitiveFunc(str, len, object);

  if( isContinuation(object) )
    return DescribeContinuation(str, len, object);

  if( isEnvironment(object) )
    return DescribeEnvironment(str, len, object);

  if( isBool(object) )
    return DescribeBool(str, len, object);

  if( isSpecialForm(object) )
    return DescribeSpecialForm(str, len, object);

  if( isCondition(object) )
    return DescribeCondition(str, len, object);

  if( isCharacter(object) )
    return DescribeCharacter(str, len, object);

  else
    return DescribeUnknown(str, len, object);
}
예제 #25
0
//=================================================================================
ModifyObjectCmd::ModifyObjectCmd(QJsonObject oldData, QJsonObject newData, ObjectItem* item, Modifications mod, QUndoCommand* parent)
    : QUndoCommand(parent),
      m_oldData(oldData),
      m_newData(oldData), // Set newData to oldData for the time being, update it later with the newData
      m_item(item),
      m_mod(mod)
{
    // Overwrite the old data with the new data if available
    for (auto it = newData.constBegin(); it != newData.constEnd(); ++it)
    {
        if (it->isDouble()) m_newData[it.key()] = it->toDouble(); // This includes integers
        else if (it->isObject()) m_newData[it.key()] = it->toObject();
        else if (it->isArray()) m_newData[it.key()] = it->toArray();
        else if (it->isString()) m_newData[it.key()] = it->toString();
        else if (it->isBool()) m_newData[it.key()] = it->toBool();
    }

    // Set the type of modification for the data
    m_oldData["modifications"] = static_cast<int>(mod);
    m_newData["modifications"] = static_cast<int>(mod);

    setText(QObject::tr(qPrintable("Modify " + newData["type"].toString() + " " + newData["name"].toString())));
}
예제 #26
0
// here we use DataTime instead of QT's built-in time conversion
// since the latter does not properly handle fractions of seconds
// in the ISO8601 specification.
QString Soprano::LiteralValue::toString() const
{
    if ( d ) {
        if ( !d->stringCacheValid ) {
            if( isInt() )
                d->stringCache = QString::number( toInt() );
            else if( isInt64() )
                d->stringCache = QString::number( toInt64() );
            else if( isUnsignedInt() )
                d->stringCache = QString::number( toUnsignedInt() );
            else if( isUnsignedInt64() )
                d->stringCache = QString::number( toUnsignedInt64() );
            else if( isBool() )
                d->stringCache = ( toBool() ? QString("true") : QString("false" ) );
            else if( isDouble() ) // FIXME: decide on a proper double encoding or check if there is one in xml schema
                d->stringCache = QString::number( toDouble(), 'e', 10 );
            else if( isDate() )
                d->stringCache = DateTime::toString( toDate() );
            else if( isTime() )
                d->stringCache = DateTime::toString( toTime() );
            else if( isDateTime() )
                d->stringCache = DateTime::toString( toDateTime() );
            else if ( isByteArray() )
                d->stringCache = QString::fromAscii( toByteArray().toBase64() );
            else
                d->stringCache = d->value.toString();

            d->stringCacheValid = true;
        }

        return d->stringCache;
    }
    else {
        return QString();
    }
}
예제 #27
0
bool CppVariant::toBoolean() const
{
    WEBKIT_ASSERT(isBool());
    return value.boolValue;
}
bool GenericObject::isObject() {
	return !isNumber() && !isBool() && !isString();
}
예제 #29
0
파일: parser.cpp 프로젝트: fly2mars/suAgent
bool Parser::getBoolToken() {
  string token;
  if (!(isBool(token = getToken()))) throw UnexpectedInputException(filename, line_num, line_pos, token, "type bool");
  return (token == "1" || token == "true" || token == "TRUE" || token == "t" || token == "T" || token == "yes" || token == "YES" || token == "y" || token == "Y");
}
예제 #30
0
std::shared_ptr<Operand> PredicateParser::createPrimitive(const std::string& fullExpression, size_t from, size_t to)
{
    from = skipSpace(fullExpression, from, to);
    while(to > from && std::isspace(fullExpression.at(to - 1)))
    {
        --to;
    }

    if(from >= to)
    {
        return nullptr;
    }

    char c = fullExpression.at(from);
    switch(c)
    {
    case '"':
    {
        auto last = skipString(fullExpression, from + 1, to);
        auto str = fullExpression.substr(from + 1, last - from - 1);
        if(last == to)
        {
            throw std::logic_error(str + " not a string");
        }

        return std::make_shared<StringOperand>(str);
    }
    case '^':
    case '.':
    {
        Compiler subCompiler;
        auto subExpression = subCompiler.compile(fullExpression, from, to);
        return std::make_shared<LocationOperand>(subExpression);
    }
    case '{':
    case '[':
    {
        std::stack<char> unmatched;
        unmatched.push(c);
        auto last = skip2MatchParenthesis(unmatched, fullExpression, from + 1, to);
        auto str = fullExpression.substr(from, last - from + 1);
        if(last == to)
        {
            throw std::logic_error(str + " not a json");
        }

        json value = json::parse(str);
        return std::make_shared<JsonOperand>(value);
    }
    case '/':
    {
        auto toPos = skip2(fullExpression, from + 1, '/', to);
        auto regex = fullExpression.substr(from + 1, toPos - from - 1);
        return std::make_shared<RegexOperand>(regex);
    }
    case '$':
    {
        auto variableName = fullExpression.substr(from + 1, to - from - 1);
        return std::make_shared<VariableOperand>(variableName);
    }
    default:
        if(isBool(fullExpression, from, to) && '0' != fullExpression.at(from) && '1' != fullExpression.at(from))
        {
            bool v = convert2Bool(fullExpression, from, to);
            return std::make_shared<BoolOperand>(v);
        }
        else if(isInt(fullExpression, from, to))
        {
            int v = convert2Int(fullExpression, from, to);
            return std::make_shared<IntOperand>(v);
        }
        else if(isReal(fullExpression, from, to))
        {
            double v = convert2Real(fullExpression, from, to);
            return std::make_shared<RealOperand>(v);
        }
        else
        {
            throw std::logic_error(fullExpression.substr(from, to - from) + " can't be interpreted as an operand");
        }
    }
}