Пример #1
0
Файл: blob.c Проект: gvx/deja
Error setbyte_blob_(Stack *S, Stack *scope_arr)
{
	require(3);
	V blob = popS();
	V index = popS();
	V value = popS();
	Error e = Nothing;
	if (getType(blob) != T_BLOB || getType(index) != T_NUM || getType(value) != T_NUM)
	{
		e = TypeError;
		goto cleanup;
	}
	int num = toNumber(value);
	if (num < 0 || num > 255)
	{
		set_error_msg("Value not in range [0,255]");
		e = ValueError;
		goto cleanup;
	}
	int byte = setbyte_blob(blob, toNumber(index), num);
	if (byte < 0)
	{
		set_error_msg("Index out of range");
		e = ValueError;
		goto cleanup;
	}
	cleanup:
	clear_ref(blob);
	clear_ref(index);
	clear_ref(value);
	return e;
}
Пример #2
0
void tst_QSet::stlIterator()
{
    QSet<QString> set1;
    for (int i = 0; i < 25000; ++i)
        set1.insert(QString::number(i));

    {
        int sum = 0;
        QSet<QString>::const_iterator i = set1.begin();
        while (i != set1.end()) {
            sum += toNumber(*i);
            ++i;
        }
        QVERIFY(sum == 24999 * 25000 / 2);
    }

    {
        int sum = 0;
        QSet<QString>::const_iterator i = set1.end();
        while (i != set1.begin()) {
            --i;
            sum += toNumber(*i);
        }
        QVERIFY(sum == 24999 * 25000 / 2);
    }
}
Пример #3
0
void tst_QSet::stlMutableIterator()
{
    QSet<QString> set1;
    for (int i = 0; i < 25000; ++i)
        set1.insert(QString::number(i));

    {
        int sum = 0;
        QSet<QString>::iterator i = set1.begin();
        while (i != set1.end()) {
            sum += toNumber(*i);
            ++i;
        }
        QVERIFY(sum == 24999 * 25000 / 2);
    }

    {
        int sum = 0;
        QSet<QString>::iterator i = set1.end();
        while (i != set1.begin()) {
            --i;
            sum += toNumber(*i);
        }
        QVERIFY(sum == 24999 * 25000 / 2);
    }

    {
        QSet<QString> set2 = set1;
        QSet<QString> set3 = set2;

        QSet<QString>::iterator i = set2.begin();
        QSet<QString>::iterator j = set3.begin();

        while (i != set2.end()) {
            i = set2.erase(i);
        }
        QVERIFY(set2.isEmpty());
        QVERIFY(!set3.isEmpty());

        j = set3.end();
        while (j != set3.begin()) {
            j--;
            if (j + 1 != set3.end())
                set3.erase(j + 1);
        }
        if (set3.begin() != set3.end())
            set3.erase(set3.begin());

        QVERIFY(set2.isEmpty());
        QVERIFY(set3.isEmpty());

#if QT_VERSION >= 0x050000
        i = set2.insert("foo");
#else
        QSet<QString>::const_iterator k = set2.insert("foo");
        i = reinterpret_cast<QSet<QString>::iterator &>(k);
#endif
        QVERIFY(*i == "foo");
    }
}
Пример #4
0
    Result<Tileset> operator()(const V& value) const {
        Tileset result;

        auto tiles = objectMember(value, "tiles");
        if (!tiles) {
            return Error { "source must have tiles" };
        }

        if (!isArray(*tiles)) {
            return Error { "source tiles must be an array" };
        }

        for (std::size_t i = 0; i < arrayLength(*tiles); i++) {
            optional<std::string> urlTemplate = toString(arrayMember(*tiles, i));
            if (!urlTemplate) {
                return Error { "source tiles member must be a string" };
            }
            result.tiles.push_back(std::move(*urlTemplate));
        }

        auto schemeValue = objectMember(value, "scheme");
        if (schemeValue) {
            optional<std::string> scheme = toString(*schemeValue);
            if (scheme && *scheme == "tms") {
                result.scheme = Tileset::Scheme::TMS;
            }
        }

        auto minzoomValue = objectMember(value, "minzoom");
        if (minzoomValue) {
            optional<float> minzoom = toNumber(*minzoomValue);
            if (!minzoom || *minzoom < 0 || *minzoom > std::numeric_limits<uint8_t>::max()) {
                return Error { "invalid minzoom" };
            }
            result.zoomRange.min = *minzoom;
        }

        auto maxzoomValue = objectMember(value, "maxzoom");
        if (maxzoomValue) {
            optional<float> maxzoom = toNumber(*maxzoomValue);
            if (!maxzoom || *maxzoom < 0 || *maxzoom > std::numeric_limits<uint8_t>::max()) {
                return Error { "invalid maxzoom" };
            }
            result.zoomRange.max = *maxzoom;
        }

        auto attributionValue = objectMember(value, "attribution");
        if (attributionValue) {
            optional<std::string> attribution = toString(*attributionValue);
            if (!attribution) {
                return Error { "source attribution must be a string" };
            }
            result.attribution = std::move(*attribution);
        }

        return result;
    }
