示例#1
0
void JSContext::callAsConstructor()
{
    QFETCH(QString, module);
    QFETCH(QString, className);
    QFETCH(QString, arg);
    QFETCH(QString, method);
    QFETCH(QString, methodArg);
    QFETCH(QString, output);

    TJSModule *js = TJSLoader(module).load();
    auto instance = js->callAsConstructor(className, arg);
    QCOMPARE(instance.isError(), false);
    auto result1 = instance.call(method, methodArg).toString();
    QCOMPARE(result1, output);
}
示例#2
0
std::vector<std::string> ReadConfig::getGroupKeys(const char* group_name){
    std::vector<std::string> keys = std::vector<std::string>();
    gsize length;
    error = nullptr;
    gchar** key = g_key_file_get_keys(config, group_name, &length, &error);
    if (isError()){
        this->exit_failure(error->message);
        return std::vector<std::string>();
    }

    for (int i = 0; i < length; i++){
        keys.push_back(key[i]);
    }

    return keys;
}
示例#3
0
Error Surface::releaseTexImage(const gl::Context *context, EGLint buffer)
{
    ASSERT(context);

    ANGLE_TRY(mImplementation->releaseTexImage(buffer));

    ASSERT(mTexture.get());
    auto glErr = mTexture->releaseTexImageFromSurface(context);
    if (glErr.isError())
    {
        return Error(EGL_BAD_SURFACE);
    }
    mTexture.set(context, nullptr);

    return NoError();
}
    int read (void* buffer, int bytesToRead)
    {
        jassert (buffer != nullptr && bytesToRead >= 0);
        DWORD bytesRead = 0;

        if (! (finished || isError()))
        {
            InternetReadFile (request, buffer, (DWORD) bytesToRead, &bytesRead);
            position += bytesRead;

            if (bytesRead == 0)
                finished = true;
        }

        return (int) bytesRead;
    }
void HandshakeResponder::responderParseStarterHello(){ //R:1 parse
    QByteArray packet;
    m_socketStream >> packet;
    QDataStream packetStream(&packet, QIODevice::ReadOnly);

    if(isError(packet)) return;

    quint8 secLevel;
    packetStream >> secLevel;
    if(static_cast<SecurityLevel>(secLevel) != PreSharedIdentity){
        processError(BadSecurityLevel);
        return;
    }

    QByteArray rsaCypherText;
    packetStream >> rsaCypherText;
    QByteArray clearText = rsaDecrypt(rsaCypherText);
    if(clearText.isEmpty()){
        processError(DataCorrupted);
        return;
    }
    QDataStream clearTextStream(&clearText, QIODevice::ReadOnly);
    QByteArray key;
    clearTextStream >> key;
    m_contact = m_contactDB->findByKey(key);
    if(m_contact == NULL){
        processError(IdentityCheckFailed);
        return;
    }
    try{
        m_rsaEncryptor.AccessKey().Load(ArraySource((byte*)m_contact->getKey().data(),
                                                    m_contact->getKey().size(),
                                                    true));
    }catch(CryptoPP::BERDecodeErr&){
        processError(BadContactKey);
    }

    quint8 version;
    clearTextStream >> version;
    if((version & 0xF0) != (SUPPORTED_PROTOCOL_VERSION & 0xF0)){
        processError(IncompatibleProtocolVersions);
        return;
    }

    updateIntegrityHash(&m_starterIntegrityHash, (char)secLevel+clearText);
    responderRespondHello();
}
示例#6
0
文件: sqlite_db.cpp 项目: volka/talks
Notebook Sqlite3Database::loadNotebook(const bigint_t notebook_id)
{
    clearStatement();
    stmt_cache_ << "SELECT * FROM notebooks WHERE id="
                << std::to_string(notebook_id);

    auto result = prepareStatement(stmt_cache_.str());

    if (isError(executeStep(result)))
        throw DatabaseException("loading notebook id " +
                                std::to_string(notebook_id) +
                                " failed, invalid result");

    Notebook nb(getInt(result, 0), getString(result, 1));

    return nb;
}
void HandshakeResponder::responderParseHandshakeFinished(){ //R:3 parse
    m_timeout.stop();
    disconnect(m_socket, &AbstractLink::readyRead, this, 0);
    QByteArray cypherResponse;
    m_socketStream >> cypherResponse;
    if(isError(cypherResponse))return;

    QByteArray clearResponse = gcmDecrypt(cypherResponse);

    if(clearResponse.isEmpty()) return;

    else if(clearResponse.size() == 1 && clearResponse.at(0) == (char)HandshakeFinished){
        emit success();
    }else{
        processError(UndefinedError);
    }
}
示例#8
0
    StringPairArray getResponseHeaders() const
    {
        StringPairArray responseHeaders;
        if (! isError())
        {
            for (int i = 0; i < headerLines.size(); ++i)
            {
                const String& headersEntry = headerLines[i];
                const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
                const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
                const String previousValue (responseHeaders [key]);
                responseHeaders.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
            }
        }

        return responseHeaders;
    }