Пример #5
0
void TestTools::set_stlMutableIterator()
{
    Set<QString> set1;
    for (int i = 0; i < 25000; ++i)
        set1.insert(QString::number(i));

    {
        int sum = 0;
        Set<QString>::iterator i = set1.begin();
        while (i != set1.end()) {
            sum += toNumber(*i);
            ++i;
        }
        QVERIFY(sum == 24999 * 25000 / 2);
    }

    {
        int sum = 0;
        Set<QString>::iterator i = set1.end();
        while (i != set1.begin()) {
            --i;
            sum += toNumber(*i);
        }
        QVERIFY(sum == 24999 * 25000 / 2);
    }

    {
        Set<QString> set2 = set1;
        Set<QString> set3 = set2;

        Set<QString>::iterator i = set2.begin();
        Set<QString>::iterator j = set3.begin();

        while (i != set2.end()) {
            i = set2.erase(i);
        }
        QVERIFY(set2.isEmpty());
        QVERIFY(!set3.isEmpty());

        j = set3.end();
        while (j != set3.begin()) {
            j--;
            if (j + 1 != set3.end())
                set3.erase(j + 1);
        }
        if (set3.begin() != set3.end())
            set3.erase(set3.begin());

        QVERIFY(set2.isEmpty());
        QVERIFY(set3.isEmpty());

        i = set2.insert("foo").first;
        QCOMPARE(*i, QLatin1String("foo"));
    }
}
Пример #6
0
    Result<Function<T>> operator()(const V& value) const {
        if (!isObject(value)) {
            return Error { "function must be an object" };
        }

        auto stopsValue = objectMember(value, "stops");
        if (!stopsValue) {
            return Error { "function value must specify stops" };
        }

        if (!isArray(*stopsValue)) {
            return Error { "function stops must be an array" };
        }

        if (arrayLength(*stopsValue) == 0) {
            return Error { "function must have at least one stop" };
        }

        std::vector<std::pair<float, T>> stops;
        for (std::size_t i = 0; i < arrayLength(*stopsValue); ++i) {
            const auto& stopValue = arrayMember(*stopsValue, i);

            if (!isArray(stopValue)) {
                return Error { "function stop must be an array" };
            }

            if (arrayLength(stopValue) != 2) {
                return Error { "function stop must have two elements" };
            }

            optional<float> z = toNumber(arrayMember(stopValue, 0));
            if (!z) {
                return Error { "function stop zoom level must be a number" };
            }

            Result<T> v = convert<T>(arrayMember(stopValue, 1));
            if (!v) {
                return v.error();
            }

            stops.emplace_back(*z, *v);
        }

        auto baseValue = objectMember(value, "base");
        if (!baseValue) {
            return Function<T>(stops, 1.0f);
        }

        optional<float> base = toNumber(*baseValue);
        if (!base) {
            return Error { "function base must be a number"};
        }

        return Function<T>(stops, *base);
    }