示例#9
0
eIoAction EventTrigger::handleIoEvent()
{
    if (isError())
    {
        throw std::system_error(errno, std::system_category(),
                                "EventTrigger::handleIoEvent: error.");
    }

    if (isEof())
    {
        throw std::system_error(errno, std::system_category(),
                                "EventTrigger::handleIoEvent: eof.");
    }

    acknowledge();
    return eIoAction::Read;
}
示例#10
0
SOCKET socket_accept_blocking(SOCKET serverSocket) {
	SOCKET socket = ::accept(serverSocket, NULL, 0);
	if (socket == INVALID_SOCKET) {
		return INVALID_SOCKET;
	}

	// Make sure to block
	ESErrorCode err = socket_setblocking(socket);
	if (isError(err)) {
		socket_close(socket);
		return 0;
	}

	socket_nodelay(socket);
	socket_setbufsize(socket, DEFAULT_MAX_DATA_SEND_SIZE);
	return socket;
}
EGLBoolean EGLAPIENTRY MakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx)
{
    EVENT(
        "(EGLDisplay dpy = 0x%0.8p, EGLSurface draw = 0x%0.8p, EGLSurface read = 0x%0.8p, "
        "EGLContext ctx = 0x%0.8p)",
        dpy, draw, read, ctx);
    Thread *thread = GetCurrentThread();

    Display *display     = static_cast<Display *>(dpy);
    gl::Context *context = static_cast<gl::Context *>(ctx);

    Error error = ValidateMakeCurrent(display, draw, read, context);
    if (error.isError())
    {
        thread->setError(error);
        return EGL_FALSE;
    }

    Surface *readSurface   = static_cast<Surface *>(read);
    Surface *drawSurface   = static_cast<Surface *>(draw);
    Error makeCurrentError = display->makeCurrent(drawSurface, readSurface, context);
    if (makeCurrentError.isError())
    {
        thread->setError(makeCurrentError);
        return EGL_FALSE;
    }

    gl::Context *previousContext = thread->getContext();
    thread->setCurrent(context);

    // Release the surface from the previously-current context, to allow
    // destroyed surfaces to delete themselves.
    if (previousContext != nullptr && context != previousContext)
    {
        auto err = previousContext->releaseSurface(display);
        if (err.isError())
        {
            thread->setError(err);
            return EGL_FALSE;
        }
    }

    thread->setError(NoError());
    return EGL_TRUE;
}
WindowsGSSAPIClientAuthenticator::WindowsGSSAPIClientAuthenticator(const std::string& hostname, const std::string& domainname, int port) : ClientAuthenticator("GSSAPI"), step_(BuildingSecurityContext), error_(false), haveCredentialsHandle_(false), haveContextHandle_(false), haveCompleteContext_(false) {
    WindowsServicePrincipalName servicePrincipalName(domainname);
    servicePrincipalName.setInstanceName(hostname);
    if ((port != -1) && (port != 5222)) {
        servicePrincipalName.setInstancePort(port);
    }
    servicePrincipalNameString_ = servicePrincipalName.toString();

    errorCode_ = acquireCredentialsHandle(&credentialsHandle_);
    if (isError()) {
        return;
    }
    else {
        haveCredentialsHandle_ = true;
    }

    buildSecurityContext(boost::optional<ByteArray>());
}
示例#13
0
文件: sqlite_db.cpp 项目: volka/talks
Note Sqlite3Database::loadNote(const bigint_t note_id)
{
    clearStatement();
    stmt_cache_ << "SELECT title,content,notebook,last_change,reminder"
                   " FROM notes WHERE (id=" << std::to_string(note_id) << ")";
    auto result = prepareStatement(stmt_cache_.str());

    if (isError(executeStep(result))) {
        throw DatabaseException("loading note id " + std::to_string(note_id) +
                                " failed, invalid result");
    }
    return Note(note_id, getString(result, 0), // title
                getString(result, 1),          // content
                getInt(result, 2),             // notebook
                getTimestamp(result, 3),       // last change
                getTimestamp(result, 4)        // reminder
                );
}
示例#14
0
SOCKET socket_create_blocking() {
	// Create a socket
	SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (s == INVALID_SOCKET) {
		return s;
	}

	// Make sure to block
	ESErrorCode err = socket_setblocking(s);
	if (isError(err)) {
		socket_close(s);
		return 0;
	}

	socket_nodelay(s);
	socket_setbufsize(s, DEFAULT_MAX_DATA_SEND_SIZE);
	return s;
}
示例#15
0
    void Connection::deallocateStatements()
    {
      for (std::vector<std::string>::size_type n = 0; n < stmtsToDeallocate.size(); ++n)
      {
        std::string sql = "DEALLOCATE " + stmtsToDeallocate[n];

        log_debug("PQexec(" << getPGConn() << ", \"" << sql << "\")");
        PGresult* result = PQexec(getPGConn(), sql.c_str());

        if (isError(result))
          log_error("error deallocating statement: " << PQresultErrorMessage(result));

        log_debug("PQclear(" << result << ')');
        PQclear(result);
      }

      stmtsToDeallocate.clear();
    }
示例#16
0
GTEST_TEST(ExpectedTest, error_handling_example) {
  auto failureSource = []() -> Expected<std::vector<int>, TestError> {
    return createError(TestError::Runtime, "Test error message ()*+,-.");
  };
  auto ret = failureSource();
  if (ret.isError()) {
    switch (ret.getErrorCode()) {
    case TestError::Some:
    case TestError::Another:
    case TestError::Semantic:
    case TestError::Logical:
      FAIL() << "There is must be a Runtime type of error";
    case TestError::Runtime:
      SUCCEED();
    }
  } else {
    FAIL() << "There is must be an error";
  }
}
示例#17
0
文件: sqlite_db.cpp 项目: volka/talks
void Sqlite3Database::updateNote(const Note &note)
{
    auto date_str = pt::to_iso_string(note.reminder());

    clearStatement();
    stmt_cache_ << "UPDATE notes SET title=?1,content=?2,"
                << "notebook=?3,last_change=datetime('now','localtime'),"
                << "reminder=?4 where (id=?5)";

    auto result = prepareStatement(stmt_cache_.str());

    bindString(result, 1, note.title());
    bindString(result, 2, note.content());
    bindInt(result, 3, note.notebook());
    bindString(result, 4, date_str);
    bindInt(result, 5, note.id());
    if (isError(executeStep(result)))
        throw DatabaseException("updating note " + note.title() + " failed");
}
示例#18
0
文件: toobj.c 项目: Orvid/dmd
void Nspace::toObjFile(bool multiobj)
{
#if LOG
    printf("Nspace::toObjFile('%s', this = %p)\n", toChars(), this);
#endif
    if (!isError(this) && members)
    {
        if (multiobj)
            // Append to list of object files to be written later
            obj_append(this);
        else
        {
            for (size_t i = 0; i < members->dim; i++)
            {
                Dsymbol *s = (*members)[i];
                s->toObjFile(multiobj);
            }
        }
    }
}
示例#19
0
文件: sqlite_db.cpp 项目: volka/talks
void Sqlite3Database::removeTag(const bigint_t note_id, const bigint_t tag_id)
{

    clearStatement();
    if (note_id < 0) {
        stmt_cache_ << "DELETE FROM tags_nm WHERE (tag_id="
                    << std::to_string(tag_id) << ")";
    } else if (tag_id < 0) {
        stmt_cache_ << "DELETE FROM tags_nm WHERE (note_id="
                    << std::to_string(note_id) << ")";
    } else {
        stmt_cache_ << "DELETE FROM tags_nm WHERE (note_id="
                    << std::to_string(note_id)
                    << " and tag_id=" << std::to_string(tag_id) << ")";
    }
    auto result = prepareStatement(stmt_cache_.str());
    if (isError(executeStep(result)))
        throw DatabaseException("removing tag " + std::to_string(tag_id) +
                                " failed");
}
示例#20
0
    WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
                    URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
                    const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
      : connection (0), request (0),
        address (address_), headers (headers_), postData (postData_), position (0),
        finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
    {
        createConnection (progressCallback, progressCallbackContext);

        if (responseHeaders != nullptr && ! isError())
        {
            DWORD bufferSizeBytes = 4096;

            for (;;)
            {
                HeapBlock<char> buffer ((size_t) bufferSizeBytes);

                if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
                {
                    StringArray headersArray;
                    headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));

                    for (int i = 0; i < headersArray.size(); ++i)
                    {
                        const String& header = headersArray[i];
                        const String key (header.upToFirstOccurrenceOf (": ", false, false));
                        const String value (header.fromFirstOccurrenceOf (": ", false, false));
                        const String previousValue ((*responseHeaders) [key]);

                        responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
                    }

                    break;
                }

                if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
                    break;
            }

        }
    }