int stringcmp(char *str1, char *str2, int i, int j)/*comparing the dates of both transactions*/
{

	int n1, n2;
	n1 = toNumber(str1, i, j);
	n2 = toNumber(str2, i, j);
	if (n2 == n1)
		return 1;
	else
		return 0;
}
Пример #8
0
void FlowValue::dump(bool x) const
{
	fflush(stderr);
	switch (type_)
	{
		case FlowValue::VOID:
			printf("void");
			break;
		case FlowValue::BOOLEAN:
			printf(toBool() ? "true" : "false");
			break;
		case FlowValue::NUMBER:
			printf("%lld", toNumber());
			break;
		case FlowValue::REGEXP:
			printf("/%s/", toRegExp().c_str());
			break;
		case FlowValue::IP:
			printf("ip(%s)", toIPAddress().str().c_str());
			break;
		case FlowValue::FUNCTION:
			printf("fnref(0x%p)", reinterpret_cast<void*>(toFunction()));
			break;
		case FlowValue::STRING:
			printf("'%s'", toString());
			break;
		case FlowValue::BUFFER: {
			long long length = toNumber();
			const char *p = toString();
			std::string data(p, p + length);
			printf("'%s'", data.c_str());
			break;
		}
		case FlowValue::ARRAY: {
			const FlowArray& p = toArray();
			printf("[");
			for (size_t k = 0, ke = p.size(); k != ke; ++k) {
				if (k) printf(", ");
				p[k].dump(false);
			}
			printf("]");

			break;
		}
		default:
			break;
	}

	if (x)
		printf("\n");
}
Пример #9
0
phy::vector_t const minimizexx(phy::vector_t x, boost::function< double (phy::vector_t const &) > const & objFct, std::string const & statusFileName, unsigned maxFEval, unsigned maxIter)
{
  glbObjFct = & objFct;
  glbInitParams = & x;

  FDNLF1 nlp(x.size(), fctWrapper, initWrapper);

  OptQNewton objfcn(&nlp);
  //OptFDNewton objfcn(&nlp);
  //OptCG objfcn(&nlp);

  objfcn.setSearchStrategy(LineSearch); //alt: TrustRegion
  // set stopping criteria: see http://csmr.ca.sandia.gov/opt%2B%2B/opt++2.4_doc/html/ControlParameters.html
  objfcn.setMaxFeval(maxFEval); 
  objfcn.setMaxIter(maxIter);

  // The "0" in the second argument says to create a new file.  A "1"
  // would signify appending to an existing file.
  if (statusFileName != "")
    if (!objfcn.setOutputFile(statusFileName.c_str(), 1) )
      cerr << "main: output file open failed" << endl;

  objfcn.optimize();

  char status[] = "Solution from quasi-newton"; // hack to avoid compiler warnings
  objfcn.printStatus(status);
  objfcn.cleanup();

  return toNumber( objfcn.getXPrev() );
}
Пример #10
0
 int String::compare(const Value& v) {
     if (v.isString()) {
         return _value.compare(v.toString());
     } else {
         return toNumber() - v.toNumber();
     }
 }