示例#21
0
    Connection::size_type Connection::execute(const std::string& query)
    {
      log_debug("execute(\"" << query << "\")");

      log_debug("PQexec(" << conn << ", \"" << query << "\")");
      PGresult* result = PQexec(conn, query.c_str());
      if (isError(result))
      {
        log_error(PQresultErrorMessage(result));
        throw PgSqlError(query, "PQexec", result, true);
      }

      std::string t = PQcmdTuples(result);
      Connection::size_type ret = t.empty() ? 0
                                            : cxxtools::convert<Connection::size_type>(t);

      log_debug("PQclear(" << result << ')');
      PQclear(result);

      return ret;
    }
示例#22
0
    WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
                    URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
                    const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
      : socketHandle (-1), levelsOfRedirection (0),
        address (address_), headers (headers_), postData (postData_), position (0),
        finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
    {
        createConnection (progressCallback, progressCallbackContext);

        if (responseHeaders != nullptr && ! isError())
        {
            for (int i = 0; i < headerLines.size(); ++i)
            {
                const String& headersEntry = headerLines[i];
                const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
                const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
                const String previousValue ((*responseHeaders) [key]);
                responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
            }
        }
    }
示例#23
0
    bool setPosition (int64 wantedPos) override
    {
        if (isError())
            return false;

        if (wantedPos != position)
        {
            finished = false;

            if (wantedPos < position)
            {
                closeSocket();
                position = 0;
                createConnection (0, 0);
            }

            skipNextBytes (wantedPos - position);
        }

        return true;
    }
示例#24
0
    bool setPosition (int64 wantedPos) override
    {
        if (isError())
            return false;

        if (wantedPos != position)
        {
            finished = false;

            if (wantedPos < position)
            {
                closeSocket();
                position = 0;
                statusCode = createConnection (0, 0, numRedirectsToFollow);
            }

            skipNextBytes (wantedPos - position);
        }

        return true;
    }