Пример #11
0
LVal filter_sbcl_uri(LVal v) {
  char* str=subseq(firsts(v),-3,0);
  if(strcmp(str,"bz2")==0 ||
     strcmp(str,"msi")==0) {
    char* u=uname();
    char* m=uname_m();
    char *third,*fourth;
    char *m2;
    int i;
    char* tmp=file_namestring(q(firsts(v)));
    LVal ret= split_string(tmp,"-");
    s(tmp);
    third=firsts(nthcdr(2,ret));
    fourth=firsts(nthcdr(3,ret));
    if(strcmp(third,"x86")==0 &&
       strcmp(fourth,"64")==0) {
      m2=q("x86-64");
      i=4;
    }else {
      m2=q(third);
      i=3;
    }
    i=(strcmp(m2,m)==0 && strcmp(firsts(nthcdr(i,ret)),u)==0);

    s(m2),s(str),s(m),s(u),sL(ret);
    return i?toNumber(1):0;
  }
  s(str);
  return 0;
}
Пример #12
0
double JSValue::toIntegerPreserveNaN(ExecState *exec) const
{
    int32_t i;
    if (getTruncatedInt32(i))
        return i;
    return trunc(toNumber(exec));
}
Пример #13
0
double LuaInterface::popNumber()
{
    assert(hasIndex(-1));
    double v = toNumber(-1);
    pop();
    return v;
}
Пример #14
0
// ECMA 9.4
double JSValue::toInteger(ExecState* exec) const
{
    if (isInt32())
        return asInt32();
    double d = toNumber(exec);
    return std::isnan(d) ? 0.0 : trunc(d);
}
Пример #15
0
Файл: hashmap.c Проект: gvx/deja
uint32_t get_hash(V v)
{
	int t = getType(v);
	if (t == T_STR)
	{
		return need_hash(v);
	}
	else if (t == T_NUM)
	{
		return (uint32_t)toNumber(v);
	}
	else if (t == T_PAIR)
	{
		return get_hash(toFirst(v)) + get_hash(toSecond(v));
	}
	else if (t == T_FRAC)
	{
		return toNumerator(v) ^ toDenominator(v);
	}
	else
	{
		return (unsigned long)v >> 4;
		/* This discards 4 bits.
		 * The reason is that allocated addresses are usually
		 * aligned to some extent.
		 * It might get rid of some entropy, though the original
		 * amount was probably low enough already.
		 * If you have a better solution, please share.
		 */
	}
}
Пример #16
0
// ECMA 9.4
double JSValue::toInteger(ExecState *exec) const
{
    int32_t i;
    if (getTruncatedInt32(i))
        return i;
    double d = toNumber(exec);
    return isNaN(d) ? 0.0 : trunc(d);
}
Пример #17
0
    void append( BSONObjBuilder& b , string name , jsval val , BSONType oldType = EOO , int depth=0 ) {
        //cout << "name: " << name << "\t" << typeString( val ) << " oldType: " << oldType << endl;
        switch ( JS_TypeOfValue( _context , val ) ) {

        case JSTYPE_VOID:
            b.appendUndefined( name.c_str() );
            break;
        case JSTYPE_NULL:
            b.appendNull( name.c_str() );
            break;

        case JSTYPE_NUMBER: {
            double d = toNumber( val );
            if ( oldType == NumberInt && ((int)d) == d )
                b.append( name.c_str() , (int)d );
            else
                b.append( name.c_str() , d );
            break;
        }
        case JSTYPE_STRING:
            b.append( name.c_str() , toString( val ) );
            break;
        case JSTYPE_BOOLEAN:
            b.appendBool( name.c_str() , toBoolean( val ) );
            break;

        case JSTYPE_OBJECT: {
            JSObject * o = JSVAL_TO_OBJECT( val );
            if ( ! o || o == JSVAL_NULL ) {
                b.appendNull( name.c_str() );
            }
            else if ( ! appendSpecialDBObject( this , b , name , val , o ) ) {
                BSONObj sub = toObject( o , depth );
                if ( JS_IsArrayObject( _context , o ) ) {
                    b.appendArray( name.c_str() , sub );
                }
                else {
                    b.append( name.c_str() , sub );
                }
            }
            break;
        }

        case JSTYPE_FUNCTION: {
            string s = toString(val);
            if ( s[0] == '/' ) {
                appendRegex( b , name , s );
            }
            else {
                b.appendCode( name.c_str() , getFunctionCode( val ).c_str() );
            }
            break;
        }

        default:
            uassert( 10217 ,  (string)"can't append field.  name:" + name + " type: " + typeString( val ) , 0 );
        }
    }
Пример #18
0
Config readConfig(const char* path) {
	std::ifstream handle(path);
	Config cfg = defaultConfig();

	if(handle.is_open()) {
		std::string line;
		while(getline(handle, line)) {
			if(line[0] == '#')
				continue;
			size_t eqPos = line.find("=");
			if(eqPos == std::string::npos)
				continue;
			std::string tag = strip(line.substr(0, eqPos));
			std::string val = strip(line.substr(eqPos+1));

			// Bwearkh.
			if(tag == "url")
				cfg.challengeUrl = val;
			else if(tag == "http_header")
				cfg.httpHeader = val;
			else if(tag == "post_header")
				cfg.postHeader = val;
			else if(tag == "post_footer")
				cfg.postFooter = val;
			else if(tag == "on_success")
				cfg.onSuccessProgram = val;
			else if(tag == "challenge_length")
				cfg.challengeLength = toNumber(val);
			else if(tag == "cooldown_time")
				cfg.authCooldownTime = toNumber(val);
			else {
				fprintf(stderr, "Invalid configuration tag: %s.\n",
						tag.c_str());
				exit(1);
			}
		}
	}
	else {
		fprintf(stderr, "Can't open configuration file. Aborting.\n");
		exit(1);
	}

	return cfg;
}
Пример #19
0
uint64_t
Component::toSequenceNumber() const
{
  if (canDecodeMarkerConvention() && type() == tlv::GenericNameComponent) {
    return toNumberWithMarker(SEQUENCE_NUMBER_MARKER);
  }
  if (canDecodeTypedConvention() && type() == tlv::SequenceNumNameComponent) {
    return toNumber();
  }
  NDN_THROW(Error("Not a SequenceNumber component"));
}
Пример #20
0
uint64_t
Component::toByteOffset() const
{
  if (canDecodeMarkerConvention() && type() == tlv::GenericNameComponent) {
    return toNumberWithMarker(SEGMENT_OFFSET_MARKER);
  }
  if (canDecodeTypedConvention() && type() == tlv::ByteOffsetNameComponent) {
    return toNumber();
  }
  NDN_THROW(Error("Not a ByteOffset component"));
}
Пример #21
0
uint64_t
Component::toVersion() const
{
  if (canDecodeMarkerConvention() && type() == tlv::GenericNameComponent) {
    return toNumberWithMarker(VERSION_MARKER);
  }
  if (canDecodeTypedConvention() && type() == tlv::VersionNameComponent) {
    return toNumber();
  }
  NDN_THROW(Error("Not a Version component"));
}
Point JSON::toPoint(const JSONValue& value)
{
    MMLT_precondition_msg(
        isArray(value),
        mmlt_msg("Expected point, got %1!")
        .arg(QString::fromStdString(toString(value)))
    );

    const JSONArray& coordinates = toArray(value);

    MMLT_precondition_msg(
        (coordinates.size() == 2),
        mmlt_msg("Point has invalid dimension (%1)!")
        .arg(coordinates.size())
    );

    return Point(
        toNumber(coordinates[0]),
        toNumber(coordinates[1])
    );
}
Пример #23
0
Файл: blob.c Проект: gvx/deja
Error make_blob(Stack *S, Stack *scope_arr)
{
	require(1);
	V v = popS();
	if (getType(v) != T_NUM)
	{
		clear_ref(v);
		return TypeError;
	}
	pushS(new_blob(toNumber(v)));
	clear_ref(v);
	return Nothing;
}
Пример #24
0
Error chr(Stack* S, Stack* scope_arr)
{
	require(1);
	V v = popS();
	if (getType(v) != T_NUM)
	{
		clear_ref(v);
		return TypeError;
	}
	pushS(unichar_to_value(toNumber(v)));
	clear_ref(v);
	return Nothing;
}
Пример #25
0
bool RPNParser::handle_token(std::string token, double at_value)
{
    if(OneOps.find(token) != OneOps.end()) // valami függvény
    {
        double arg = m_stack.top();
        double newval = (OneOps[token])(arg);
        m_stack.pop();
        m_stack.push(newval);
    }
    else if(TwoOps.find(token) != TwoOps.end()) // kétoperandusú kifejezés
    {
        if(m_stack.size() < 2)
        {
            throw std::invalid_argument("Invalid expression, want to eval a two-operand expression with one or less value on stack");
        }
        double arg1 = m_stack.top();
        m_stack.pop();
        double arg2 = m_stack.top();
        m_stack.pop();

        double newval = (TwoOps[token])(arg1, arg2);
        m_stack.push(newval);
    }
    else if(token == "x")
    {
        m_stack.push(at_value);
    }
    else if( !std::isnan(toNumber(token)) ) // Szám
    {
        m_stack.push(toNumber(token));
    }
    else
    {
        return false;
    }
    return true;
}
Пример #26
0
time::system_clock::TimePoint
Component::toTimestamp() const
{
  uint64_t value = 0;
  if (canDecodeMarkerConvention() && type() == tlv::GenericNameComponent) {
    value = toNumberWithMarker(TIMESTAMP_MARKER);
  }
  else if (canDecodeTypedConvention() && type() == tlv::TimestampNameComponent) {
    value = toNumber();
  }
  else {
    NDN_THROW(Error("Not a Timestamp component"));
  }
  return time::getUnixEpoch() + time::microseconds(value);
}
 int evalRPN(vector<string> &tokens) {
     stack<int> s;
     for (int i = 0; i < tokens.size(); ++ i) {
         string key = tokens[i];
         if (is_operator(key)) {
             int b = s.top();
             s.pop();
             int a = s.top();
             s.pop();
             s.push(eval(a, b, key[0]));
         } else {
             s.push(toNumber(key));
         }
     }
     return s.top();
 }