示例#25
0
int TextRendererTTF::textWidth(const char* text, int n) const
{
    if (isError())
        return 0;

    FT_Set_Pixel_Sizes(face, 0, fontSize);
    FT_GlyphSlot g = face->glyph;
    int  x = 0;

    for (int i = 0; i < n; i++)
    {
        /* Try to load and render the character */
        if (FT_Load_Char(face, text[i], FT_LOAD_RENDER))
            continue;

        /* Advance the cursor to the start of the next character */
        x += g->advance.x >> 6;
    }

    return x;
}
示例#26
0
文件: sqlite_db.cpp 项目: volka/talks
// DEMO : sqlite3 example with prepared statement parameters
void Sqlite3Database::newNote(Note &note)
{
    auto date_str = pt::to_iso_string(note.reminder());

    clearStatement();
    stmt_cache_ << "INSERT INTO notes(title,content,notebook,reminder) VALUES("
                << "?1, ?2, ?3, ?4"
                << ")";

    auto result = prepareStatement(stmt_cache_.str());

    bindString(result, 1, note.title());
    bindString(result, 2, note.content());
    bindInt(result, 3, note.notebook());
    bindString(result, 4, date_str);
    if (isError(executeStep(result)))
        throw DatabaseException("inserting note " + note.title() + " failed");

    // get the generated ID
    note.id(getLastInsertId());
}
示例#27
0
 void visit(Nspace *ns)
 {
 #if LOG
     printf("Nspace::toObjFile('%s', this = %p)\n", ns->toChars(), ns);
 #endif
     if (!isError(ns) && ns->members)
     {
         if (multiobj)
         {
             // Append to list of object files to be written later
             obj_append(ns);
         }
         else
         {
             for (size_t i = 0; i < ns->members->dim; i++)
             {
                 Dsymbol *s = (*ns->members)[i];
                 s->accept(this);
             }
         }
     }
 }
示例#28
0
    bool setPosition (int64 wantedPos)
    {
        if (isError())
            return false;

        if (wantedPos != position)
        {
            finished = false;

            if (wantedPos < position)
                return false;

            int64 numBytesToSkip = wantedPos - position;
            const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
            HeapBlock<char> temp ((size_t) skipBufferSize);

            while (numBytesToSkip > 0 && ! isExhausted())
                numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
        }

        return true;
    }
示例#29
0
    int read (void* buffer, int bytesToRead)
    {
        if (finished || isError())
            return 0;

        fd_set readbits;
        FD_ZERO (&readbits);
        FD_SET (socketHandle, &readbits);

        struct timeval tv;
        tv.tv_sec = jmax (1, timeOutMs / 1000);
        tv.tv_usec = 0;

        if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
            return 0;   // (timeout)

        const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
        if (bytesRead == 0)
            finished = true;
        position += bytesRead;
        return bytesRead;
    }
static void verify_Options(struct Options *Options) {
	//algorithms
	if (Options->calculate_mass == 0 && \
			Options->calculate_heat == 0 && \
			Options->calculate_hybrid == 0 && \
			Options->calculate_HNBI == 0 && \
			Options->calculate_RENBI == 0 && \
			Options->calculate_UCF == 0 && \
			Options->calculate_ICF == 0 && \
			Options->calculate_SVD == 0) {
		isError("no algorithms selected, what do you want to calculate?");
	}

	//dataset & dataset_divide_rate
	if (Options->total_filename == NULL && \
			(Options->train_filename == NULL || Options->test_filename == NULL)) {
		isError("dataset not enough.");
	}
	else if (Options->total_filename != NULL && \
			(Options->train_filename != NULL || Options->test_filename != NULL)) {
		isError("dataset too much.\n");
	}
	else if (Options->total_filename != NULL) {
		if (Options->dataset_divide_rate <= 0 || Options->dataset_divide_rate >= 1) {
			isError("We will use the whole dataset file: %s, but why the divide_rate is %f?",\
					Options->total_filename, Options->dataset_divide_rate);
		}
		else {
			printsf("using the whole dataset file: %s, divide_rate is %f.",\
					Options->total_filename, Options->dataset_divide_rate);
		}
	}
	else {
		printsf("using the trainset file: %s and the testset file: %s", Options->train_filename, Options->test_filename);
	}

	//loopnum
	if (Options->loopNum < 1) {
		isError("are you sure you want to set the loopNum to %d?", Options->loopNum);
	}

	//L
	if (Options->L < 1) {
		isError("are you sure you want to set the L to %d?", Options->L);
	}
}