Пример #28
0
as_value
number_ctor(const fn_call& fn)
{
    double val = 0;
    if (fn.nargs > 0) {
        val = toNumber(fn.arg(0), getVM(fn));
    }

    if (!fn.isInstantiation()) {
        return as_value(val);
    }

    fn.this_ptr->setRelay(new Number_as(val));
    
    return as_value(); 
}
Пример #29
0
void ValueWriter::writeThis(BSONObjBuilder* b,
                            StringData sd,
                            ObjectWrapper::WriteFieldRecursionFrames* frames) {
    uassert(17279,
            str::stream() << "Exceeded depth limit of " << ObjectWrapper::kMaxWriteFieldDepth
                          << " when converting js object to BSON. Do you have a cycle?",
            frames->size() < ObjectWrapper::kMaxWriteFieldDepth);

    // Null char should be at the end, not in the string
    uassert(16985,
            str::stream() << "JavaScript property (name) contains a null char "
                          << "which is not allowed in BSON. "
                          << (_originalParent ? _originalParent->jsonString() : ""),
            (std::string::npos == sd.find('\0')));

    if (_value.isString()) {
        JSStringWrapper jsstr;
        b->append(sd, toStringData(&jsstr));
    } else if (_value.isNumber()) {
        double val = toNumber();

        // if previous type was integer, keep it
        int intval = static_cast<int>(val);

        if (val == intval && _originalParent) {
            // This makes copying an object of numbers O(n**2) :(
            BSONElement elmt = _originalParent->getField(sd);
            if (elmt.type() == mongo::NumberInt) {
                b->append(sd, intval);
                return;
            }
        }

        b->append(sd, val);
    } else if (_value.isObject()) {
        _writeObject(b, sd, frames);
    } else if (_value.isBoolean()) {
        b->appendBool(sd, _value.toBoolean());
    } else if (_value.isUndefined()) {
        b->appendUndefined(sd);
    } else if (_value.isNull()) {
        b->appendNull(sd);
    } else {
        uasserted(16662,
                  str::stream() << "unable to convert JavaScript property to mongo element " << sd);
    }
}
Пример #30
0
int main()
{
    int i,j,N,seq[11];
    char s[10];
    for(i=0;i<128;i++) for(j=0;j<10;j++) if((i&rep[j])==rep[j]) {A[i][j]=1;def[i][j]=i^rep[j];}
    while(1) {
        scanf("%d",&N);if(!N) break;
        for(i=0;i<N;i++) {
            scanf("%s",s);seq[i]=toNumber(s);
            /*printf("%d : ",seq[i]);
            for(j=0;j<10;j++) if(A[seq[i]][j]) printf("%d ",j);printf("\n");*/
        }
        for(i=0;i<10;i++) {if(A[seq[0]][i]&&isMatch(seq,1,i,N-1,def[seq[0]][i])) {printf("MATCH\n");break;}}
        if(i==10) printf("MISMATCH\n");
    }
    return 0;
}