<commit_before>/*
 * httpserver2-threads.cc: Multithreaded HTTP server example
 *
 * Copyright (C) 2003-2017 by Thomas Dreibholz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact: dreibh@iem.uni-due.de
 */

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>

#include <neat-socketapi.h>

#include "thread.h"
#include "ansistyle.h"
#include "safeprint.h"

using namespace std;

static const char* properties = "{\
    \"transport\": [\
        {\
            \"value\": \"SCTP\",\
            \"precedence\": 1\
        },\
        {\
            \"value\": \"TCP\",\
            \"precedence\": 1\
        }\
    ]\
}";\

class ServiceThread : public Thread
{
   public:
   ServiceThread(int sd);
   ~ServiceThread();

   inline bool hasFinished() {
      return(SocketDesc < 0);
   }

   private:
   void run();

   unsigned int ID;
   int          SocketDesc;
};

ServiceThread::ServiceThread(int sd)
{
   static unsigned int IDCounter = 0;
   ID         = ++IDCounter;
   SocketDesc = sd;
   cout << "Starting thread " << ID << "..." << endl;
   start();
}

ServiceThread::~ServiceThread()
{
   cout << "Stopping thread " << ID << "..." << endl;
   if(SocketDesc >= 0) {
      nsa_close(SocketDesc);
   }
   waitForFinish();
   cout << "Thread " << ID << " has been stopped." << endl;
}

void ServiceThread::run()
{
   // ====== Get command ==================================================
   char   command[1024];
   size_t cmdpos = 0;
   while(cmdpos < sizeof(command) - 1) {
      const ssize_t r = nsa_read(SocketDesc, &command[cmdpos], 1);
      if(r <= 0) {
         nsa_close(SocketDesc);
         SocketDesc = -1;
         return;
      }
      if(command[cmdpos] == '\r') {
         command[cmdpos] = 0x00;
         break;
      }
      cmdpos++;
   }

   cout << "Command: ";
   safePrint(cout, command, cmdpos);
   cout << endl;

   // ====== Execute HTTP GET command =====================================
   ssize_t result = 0;
   if(strncasecmp(command, "GET ", 4) == 0) {
      std::string fileName = std::string((const char*)&command[4]);
      fileName = fileName.substr(0, fileName.find(' '));   // Remove <space>HTTP/1.x
      while(fileName[0] == '/') {                          // No absolute paths!
         fileName.erase(0, 1);
      }
      if(fileName == "") {   // No file name -> index.html
         fileName = "index.html";
      }

      if(fileName[0] != '.') {   // No access to top-level directories!
         cout << "Thread " << ID << ": Trying to upload file \""
              << fileName << "\"..." << endl;
         ifstream is(fileName.c_str(), ios::binary);
         if(is.good()) {
            const char* status = "HTTP/1.0 200 OK\r\n\r\n";
            result = nsa_write(SocketDesc, status, strlen(status));

            char str[8192];
            streamsize s = is.rdbuf()->sgetn(str, sizeof(str));
            while((s > 0) && (result > 0)) {
               result = nsa_write(SocketDesc, str, s);
               s = is.rdbuf()->sgetn(str, sizeof(str));
            }
         }
         else {
            cout << "Thread " << ID << ": File <" << fileName << "> not found!" << endl;
            const char* status = "HTTP/1.0 404 Not Found\r\n\r\n404 Not Found\r\n";
            result = nsa_write(SocketDesc, status, strlen(status));
         }
      }
      else {
         cout << "Thread " << ID << ": Request for . or .. not acceptable!" << endl;
         const char* status = "HTTP/1.0 406 Not Acceptable\r\n\r\n406 Not Acceptable\r\n";
         result = nsa_write(SocketDesc, status, strlen(status));
      }
   }
   else {
      cout << "Thread " << ID << ": Bad request!" << endl;
      const char* status = "HTTP/1.0 400 Bad Request\r\n\r\n400 Bad Request\r\n";
      result = nsa_write(SocketDesc, status, strlen(status));
   }

   // ====== Shutdown connection ==========================================
   nsa_shutdown(SocketDesc, SHUT_RDWR);
   nsa_close(SocketDesc);
   SocketDesc = -1;
}

class ServiceThreadList
{
   public:
   ServiceThreadList();
   ~ServiceThreadList();
   void add(ServiceThread* thread);
   void remove(ServiceThread* thread);
   void removeFinished();
   void removeAll();

   private:
   struct ThreadListEntry {
      ThreadListEntry* Next;
      ServiceThread*   Object;
   };
   ThreadListEntry* ThreadList;
};

ServiceThreadList::ServiceThreadList()
{
   ThreadList = NULL;
}

ServiceThreadList::~ServiceThreadList()
{
   removeAll();
}

void ServiceThreadList::removeFinished()
{
   ThreadListEntry* entry = ThreadList;
   while(entry != NULL) {
      ThreadListEntry* next = entry->Next;
      if(entry->Object->hasFinished()) {
         remove(entry->Object);
      }
      entry = next;
   }
}

void ServiceThreadList::removeAll()
{
   ThreadListEntry* entry = ThreadList;
   while(entry != NULL) {
      remove(entry->Object);
      entry = ThreadList;
   }
}

void ServiceThreadList::add(ServiceThread* thread)
{
   ThreadListEntry* entry = new ThreadListEntry;
   entry->Next   = ThreadList;
   entry->Object = thread;
   ThreadList    = entry;
}

void ServiceThreadList::remove(ServiceThread* thread)
{
   ThreadListEntry* entry = ThreadList;
   ThreadListEntry* prev  = NULL;
   while(entry != NULL) {
      if(entry->Object == thread) {
         if(prev == NULL) {
            ThreadList = entry->Next;
         }
         else {
            prev->Next = entry->Next;
         }
         delete entry->Object;
         entry->Object = NULL;
         delete entry;
         return;
      }
      prev  = entry;
      entry = entry->Next;
   }
}

int ServerSocket = -1;

void intHandler(int signum)
{
   if(ServerSocket >= 0) {
      fputs("*** Ctrl-C ***\n", stderr);
      nsa_close(ServerSocket);
      ServerSocket = -1;
   }
}

int main(int argc, char** argv)
{
   if(argc < 2) {
      cerr << "Usage: " << argv[0] << " [Port]" << endl;
      exit(1);
   }

   // ====== Get remote address (resolve hostname and service if necessary) ==
   struct addrinfo* ainfo = NULL;
   struct addrinfo  ainfohint;
   memset((char*)&ainfohint, 0, sizeof(ainfohint));
   // AI_PASSIVE will set address to the ANY address.
   ainfohint.ai_flags    = AI_PASSIVE;
   ainfohint.ai_family   = AF_UNSPEC;
   ainfohint.ai_socktype = SOCK_STREAM;
   ainfohint.ai_protocol = IPPROTO_TCP;
   int error = getaddrinfo(NULL, argv[1], &ainfohint, &ainfo);
   if(error != 0) {
      cerr << "ERROR: getaddrinfo() failed: " << gai_strerror(error) << endl;
      exit(1);
   }

   // ====== Create socket of appropriate type ===============================
   ServerSocket = nsa_socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol, properties);
   if(ServerSocket <= 0) {
      perror("nsa_socket() call failed");
      exit(1);
   }

   // ====== Bind to local port ==============================================
   if(nsa_bind(ServerSocket, ainfo->ai_addr, ainfo->ai_addrlen) < 0) {
      perror("nsa_bind() call failed");
      exit(1);
   }

   // ====== Turn socket into "listen" mode ==================================
   if(nsa_listen(ServerSocket, 10) < 0) {
      perror("nsa_listen() call failed");
   }

   // ====== Install SIGINT handler ==========================================
   signal(SIGINT, &intHandler);

   // ====== Print information ===============================================
   char localHost[512];
   char localService[128];
   error = getnameinfo(ainfo->ai_addr, ainfo->ai_addrlen,
                       (char*)&localHost, sizeof(localHost),
                       (char*)&localService, sizeof(localService),
                       NI_NUMERICHOST);
   if(error != 0) {
      cerr << "ERROR: getnameinfo() failed: " << gai_strerror(error) << endl;
      exit(1);
   }
   cout << "Waiting for requests at address "
        << localHost << ", service " << localService << "..." << endl;

   // ====== Handle requests =================================================
   ServiceThreadList stl;
   for(;;) {
      // ====== Accept connection ============================================
      sockaddr_storage remoteAddress;
      socklen_t        remoteAddressLength = sizeof(remoteAddress);
      const int        newSD = nsa_accept(ServerSocket, (sockaddr*)&remoteAddress, &remoteAddressLength);
      if(newSD < 0) {
         break;
      }

      // ====== Delete finished threads ======================================
      stl.removeFinished();

      // ====== Print information ============================================
      char remoteHost[512];
      char remoteService[128];
      error = getnameinfo((sockaddr*)&remoteAddress, remoteAddressLength,
                          (char*)&remoteHost, sizeof(remoteHost),
                          (char*)&remoteService, sizeof(remoteService),
                          NI_NUMERICHOST);
      if(error != 0) {
         cerr << "ERROR: getnameinfo() failed: " << gai_strerror(error) << endl;
         exit(1);
      }
      cout << "Got connection from "
           << remoteHost << ", service " << remoteService << ":" << endl;

      // ====== Start new service thread =====================================
      stl.add(new ServiceThread(newSD));
   }

   // ====== Clean up ========================================================
   stl.removeAll();
   freeaddrinfo(ainfo);
   if(ServerSocket >= 0) {
      nsa_close(ServerSocket);
   }
   nsa_cleanup();

   cout << endl << "Terminated!" << endl;
   return(0);
}
<commit_msg>Fixed problem with SCTP connections to the HTTP server: SCTP sends messages, not bytes => need to be able to read a full message!<commit_after>/*
 * httpserver2-threads.cc: Multithreaded HTTP server example
 *
 * Copyright (C) 2003-2017 by Thomas Dreibholz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact: dreibh@iem.uni-due.de
 */

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>

#include <neat-socketapi.h>

#include "thread.h"
#include "ansistyle.h"
#include "safeprint.h"

using namespace std;

static const char* properties = "{\
    \"transport\": [\
        {\
            \"value\": \"SCTP\",\
            \"precedence\": 1\
        },\
        {\
            \"value\": \"TCP\",\
            \"precedence\": 1\
        }\
    ]\
}";\

class ServiceThread : public Thread
{
   public:
   ServiceThread(int sd);
   ~ServiceThread();

   inline bool hasFinished() {
      return(SocketDesc < 0);
   }

   private:
   void run();

   unsigned int ID;
   int          SocketDesc;
};

ServiceThread::ServiceThread(int sd)
{
   static unsigned int IDCounter = 0;
   ID         = ++IDCounter;
   SocketDesc = sd;
   cout << "Starting thread " << ID << "..." << endl;
   start();
}

ServiceThread::~ServiceThread()
{
   cout << "Stopping thread " << ID << "..." << endl;
   if(SocketDesc >= 0) {
      nsa_close(SocketDesc);
   }
   waitForFinish();
   cout << "Thread " << ID << " has been stopped." << endl;
}

void ServiceThread::run()
{
   // ====== Get command ==================================================
   char   command[8192];
   size_t cmdpos   = 0;
   bool   finished = false;
   while( (cmdpos < sizeof(command) - 1) && (!finished) ) {
      const ssize_t r = nsa_read(SocketDesc, &command[cmdpos], sizeof(command) - cmdpos);
      if(r <= 0) {
         if(r < 0) {
            cout << "Thread " << ID << ": Connection aborted - " << strerror(errno) << endl;
         }
         nsa_close(SocketDesc);
         SocketDesc = -1;
         return;
      }
      for(size_t i = 0; i < (size_t)r; i++) {
         if(command[cmdpos] == '\r') {
            command[cmdpos] = 0x00;
            finished = true;
            break;
         }
         cmdpos++;
      }
   }

   cout << "Command: ";
   safePrint(cout, command, cmdpos);
   cout << endl;

   // ====== Execute HTTP GET command =====================================
   ssize_t result = 0;
   if(strncasecmp(command, "GET ", 4) == 0) {
      std::string fileName = std::string((const char*)&command[4]);
      fileName = fileName.substr(0, fileName.find(' '));   // Remove <space>HTTP/1.x
      while(fileName[0] == '/') {                          // No absolute paths!
         fileName.erase(0, 1);
      }
      if(fileName == "") {   // No file name -> index.html
         fileName = "index.html";
      }

      if(fileName[0] != '.') {   // No access to top-level directories!
         cout << "Thread " << ID << ": Trying to upload file \""
              << fileName << "\"..." << endl;
         ifstream is(fileName.c_str(), ios::binary);
         if(is.good()) {
            const char* status = "HTTP/1.0 200 OK\r\n\r\n";
            result = nsa_write(SocketDesc, status, strlen(status));

            char str[8192];
            streamsize s = is.rdbuf()->sgetn(str, sizeof(str));
            while((s > 0) && (result > 0)) {
               result = nsa_write(SocketDesc, str, s);
               s = is.rdbuf()->sgetn(str, sizeof(str));
            }
         }
         else {
            cout << "Thread " << ID << ": File <" << fileName << "> not found!" << endl;
            const char* status = "HTTP/1.0 404 Not Found\r\n\r\n404 Not Found\r\n";
            result = nsa_write(SocketDesc, status, strlen(status));
         }
      }
      else {
         cout << "Thread " << ID << ": Request for . or .. not acceptable!" << endl;
         const char* status = "HTTP/1.0 406 Not Acceptable\r\n\r\n406 Not Acceptable\r\n";
         result = nsa_write(SocketDesc, status, strlen(status));
      }
   }
   else {
      cout << "Thread " << ID << ": Bad request!" << endl;
      const char* status = "HTTP/1.0 400 Bad Request\r\n\r\n400 Bad Request\r\n";
      result = nsa_write(SocketDesc, status, strlen(status));
   }

   // ====== Shutdown connection ==========================================
   nsa_shutdown(SocketDesc, SHUT_RDWR);
   nsa_close(SocketDesc);
   SocketDesc = -1;
}

class ServiceThreadList
{
   public:
   ServiceThreadList();
   ~ServiceThreadList();
   void add(ServiceThread* thread);
   void remove(ServiceThread* thread);
   void removeFinished();
   void removeAll();

   private:
   struct ThreadListEntry {
      ThreadListEntry* Next;
      ServiceThread*   Object;
   };
   ThreadListEntry* ThreadList;
};

ServiceThreadList::ServiceThreadList()
{
   ThreadList = NULL;
}

ServiceThreadList::~ServiceThreadList()
{
   removeAll();
}

void ServiceThreadList::removeFinished()
{
   ThreadListEntry* entry = ThreadList;
   while(entry != NULL) {
      ThreadListEntry* next = entry->Next;
      if(entry->Object->hasFinished()) {
         remove(entry->Object);
      }
      entry = next;
   }
}

void ServiceThreadList::removeAll()
{
   ThreadListEntry* entry = ThreadList;
   while(entry != NULL) {
      remove(entry->Object);
      entry = ThreadList;
   }
}

void ServiceThreadList::add(ServiceThread* thread)
{
   ThreadListEntry* entry = new ThreadListEntry;
   entry->Next   = ThreadList;
   entry->Object = thread;
   ThreadList    = entry;
}

void ServiceThreadList::remove(ServiceThread* thread)
{
   ThreadListEntry* entry = ThreadList;
   ThreadListEntry* prev  = NULL;
   while(entry != NULL) {
      if(entry->Object == thread) {
         if(prev == NULL) {
            ThreadList = entry->Next;
         }
         else {
            prev->Next = entry->Next;
         }
         delete entry->Object;
         entry->Object = NULL;
         delete entry;
         return;
      }
      prev  = entry;
      entry = entry->Next;
   }
}

int ServerSocket = -1;

void intHandler(int signum)
{
   if(ServerSocket >= 0) {
      fputs("*** Ctrl-C ***\n", stderr);
      nsa_close(ServerSocket);
      ServerSocket = -1;
   }
}

int main(int argc, char** argv)
{
   if(argc < 2) {
      cerr << "Usage: " << argv[0] << " [Port]" << endl;
      exit(1);
   }

   // ====== Get remote address (resolve hostname and service if necessary) ==
   struct addrinfo* ainfo = NULL;
   struct addrinfo  ainfohint;
   memset((char*)&ainfohint, 0, sizeof(ainfohint));
   // AI_PASSIVE will set address to the ANY address.
   ainfohint.ai_flags    = AI_PASSIVE;
   ainfohint.ai_family   = AF_UNSPEC;
   ainfohint.ai_socktype = SOCK_STREAM;
   ainfohint.ai_protocol = IPPROTO_TCP;
   int error = getaddrinfo(NULL, argv[1], &ainfohint, &ainfo);
   if(error != 0) {
      cerr << "ERROR: getaddrinfo() failed: " << gai_strerror(error) << endl;
      exit(1);
   }

   // ====== Create socket of appropriate type ===============================
   ServerSocket = nsa_socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol, properties);
   if(ServerSocket <= 0) {
      perror("nsa_socket() call failed");
      exit(1);
   }

   // ====== Bind to local port ==============================================
   if(nsa_bind(ServerSocket, ainfo->ai_addr, ainfo->ai_addrlen) < 0) {
      perror("nsa_bind() call failed");
      exit(1);
   }

   // ====== Turn socket into "listen" mode ==================================
   if(nsa_listen(ServerSocket, 10) < 0) {
      perror("nsa_listen() call failed");
   }

   // ====== Install SIGINT handler ==========================================
   signal(SIGINT, &intHandler);

   // ====== Print information ===============================================
   char localHost[512];
   char localService[128];
   error = getnameinfo(ainfo->ai_addr, ainfo->ai_addrlen,
                       (char*)&localHost, sizeof(localHost),
                       (char*)&localService, sizeof(localService),
                       NI_NUMERICHOST);
   if(error != 0) {
      cerr << "ERROR: getnameinfo() failed: " << gai_strerror(error) << endl;
      exit(1);
   }
   cout << "Waiting for requests at address "
        << localHost << ", service " << localService << "..." << endl;

   // ====== Handle requests =================================================
   ServiceThreadList stl;
   for(;;) {
      // ====== Accept connection ============================================
      sockaddr_storage remoteAddress;
      socklen_t        remoteAddressLength = sizeof(remoteAddress);
      const int        newSD = nsa_accept(ServerSocket, (sockaddr*)&remoteAddress, &remoteAddressLength);
      if(newSD < 0) {
         break;
      }

      // ====== Delete finished threads ======================================
      stl.removeFinished();

      // ====== Print information ============================================
      char remoteHost[512];
      char remoteService[128];
      error = getnameinfo((sockaddr*)&remoteAddress, remoteAddressLength,
                          (char*)&remoteHost, sizeof(remoteHost),
                          (char*)&remoteService, sizeof(remoteService),
                          NI_NUMERICHOST);
      if(error != 0) {
         cerr << "ERROR: getnameinfo() failed: " << gai_strerror(error) << endl;
         exit(1);
      }
      cout << "Got connection from "
           << remoteHost << ", service " << remoteService << ":" << endl;

      // ====== Start new service thread =====================================
      stl.add(new ServiceThread(newSD));
   }

   // ====== Clean up ========================================================
   stl.removeAll();
   freeaddrinfo(ainfo);
   if(ServerSocket >= 0) {
      nsa_close(ServerSocket);
   }
   nsa_cleanup();

   cout << endl << "Terminated!" << endl;
   return(0);
}
<|endoftext|>


<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "extproc/http_runner.hpp"

#include "extproc/http_job.hpp"
#include "containers/archive/stl_types.hpp"
#include "arch/timing.hpp"

RDB_IMPL_ME_SERIALIZABLE_3(http_opts_t::http_auth_t, 0, type, username, password);
RDB_IMPL_ME_SERIALIZABLE_14(http_opts_t, 0, auth, method, result_format, url,
                            proxy, url_params, header, data, form_data, timeout_ms,
                            attempts, max_redirects, depaginate, verify);

std::string http_method_to_str(http_method_t method) {
    switch(method) {
    case http_method_t::GET:    return std::string("GET");
    case http_method_t::HEAD:   return std::string("HEAD");
    case http_method_t::POST:   return std::string("POST");
    case http_method_t::PUT:    return std::string("PUT");
    case http_method_t::PATCH:  return std::string("PATCH");
    case http_method_t::DELETE: return std::string("DELETE");
    default:                    return std::string("UNKNOWN");
    }
}

http_opts_t::http_opts_t() :
    auth(),
    method(http_method_t::GET),
    result_format(http_result_format_t::AUTO),
    proxy(),
    url(),
    url_params(),
    header(),
    data(),
    form_data(),
    timeout_ms(30000),
    attempts(5),
    max_redirects(0),
    depaginate(false),
    verify(true) { }

http_opts_t::http_auth_t::http_auth_t() :
    type(http_auth_type_t::NONE),
    username(),
    password() { }

void http_opts_t::http_auth_t::make_basic_auth(std::string &&user,
                                               std::string &&pass) {
    type = http_auth_type_t::BASIC;
    username.assign(std::move(user));
    password.assign(std::move(pass));
}

void http_opts_t::http_auth_t::make_digest_auth(std::string &&user,
                                                std::string &&pass) {
    type = http_auth_type_t::DIGEST;
    username.assign(std::move(user));
    password.assign(std::move(pass));
}

http_runner_t::http_runner_t(extproc_pool_t *_pool) :
    pool(_pool) { }

http_result_t http_runner_t::http(const http_opts_t *opts,
                                  signal_t *interruptor) {
    signal_timer_t timeout;
    wait_any_t combined_interruptor(interruptor, &timeout);
    http_job_t job(pool, &combined_interruptor);

    assert_thread();
    timeout.start(opts->timeout_ms);

    try {
        return job.http(opts);
    } catch (...) {
        // This will mark the worker as errored so we don't try to re-sync with it
        //  on the next line (since we're in a catch statement, we aren't allowed)
        job.worker_error();
        throw;
    }
}

<commit_msg>setting default user agent to 'RethinkDB'<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "extproc/http_runner.hpp"

#include "extproc/http_job.hpp"
#include "containers/archive/stl_types.hpp"
#include "arch/timing.hpp"

RDB_IMPL_ME_SERIALIZABLE_3(http_opts_t::http_auth_t, 0, type, username, password);
RDB_IMPL_ME_SERIALIZABLE_14(http_opts_t, 0, auth, method, result_format, url,
                            proxy, url_params, header, data, form_data, timeout_ms,
                            attempts, max_redirects, depaginate, verify);

std::string http_method_to_str(http_method_t method) {
    switch(method) {
    case http_method_t::GET:    return std::string("GET");
    case http_method_t::HEAD:   return std::string("HEAD");
    case http_method_t::POST:   return std::string("POST");
    case http_method_t::PUT:    return std::string("PUT");
    case http_method_t::PATCH:  return std::string("PATCH");
    case http_method_t::DELETE: return std::string("DELETE");
    default:                    return std::string("UNKNOWN");
    }
}

http_opts_t::http_opts_t() :
    auth(),
    method(http_method_t::GET),
    result_format(http_result_format_t::AUTO),
    proxy(),
    url(),
    url_params(),
    header(),
    data(),
    form_data(),
    timeout_ms(30000),
    attempts(5),
    max_redirects(0),
    depaginate(false),
    verify(true)
{
    header.push_back(strprintf("User-Agent: %s/%s",
                               SOFTWARE_NAME_STRING,
                               RETHINKDB_VERSION));
}

http_opts_t::http_auth_t::http_auth_t() :
    type(http_auth_type_t::NONE),
    username(),
    password() { }

void http_opts_t::http_auth_t::make_basic_auth(std::string &&user,
                                               std::string &&pass) {
    type = http_auth_type_t::BASIC;
    username.assign(std::move(user));
    password.assign(std::move(pass));
}

void http_opts_t::http_auth_t::make_digest_auth(std::string &&user,
                                                std::string &&pass) {
    type = http_auth_type_t::DIGEST;
    username.assign(std::move(user));
    password.assign(std::move(pass));
}

http_runner_t::http_runner_t(extproc_pool_t *_pool) :
    pool(_pool) { }

http_result_t http_runner_t::http(const http_opts_t *opts,
                                  signal_t *interruptor) {
    signal_timer_t timeout;
    wait_any_t combined_interruptor(interruptor, &timeout);
    http_job_t job(pool, &combined_interruptor);

    assert_thread();
    timeout.start(opts->timeout_ms);

    try {
        return job.http(opts);
    } catch (...) {
        // This will mark the worker as errored so we don't try to re-sync with it
        //  on the next line (since we're in a catch statement, we aren't allowed)
        job.worker_error();
        throw;
    }
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2002-2004 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "base/misc.hh"
#include "dev/pktfifo.hh"

using namespace std;

void
PacketFifo::serialize(const string &base, ostream &os)
{
    paramOut(os, base + ".size", _size);
    paramOut(os, base + ".maxsize", _maxsize);
    paramOut(os, base + ".reserved", _reserved);
    paramOut(os, base + ".packets", fifo.size());

    int i = 0;
    std::list<PacketPtr>::iterator p = fifo.begin();
    std::list<PacketPtr>::iterator end = fifo.end();
    while (p != end) {
        (*p)->serialize(csprintf("%s.packet%d", base, i), os);
        ++p;
        ++i;
    }
}

void
PacketFifo::unserialize(const string &base, Checkpoint *cp,
                        const string &section)
{
    paramIn(cp, section, base + ".size", _size);
    paramIn(cp, section, base + ".maxsize", _maxsize);
    paramIn(cp, section, base + ".reserved", _reserved);
    int fifosize;
    paramIn(cp, section, base + ".packets", fifosize);

    fifo.clear();

    for (int i = 0; i < fifosize; ++i) {
        PacketPtr p = new PacketData(16384);
        p->unserialize(csprintf("%s.packet%d", base, i), cp, section);
        fifo.push_back(p);
    }
}
<commit_msg>Fix annoying bug that lead to dropped packets in the P4 system<commit_after>/*
 * Copyright (c) 2002-2004 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "base/misc.hh"
#include "dev/pktfifo.hh"

using namespace std;

void
PacketFifo::serialize(const string &base, ostream &os)
{
    paramOut(os, base + ".size", _size);
    paramOut(os, base + ".maxsize", _maxsize);
    paramOut(os, base + ".reserved", _reserved);
    paramOut(os, base + ".packets", fifo.size());

    int i = 0;
    std::list<PacketPtr>::iterator p = fifo.begin();
    std::list<PacketPtr>::iterator end = fifo.end();
    while (p != end) {
        (*p)->serialize(csprintf("%s.packet%d", base, i), os);
        ++p;
        ++i;
    }
}

void
PacketFifo::unserialize(const string &base, Checkpoint *cp,
                        const string &section)
{
    paramIn(cp, section, base + ".size", _size);
//  paramIn(cp, section, base + ".maxsize", _maxsize);
    paramIn(cp, section, base + ".reserved", _reserved);
    int fifosize;
    paramIn(cp, section, base + ".packets", fifosize);

    fifo.clear();

    for (int i = 0; i < fifosize; ++i) {
        PacketPtr p = new PacketData(16384);
        p->unserialize(csprintf("%s.packet%d", base, i), cp, section);
        fifo.push_back(p);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <cstddef>
#include <cstdint>

#if defined(__i386__) || defined(__arm__)

extern "C" int64_t __udivmoddi4(uint64_t u, uint64_t v, uint64_t* rp);

extern "C" int64_t __wrap___divmoddi4(int64_t u, int64_t v, int64_t* rp)
{
    int32_t c1 = 0, c2 = 0;
    int64_t uu = u, vv = v;
    int64_t w;
    int64_t r;

    if (uu < 0) {
        c1 = ~c1, c2 = ~c2, uu = -uu;
    }
    if (vv < 0) {
        c1 = ~c1, vv = -vv;
    }

    w = __udivmoddi4(uu, vv, (uint64_t*)&r);
    if (c1)
        w = -w;
    if (c2)
        r = -r;

    *rp = r;
    return w;
}
#endif

extern "C" float log2f_old(float x);
#ifdef __i386__
__asm(".symver log2f_old,log2f@GLIBC_2.1");
#elif defined(__amd64__)
__asm(".symver log2f_old,log2f@GLIBC_2.2.5");
#elif defined(__arm__)
__asm(".symver log2f_old,log2f@GLIBC_2.4");
#elif defined(__aarch64__)
__asm(".symver log2f_old,log2f@GLIBC_2.17");
#elif defined(__powerpc64__)
#  ifdef WORDS_BIGENDIAN
__asm(".symver log2f_old,log2f@GLIBC_2.3");
#  else
__asm(".symver log2f_old,log2f@GLIBC_2.17");
#  endif
#elif defined(__riscv)
__asm(".symver log2f_old,log2f@GLIBC_2.27");
#endif
extern "C" float __wrap_log2f(float x)
{
    return log2f_old(x);
}
<commit_msg>compat: remove glibc_compat.cpp<commit_after><|endoftext|>


<commit_before>#include "StdAfx.h"
#include "Rw2Decoder.h"

/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/
namespace RawSpeed {

Rw2Decoder::Rw2Decoder(TiffIFD *rootIFD, FileMap* file) :
    RawDecoder(file), mRootIFD(rootIFD), input_start(0) {
      decoderVersion = 1;
}
Rw2Decoder::~Rw2Decoder(void) {
  if (input_start)
    delete input_start;
  input_start = 0;
}

RawImage Rw2Decoder::decodeRaw() {

  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(PANASONIC_STRIPOFFSET);

  bool isOldPanasonic = FALSE;

  if (data.empty()) {
    if (!mRootIFD->hasEntryRecursive(STRIPOFFSETS))
      ThrowRDE("RW2 Decoder: No image data found");
    isOldPanasonic = TRUE;
    data = mRootIFD->getIFDsWithTag(STRIPOFFSETS);
  }

  TiffIFD* raw = data[0];
  uint32 height = raw->getEntry((TiffTag)3)->getShort();
  uint32 width = raw->getEntry((TiffTag)2)->getShort();

  mRaw->dim = iPoint2D(width, height);
  mRaw->bpp = 2;
  mRaw->createData();

  if (isOldPanasonic) {
    TiffEntry *offsets = raw->getEntry(STRIPOFFSETS);
    TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS);

    if (offsets->count != 1) {
      ThrowRDE("RW2 Decoder: Multiple Strips found: %u", offsets->count);
    }
    int off = offsets->getInt();
    if (!mFile->isValid(off))
      ThrowRDE("Panasonic RAW Decoder: Invalid image data offset, cannot decode.");

    int count = counts->getInt();
    if (count != width*height*2)
      ThrowRDE("Panasonic RAW Decoder: Byte count is wrong.");

    ByteStream input_start(mFile->getData(off), mFile->getSize() - off);
    iPoint2D pos(0, 0);
    readUncompressedRaw(input_start, mRaw->dim,pos, width*2, 16, FALSE);

  } else {

    TiffEntry *offsets = raw->getEntry(PANASONIC_STRIPOFFSET);

    if (offsets->count != 1) {
      ThrowRDE("RW2 Decoder: Multiple Strips found: %u", offsets->count);
    }

    load_flags = 0x2008;
    int off = offsets->getInt();

    if (!mFile->isValid(off))
      ThrowRDE("RW2 Decoder: Invalid image data offset, cannot decode.");

    input_start = new ByteStream(mFile->getData(off), mFile->getSize() - off);
    DecodeRw2();
  }
  return mRaw;
}

void Rw2Decoder::DecodeRw2() {
  startThreads();
}

void Rw2Decoder::decodeThreaded(RawDecoderThread * t) {
  int x, i, j, sh = 0, pred[2], nonz[2];
  int w = mRaw->dim.x / 14;
  uint32 y;

  /* 9 + 1/7 bits per pixel */
  int skip = w * 14 * t->start_y * 9;
  skip += w * 2 * t->start_y;
  skip /= 8;

  PanaBitpump bits(new ByteStream(input_start));
  bits.load_flags = load_flags;
  bits.skipBytes(skip);

  for (y = t->start_y; y < t->end_y; y++) {
    ushort16* dest = (ushort16*)mRaw->getData(0, y);
    for (x = 0; x < w; x++) {
      pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
      for (i = 0; i < 14; i++) {
        // Even pixels
        if (i % 3 == 2)
          sh = 4 >> (3 - bits.getBits(2));
        if (nonz[0]) {
          if ((j = bits.getBits(8))) {
            if ((pred[0] -= 0x80 << sh) < 0 || sh == 4)
              pred[0] &= ~(-1 << sh);
            pred[0] += j << sh;
          }
        } else if ((nonz[0] = bits.getBits(8)) || i > 11)
          pred[0] = nonz[0] << 4 | bits.getBits(4);
        *dest++ = pred[0];

        // Odd pixels
        i++;
        if (i % 3 == 2)
          sh = 4 >> (3 - bits.getBits(2));
        if (nonz[1]) {
          if ((j = bits.getBits(8))) {
            if ((pred[1] -= 0x80 << sh) < 0 || sh == 4)
              pred[1] &= ~(-1 << sh);
            pred[1] += j << sh;
          }
        } else if ((nonz[1] = bits.getBits(8)) || i > 11)
          pred[1] = nonz[1] << 4 | bits.getBits(4);
        *dest++ = pred[1];
      }
    }
  }
}

void Rw2Decoder::checkSupport(CameraMetaData *meta) {
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);
  if (data.empty())
    ThrowRDE("RW2 Support check: Model name found");

  string make = data[0]->getEntry(MAKE)->getString();
  string model = data[0]->getEntry(MODEL)->getString();
  this->checkCameraSupported(meta, make, model, getMode(model));
}

void Rw2Decoder::decodeMetaData(CameraMetaData *meta) {
  mRaw->cfa.setCFA(CFA_BLUE, CFA_GREEN, CFA_GREEN2, CFA_RED);
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);

  if (data.empty())
    ThrowRDE("CR2 Meta Decoder: Model name not found");

  string make = data[0]->getEntry(MAKE)->getString();
  string model = data[0]->getEntry(MODEL)->getString();
  string mode = getMode(model);

  setMetaData(meta, make, model, mode);
}

bool Rw2Decoder::almostEqualRelative(float A, float B, float maxRelativeError) {
  if (A == B)
    return true;

  float relativeError = fabs((A - B) / B);
  if (relativeError <= maxRelativeError)
    return true;
  return false;
}

std::string Rw2Decoder::getMode(const string model) {
  float ratio = 3.0f / 2.0f;  // Default
  if (mRaw->isAllocated()) {
    ratio = (float)mRaw->dim.x / (float)mRaw->dim.y;
  }

  if (almostEqualRelative(ratio, 16.0f / 9.0f, 0.02f))
    return "16:9";
  if (almostEqualRelative(ratio, 3.0f / 2.0f, 0.02f))
    return "3:2";
  if (almostEqualRelative(ratio, 4.0f / 3.0f, 0.02f))
    return "4:3";
  if (almostEqualRelative(ratio, 1.0f, 0.02f))
    return "1:1";

  return "";
}

PanaBitpump::PanaBitpump(ByteStream* _input) : input(_input), vbits(0) {
}

PanaBitpump::~PanaBitpump() {
  if (input)
    delete input;
  input = 0;
}

void PanaBitpump::skipBytes(int bytes) {
  int blocks = (bytes / 0x4000) * 0x4000;
  input->skipBytes(blocks);
  for (int i = blocks; i < bytes; i++)
    getBits(8);
}

uint32 PanaBitpump::getBits(int nbits) {
  int byte;

  if (!vbits) {
    /* On truncated files this routine will just return just for the truncated
    * part of the file. Since there is no chance of affecting output buffer
    * size we allow the decoder to decode this
    */
    if (input->getRemainSize() < 0x4000 - load_flags) {
      memcpy(buf + load_flags, input->getData(), input->getRemainSize());
      input->skipBytes(input->getRemainSize());
    } else {
      memcpy(buf + load_flags, input->getData(), 0x4000 - load_flags);
      input->skipBytes(0x4000 - load_flags);
      if (input->getRemainSize() < load_flags) {
        memcpy(buf, input->getData(), input->getRemainSize());
        input->skipBytes(input->getRemainSize());
      } else {
        memcpy(buf, input->getData(), load_flags);
        input->skipBytes(load_flags);
      }
    }
  }
  vbits = (vbits - nbits) & 0x1ffff;
  byte = vbits >> 3 ^ 0x3ff0;
  return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits);
}

} // namespace RawSpeed
<commit_msg>Fix GCC warning.<commit_after>#include "StdAfx.h"
#include "Rw2Decoder.h"

/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/
namespace RawSpeed {

Rw2Decoder::Rw2Decoder(TiffIFD *rootIFD, FileMap* file) :
    RawDecoder(file), mRootIFD(rootIFD), input_start(0) {
      decoderVersion = 1;
}
Rw2Decoder::~Rw2Decoder(void) {
  if (input_start)
    delete input_start;
  input_start = 0;
}

RawImage Rw2Decoder::decodeRaw() {

  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(PANASONIC_STRIPOFFSET);

  bool isOldPanasonic = FALSE;

  if (data.empty()) {
    if (!mRootIFD->hasEntryRecursive(STRIPOFFSETS))
      ThrowRDE("RW2 Decoder: No image data found");
    isOldPanasonic = TRUE;
    data = mRootIFD->getIFDsWithTag(STRIPOFFSETS);
  }

  TiffIFD* raw = data[0];
  uint32 height = raw->getEntry((TiffTag)3)->getShort();
  uint32 width = raw->getEntry((TiffTag)2)->getShort();

  mRaw->dim = iPoint2D(width, height);
  mRaw->bpp = 2;
  mRaw->createData();

  if (isOldPanasonic) {
    TiffEntry *offsets = raw->getEntry(STRIPOFFSETS);
    TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS);

    if (offsets->count != 1) {
      ThrowRDE("RW2 Decoder: Multiple Strips found: %u", offsets->count);
    }
    int off = offsets->getInt();
    if (!mFile->isValid(off))
      ThrowRDE("Panasonic RAW Decoder: Invalid image data offset, cannot decode.");

    int count = counts->getInt();
    if (count != (int)(width*height*2))
      ThrowRDE("Panasonic RAW Decoder: Byte count is wrong.");

    ByteStream input_start(mFile->getData(off), mFile->getSize() - off);
    iPoint2D pos(0, 0);
    readUncompressedRaw(input_start, mRaw->dim,pos, width*2, 16, FALSE);

  } else {

    TiffEntry *offsets = raw->getEntry(PANASONIC_STRIPOFFSET);

    if (offsets->count != 1) {
      ThrowRDE("RW2 Decoder: Multiple Strips found: %u", offsets->count);
    }

    load_flags = 0x2008;
    int off = offsets->getInt();

    if (!mFile->isValid(off))
      ThrowRDE("RW2 Decoder: Invalid image data offset, cannot decode.");

    input_start = new ByteStream(mFile->getData(off), mFile->getSize() - off);
    DecodeRw2();
  }
  return mRaw;
}

void Rw2Decoder::DecodeRw2() {
  startThreads();
}

void Rw2Decoder::decodeThreaded(RawDecoderThread * t) {
  int x, i, j, sh = 0, pred[2], nonz[2];
  int w = mRaw->dim.x / 14;
  uint32 y;

  /* 9 + 1/7 bits per pixel */
  int skip = w * 14 * t->start_y * 9;
  skip += w * 2 * t->start_y;
  skip /= 8;

  PanaBitpump bits(new ByteStream(input_start));
  bits.load_flags = load_flags;
  bits.skipBytes(skip);

  for (y = t->start_y; y < t->end_y; y++) {
    ushort16* dest = (ushort16*)mRaw->getData(0, y);
    for (x = 0; x < w; x++) {
      pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
      for (i = 0; i < 14; i++) {
        // Even pixels
        if (i % 3 == 2)
          sh = 4 >> (3 - bits.getBits(2));
        if (nonz[0]) {
          if ((j = bits.getBits(8))) {
            if ((pred[0] -= 0x80 << sh) < 0 || sh == 4)
              pred[0] &= ~(-1 << sh);
            pred[0] += j << sh;
          }
        } else if ((nonz[0] = bits.getBits(8)) || i > 11)
          pred[0] = nonz[0] << 4 | bits.getBits(4);
        *dest++ = pred[0];

        // Odd pixels
        i++;
        if (i % 3 == 2)
          sh = 4 >> (3 - bits.getBits(2));
        if (nonz[1]) {
          if ((j = bits.getBits(8))) {
            if ((pred[1] -= 0x80 << sh) < 0 || sh == 4)
              pred[1] &= ~(-1 << sh);
            pred[1] += j << sh;
          }
        } else if ((nonz[1] = bits.getBits(8)) || i > 11)
          pred[1] = nonz[1] << 4 | bits.getBits(4);
        *dest++ = pred[1];
      }
    }
  }
}

void Rw2Decoder::checkSupport(CameraMetaData *meta) {
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);
  if (data.empty())
    ThrowRDE("RW2 Support check: Model name found");

  string make = data[0]->getEntry(MAKE)->getString();
  string model = data[0]->getEntry(MODEL)->getString();
  this->checkCameraSupported(meta, make, model, getMode(model));
}

void Rw2Decoder::decodeMetaData(CameraMetaData *meta) {
  mRaw->cfa.setCFA(CFA_BLUE, CFA_GREEN, CFA_GREEN2, CFA_RED);
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);

  if (data.empty())
    ThrowRDE("CR2 Meta Decoder: Model name not found");

  string make = data[0]->getEntry(MAKE)->getString();
  string model = data[0]->getEntry(MODEL)->getString();
  string mode = getMode(model);

  setMetaData(meta, make, model, mode);
}

bool Rw2Decoder::almostEqualRelative(float A, float B, float maxRelativeError) {
  if (A == B)
    return true;

  float relativeError = fabs((A - B) / B);
  if (relativeError <= maxRelativeError)
    return true;
  return false;
}

std::string Rw2Decoder::getMode(const string model) {
  float ratio = 3.0f / 2.0f;  // Default
  if (mRaw->isAllocated()) {
    ratio = (float)mRaw->dim.x / (float)mRaw->dim.y;
  }

  if (almostEqualRelative(ratio, 16.0f / 9.0f, 0.02f))
    return "16:9";
  if (almostEqualRelative(ratio, 3.0f / 2.0f, 0.02f))
    return "3:2";
  if (almostEqualRelative(ratio, 4.0f / 3.0f, 0.02f))
    return "4:3";
  if (almostEqualRelative(ratio, 1.0f, 0.02f))
    return "1:1";

  return "";
}

PanaBitpump::PanaBitpump(ByteStream* _input) : input(_input), vbits(0) {
}

PanaBitpump::~PanaBitpump() {
  if (input)
    delete input;
  input = 0;
}

void PanaBitpump::skipBytes(int bytes) {
  int blocks = (bytes / 0x4000) * 0x4000;
  input->skipBytes(blocks);
  for (int i = blocks; i < bytes; i++)
    getBits(8);
}

uint32 PanaBitpump::getBits(int nbits) {
  int byte;

  if (!vbits) {
    /* On truncated files this routine will just return just for the truncated
    * part of the file. Since there is no chance of affecting output buffer
    * size we allow the decoder to decode this
    */
    if (input->getRemainSize() < 0x4000 - load_flags) {
      memcpy(buf + load_flags, input->getData(), input->getRemainSize());
      input->skipBytes(input->getRemainSize());
    } else {
      memcpy(buf + load_flags, input->getData(), 0x4000 - load_flags);
      input->skipBytes(0x4000 - load_flags);
      if (input->getRemainSize() < load_flags) {
        memcpy(buf, input->getData(), input->getRemainSize());
        input->skipBytes(input->getRemainSize());
      } else {
        memcpy(buf, input->getData(), load_flags);
        input->skipBytes(load_flags);
      }
    }
  }
  vbits = (vbits - nbits) & 0x1ffff;
  byte = vbits >> 3 ^ 0x3ff0;
  return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits);
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include <iostream>
#include <sstream>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkPSMEntropyMixedEffectsModelFilter.h"
#include "itkPSMProjectReader.h"
#include "itkCommand.h"

namespace itk{

class MyMixedEffectsIterationCommand : public itk::Command
{
public:
 /** Standard class typedefs. */
  typedef MyMixedEffectsIterationCommand         Self;
  typedef Command                    Superclass;
  typedef SmartPointer< Self >       Pointer;
  typedef SmartPointer< const Self > ConstPointer;

  typedef Image<float, 3> ImageType;

  /** Run-time type information (and related methods). */
  itkTypeMacro(MyMixedEffectsIterationCommand, Command);

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** This method will be passed a PSMGradientDescentOptimizer */
  virtual void Execute(Object *caller, const EventObject &)
  {
    PSMEntropyMixedEffectsModelFilter<ImageType> *o
      = static_cast<PSMEntropyMixedEffectsModelFilter<ImageType> *>(caller);

    // Print every 10 iterations
    //    if (o->GetNumberOfElapsedIterations() % 10 != 0) return;

    std::cout << "Iteration # " << o->GetNumberOfElapsedIterations() << std::endl;
    std::cout << " Eigenmode variances: ";
    for (unsigned int i = 0; i < o->GetShapePCAVariances().size(); i++)
      {
        std::cout << o->GetShapePCAVariances()[i] << " ";
      }
    std::cout << std::endl;
    std::cout << " Regularization = " << o->GetRegularizationConstant() << std::endl;
  }
  virtual void Execute(const Object *, const EventObject &)
  {
    std::cout << "SHOULDN'T BE HERE" << std::endl;
  }

protected:
  MyMixedEffectsIterationCommand() {}
  ~MyMixedEffectsIterationCommand() {}
private:
  MyMixedEffectsIterationCommand(const Self &);        //purposely not implemented
  void operator=(const Self &); //purposely not implemented
};

} // end namespace itk

/** This test exercises functionality of the base itkPSMEntropyMixedEffectsModelFilter class */
int itkPSMEntropyMixedEffectsModelFilterTest(int argc, char* argv[] )
{
  bool passed = true;
  std::string errstring = "";
  std::string output_path = "";
  std::string input_path_prefix = "";

  // Check for proper arguments
  if (argc < 2)
    {
      std::cout << "Wrong number of arguments. \nUse: "
	<< "itkPSMEntropyMixedEffectsModelFilterTest parameter_file [output_path] [input_path]\n"
        << "See itk::PSMParameterFileReader for documentation on the parameter file format."
	<< std::endl;
      return EXIT_FAILURE;
    }

  if (argc >2)
    {
      output_path = std::string(argv[2]);
    }

  if (argc >3)
    {
      input_path_prefix = std::string(argv[3]);
    }

  typedef itk::Image<float, 3> ImageType;

  try
    {
     // Read the project parameters
     itk::PSMProjectReader::Pointer xmlreader =
       itk::PSMProjectReader::New();
     xmlreader->SetFileName(argv[1]);
     xmlreader->Update();

     itk::PSMProject::Pointer project = xmlreader->GetOutput();

     // Create the modeling filter and set up the optimization.
     itk::PSMEntropyMixedEffectsModelFilter<ImageType>::Pointer P
       = itk::PSMEntropyMixedEffectsModelFilter<ImageType>::New();

     // Setup the Callback function that is executed after each
     // iteration of the solver.
     itk::MyMixedEffectsIterationCommand::Pointer mycommand = itk::MyMixedEffectsIterationCommand::New();
     P->AddObserver(itk::IterationEvent(), mycommand);

     // Load the distance transforms
     const std::vector<std::string> &dt_files = project->GetDistanceTransforms();
     std::cout << "Reading distance transforms ..." << std::endl;
     for (unsigned int i = 0; i < dt_files.size(); i++)
       {
         itk::ImageFileReader<ImageType>::Pointer reader =
           itk::ImageFileReader<ImageType>::New();
         reader->SetFileName(input_path_prefix + dt_files[i]);
         reader->Update();

         std::cout << "  " << (input_path_prefix + dt_files[i]) << std::endl;

         P->SetInput(i,reader->GetOutput());
       }
     std::cout << "Done!" << std::endl;

     // Load the model initialization.  It should be specified as a model with a name.
     const std::vector<std::string> &pt_files = project->GetModel(std::string("initialization"));
     std::cout << "Reading the initial model correspondences ..." << std::endl;
     for (unsigned int i = 0; i < pt_files.size(); i++)
       {
         // Read the points for this file and add as a list
         std::vector<itk::PSMEntropyMixedEffectsModelFilter<ImageType>::PointType> c;

         int counter = 0;
         // Open the ascii file.
         std::ifstream in( (input_path_prefix + pt_files[i]).c_str() );
         if ( !in )
           {
             errstring += "Could not open point file for input.";
             passed = false;
             break;
           }

         // Read all of the points, one point per line.
         while (in)
           {
             itk::PSMEntropyMixedEffectsModelFilter<ImageType>::PointType pt;

             for (unsigned int d = 0; d < 3; d++)
               {
                 in >> pt[d];
               }
             c.push_back(pt);
             counter++;
           }
         // this algorithm pushes the last point twice
         c.pop_back();
         //  std::cout << "Read " << counter-1 << " points. " << std::endl;
         in.close();

         P->SetInputCorrespondencePoints(i,c);

         std::cout << "  " << pt_files[i] << std::endl;
       }
     std::cout << "Done!" << std::endl;

     // Read the explanatory variables (e.g. time)
     if (project->HasVariables("explanatory_variables"))
       {
         std::vector<double> expl = project->GetVariables("explanatory_variables");

         if (expl.size() < dt_files.size())
           {
             errstring += "There are fewer explanatory variables than input files";
             passed = false;
           }
         else // set the explanatory variables
           {std::cout << "Setting variables" << std::endl;
             P->SetVariables(expl);
           }
       }
     else
       {
         errstring += "No explanatory variables were present for the regression.";
         passed = false;
       }

     //  Read some parameters from the file or provide defaults
     double regularization_initial   = 100.0f;
     double regularization_final     = 5.0f;
     double regularization_decayspan = 2000.0f;
     double tolerance                = 1.0e-8;
     unsigned int maximum_iterations = 20000;
     unsigned int num_individuals = 1;

     if ( project->HasOptimizationAttribute("regularization_initial") )
       regularization_initial = project->GetOptimizationAttribute("regularization_initial");
     if ( project->HasOptimizationAttribute("regularization_final") )
       regularization_final = project->GetOptimizationAttribute("regularization_final");
     if ( project->HasOptimizationAttribute("regularization_decayspan") )
       regularization_decayspan = project->GetOptimizationAttribute("regularization_decayspan");
     if ( project->HasOptimizationAttribute("tolerance") )
       tolerance = project->GetOptimizationAttribute("tolerance");
     if ( project->HasOptimizationAttribute("maximum_iterations") )
       maximum_iterations = static_cast<unsigned int>(project->GetOptimizationAttribute("maximum_iterations"));
     if ( project->HasOptimizationAttribute("num_individuals") )
        num_individuals = static_cast<unsigned int>(project->GetOptimizationAttribute("num_individuals"));

     std::cout << "Optimization parameters: " << std::endl;
     std::cout << "    regularization_initial = " << regularization_initial << std::endl;
     std::cout << "      regularization_final = " << regularization_final << std::endl;
     std::cout << "  regularization_decayspan = " << regularization_decayspan << std::endl;
     std::cout << "                 tolerance = " << tolerance << std::endl;
     std::cout << "        maximum_iterations = " << maximum_iterations << std::endl;

     // Set the parameters and Run the optimization.
     P->SetMaximumNumberOfIterations(maximum_iterations);
     P->SetRegularizationInitial(regularization_initial);
     P->SetRegularizationFinal(regularization_final);
     P->SetRegularizationDecaySpan(regularization_decayspan);
     P->SetTolerance(tolerance);
     P->SetNumIndividuals(num_individuals);

     std::cout << "        num_individuals = " << P->GetNumIndividuals() << std::endl;

     // Read the number of timepoints per individual
     if (project->HasVariables("timepts_per_individual"))
     {
       std::vector<double> tp = project->GetVariables("timepts_per_individual");
       vnl_vector<int> timepts; timepts.set_size(tp.size());
       for(int i = 0; i < timepts.size(); i++)
	 timepts[i] = static_cast<int>(tp[i]);

       if (timepts.size() != num_individuals)
       {
	 errstring += "Number of individuals and timepts associated dont match!";
	 passed = false;
       }
       else // set the timepts variables
       {
	 std::cout << "Setting variables" << std::endl;
	 P->SetTimePointsPerIndividual(timepts);
       }
     }
     else
     {
       errstring += "No timepts variables were present.";
       passed = false;
     }

     // Update parameters
     P->Update();

     //   if (P->GetNumberOfElapsedIterations() >= maximum_iterations)
     //  {
     //    errstring += "Optimization did not converge based on tolerance criteria.\n";
     //    passed = false;
     //  }

     // Print out points for domain d
     // Load the model initialization.  It should be specified as a model with a name.
     const std::vector<std::string> &out_files = project->GetModel(std::string("optimized"));
     if (out_files.size() != P->GetParticleSystem()->GetNumberOfDomains())
       {
         errstring += "Number of output files does not match the number of particle domains (inputs).";
         passed = false;
       }

     if (passed == true)
       {
         for (unsigned int d = 0; d < P->GetParticleSystem()->GetNumberOfDomains(); d++)
           {
             // Open the output file.
             std::string fname = output_path + out_files[d];
             std::ofstream out( fname.c_str() );
             if ( !out )
               {
                 errstring += "Could not open point file for output: ";
               }
             else
               {
                 for (unsigned int j = 0; j < P->GetParticleSystem()->GetNumberOfParticles(d); j++)
                   {
                     for (unsigned int i = 0; i < 3; i++)
                       {
                         out <<  P->GetParticleSystem()->GetPosition(j,d)[i]  << " ";
                       }
                     out << std::endl;
                   }
               }
           }
       }
     vnl_vector<double> intercepts = P->GetShapeMatrix()->GetIntercept();
     vnl_vector<double> slope = P->GetShapeMatrix()->GetSlope();
     std::string fname1 = output_path + "Intercept.lpts";
     std::string fname2 = output_path + "Intercept_0.5xSlope.lpts";
     std::string fname3 = output_path + "Intercept_1xSlope.lpts";
     std::ofstream out1(fname1.c_str());
     std::ofstream out2(fname2.c_str());
     std::ofstream out3(fname3.c_str());

     vnl_vector<double>::iterator it1,it2;
     if ( !out1 || !out2 || !out3 )
       {
       errstring += "Could not open point file for output: ";
       }
     else
       {
       int counter = 0;
       for(it1 = intercepts.begin(), it2 = slope.begin(); it1 != intercepts.end(), it2 != slope.end(); ++it1, ++it2)
         {
         out1 << *it1 << ' ';
         out2 << *it1 + (0.5)*(*it2) << ' ';
         out3 << (*it1) + (*it2) << ' ';
         counter++;
         if(counter == 3)
           {
           out1 << std::endl;
           out2 << std::endl;
           out3 << std::endl;
           counter = 0;
           }
         }
       }
    }
  catch(itk::ExceptionObject &e)
    {
      errstring = "ITK exception with description: " + std::string(e.GetDescription())
        + std::string("\n at location:") + std::string(e.GetLocation())
        + std::string("\n in file:") + std::string(e.GetFile());
      passed = false;
    }
  catch(...)
    {
      errstring = "Unknown exception thrown";
      passed = false;
    }

  if (passed)
    {
    std::cout << "All tests passed" << std::endl;
    return EXIT_SUCCESS;
    }
  else
    {
    std::cout << "Test failed with the following error:" << std::endl;
    std::cout << errstring << std::endl;
    return EXIT_FAILURE;
    }
}
<commit_msg>Modified the intercept and slope output to files.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include <iostream>
#include <sstream>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkPSMEntropyMixedEffectsModelFilter.h"
#include "itkPSMProjectReader.h"
#include "itkCommand.h"

namespace itk{

class MyMixedEffectsIterationCommand : public itk::Command
{
public:
 /** Standard class typedefs. */
  typedef MyMixedEffectsIterationCommand         Self;
  typedef Command                    Superclass;
  typedef SmartPointer< Self >       Pointer;
  typedef SmartPointer< const Self > ConstPointer;

  typedef Image<float, 3> ImageType;

  /** Run-time type information (and related methods). */
  itkTypeMacro(MyMixedEffectsIterationCommand, Command);

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** This method will be passed a PSMGradientDescentOptimizer */
  virtual void Execute(Object *caller, const EventObject &)
  {
    PSMEntropyMixedEffectsModelFilter<ImageType> *o
      = static_cast<PSMEntropyMixedEffectsModelFilter<ImageType> *>(caller);

    // Print every 10 iterations
    //    if (o->GetNumberOfElapsedIterations() % 10 != 0) return;

    std::cout << "Iteration # " << o->GetNumberOfElapsedIterations() << std::endl;
    std::cout << " Eigenmode variances: ";
    for (unsigned int i = 0; i < o->GetShapePCAVariances().size(); i++)
      {
        std::cout << o->GetShapePCAVariances()[i] << " ";
      }
    std::cout << std::endl;
    std::cout << " Regularization = " << o->GetRegularizationConstant() << std::endl;
  }
  virtual void Execute(const Object *, const EventObject &)
  {
    std::cout << "SHOULDN'T BE HERE" << std::endl;
  }

protected:
  MyMixedEffectsIterationCommand() {}
  ~MyMixedEffectsIterationCommand() {}
private:
  MyMixedEffectsIterationCommand(const Self &);        //purposely not implemented
  void operator=(const Self &); //purposely not implemented
};

} // end namespace itk

/** This test exercises functionality of the base itkPSMEntropyMixedEffectsModelFilter class */
int itkPSMEntropyMixedEffectsModelFilterTest(int argc, char* argv[] )
{
  bool passed = true;
  std::string errstring = "";
  std::string output_path = "";
  std::string input_path_prefix = "";

  // Check for proper arguments
  if (argc < 2)
    {
      std::cout << "Wrong number of arguments. \nUse: "
	<< "itkPSMEntropyMixedEffectsModelFilterTest parameter_file [output_path] [input_path]\n"
        << "See itk::PSMParameterFileReader for documentation on the parameter file format."
	<< std::endl;
      return EXIT_FAILURE;
    }

  if (argc >2)
    {
      output_path = std::string(argv[2]);
    }

  if (argc >3)
    {
      input_path_prefix = std::string(argv[3]);
    }

  typedef itk::Image<float, 3> ImageType;

  try
    {
     // Read the project parameters
     itk::PSMProjectReader::Pointer xmlreader =
       itk::PSMProjectReader::New();
     xmlreader->SetFileName(argv[1]);
     xmlreader->Update();

     itk::PSMProject::Pointer project = xmlreader->GetOutput();

     // Create the modeling filter and set up the optimization.
     itk::PSMEntropyMixedEffectsModelFilter<ImageType>::Pointer P
       = itk::PSMEntropyMixedEffectsModelFilter<ImageType>::New();

     // Setup the Callback function that is executed after each
     // iteration of the solver.
     itk::MyMixedEffectsIterationCommand::Pointer mycommand = itk::MyMixedEffectsIterationCommand::New();
     P->AddObserver(itk::IterationEvent(), mycommand);

     // Load the distance transforms
     const std::vector<std::string> &dt_files = project->GetDistanceTransforms();
     std::cout << "Reading distance transforms ..." << std::endl;
     for (unsigned int i = 0; i < dt_files.size(); i++)
       {
         itk::ImageFileReader<ImageType>::Pointer reader =
           itk::ImageFileReader<ImageType>::New();
         reader->SetFileName(input_path_prefix + dt_files[i]);
         reader->Update();

         std::cout << "  " << (input_path_prefix + dt_files[i]) << std::endl;

         P->SetInput(i,reader->GetOutput());
       }
     std::cout << "Done!" << std::endl;

     // Load the model initialization.  It should be specified as a model with a name.
     const std::vector<std::string> &pt_files = project->GetModel(std::string("initialization"));
     std::cout << "Reading the initial model correspondences ..." << std::endl;
     for (unsigned int i = 0; i < pt_files.size(); i++)
       {
         // Read the points for this file and add as a list
         std::vector<itk::PSMEntropyMixedEffectsModelFilter<ImageType>::PointType> c;

         int counter = 0;
         // Open the ascii file.
         std::ifstream in( (input_path_prefix + pt_files[i]).c_str() );
         if ( !in )
           {
             errstring += "Could not open point file for input.";
             passed = false;
             break;
           }

         // Read all of the points, one point per line.
         while (in)
           {
             itk::PSMEntropyMixedEffectsModelFilter<ImageType>::PointType pt;

             for (unsigned int d = 0; d < 3; d++)
               {
                 in >> pt[d];
               }
             c.push_back(pt);
             counter++;
           }
         // this algorithm pushes the last point twice
         c.pop_back();
         //  std::cout << "Read " << counter-1 << " points. " << std::endl;
         in.close();

         P->SetInputCorrespondencePoints(i,c);

         std::cout << "  " << pt_files[i] << std::endl;
       }
     std::cout << "Done!" << std::endl;

     // Read the explanatory variables (e.g. time)
     std::vector<double> expl;
     if (project->HasVariables("explanatory_variables"))
       {
         expl = project->GetVariables("explanatory_variables");

         if (expl.size() < dt_files.size())
           {
             errstring += "There are fewer explanatory variables than input files";
             passed = false;
           }
         else // set the explanatory variables
           {std::cout << "Setting variables" << std::endl;
             P->SetVariables(expl);
           }
       }
     else
       {
         errstring += "No explanatory variables were present for the regression.";
         passed = false;
       }

     //  Read some parameters from the file or provide defaults
     double regularization_initial   = 100.0f;
     double regularization_final     = 5.0f;
     double regularization_decayspan = 2000.0f;
     double tolerance                = 1.0e-8;
     unsigned int maximum_iterations = 20000;
     unsigned int num_individuals = 1;

     if ( project->HasOptimizationAttribute("regularization_initial") )
       regularization_initial = project->GetOptimizationAttribute("regularization_initial");
     if ( project->HasOptimizationAttribute("regularization_final") )
       regularization_final = project->GetOptimizationAttribute("regularization_final");
     if ( project->HasOptimizationAttribute("regularization_decayspan") )
       regularization_decayspan = project->GetOptimizationAttribute("regularization_decayspan");
     if ( project->HasOptimizationAttribute("tolerance") )
       tolerance = project->GetOptimizationAttribute("tolerance");
     if ( project->HasOptimizationAttribute("maximum_iterations") )
       maximum_iterations = static_cast<unsigned int>(project->GetOptimizationAttribute("maximum_iterations"));
     if ( project->HasOptimizationAttribute("num_individuals") )
        num_individuals = static_cast<unsigned int>(project->GetOptimizationAttribute("num_individuals"));

     std::cout << "Optimization parameters: " << std::endl;
     std::cout << "    regularization_initial = " << regularization_initial << std::endl;
     std::cout << "      regularization_final = " << regularization_final << std::endl;
     std::cout << "  regularization_decayspan = " << regularization_decayspan << std::endl;
     std::cout << "                 tolerance = " << tolerance << std::endl;
     std::cout << "        maximum_iterations = " << maximum_iterations << std::endl;

     // Set the parameters and Run the optimization.
     P->SetMaximumNumberOfIterations(maximum_iterations);
     P->SetRegularizationInitial(regularization_initial);
     P->SetRegularizationFinal(regularization_final);
     P->SetRegularizationDecaySpan(regularization_decayspan);
     P->SetTolerance(tolerance);
     P->SetNumIndividuals(num_individuals);

     std::cout << "        num_individuals = " << P->GetNumIndividuals() << std::endl;

     // Read the number of timepoints per individual
     if (project->HasVariables("timepts_per_individual"))
     {
       std::vector<double> tp = project->GetVariables("timepts_per_individual");
       vnl_vector<int> timepts; timepts.set_size(tp.size());
       for(int i = 0; i < timepts.size(); i++)
         timepts[i] = static_cast<int>(tp[i]);

       if (timepts.size() != num_individuals)
       {
         errstring += "Number of individuals and timepts associated dont match!";
         passed = false;
       }
       else // set the timepts variables
       {
         std::cout << "Setting variables" << std::endl;
         P->SetTimePointsPerIndividual(timepts);
       }
     }
     else
     {
       errstring += "No timepts variables were present.";
       passed = false;
     }

     // Update parameters
     P->Update();

     //   if (P->GetNumberOfElapsedIterations() >= maximum_iterations)
     //  {
     //    errstring += "Optimization did not converge based on tolerance criteria.\n";
     //    passed = false;
     //  }

     // Print out points for domain d
     // Load the model initialization.  It should be specified as a model with a name.
     const std::vector<std::string> &out_files = project->GetModel(std::string("optimized"));
     if (out_files.size() != P->GetParticleSystem()->GetNumberOfDomains())
       {
         errstring += "Number of output files does not match the number of particle domains (inputs).";
         passed = false;
       }

     if (passed == true)
       {
         for (unsigned int d = 0; d < P->GetParticleSystem()->GetNumberOfDomains(); d++)
           {
             // Open the output file.
             std::string fname = output_path + out_files[d];
             std::ofstream out( fname.c_str() );
             if ( !out )
               {
                 errstring += "Could not open point file for output: ";
               }
             else
               {
                 for (unsigned int j = 0; j < P->GetParticleSystem()->GetNumberOfParticles(d); j++)
                   {
                     for (unsigned int i = 0; i < 3; i++)
                       {
                         out <<  P->GetParticleSystem()->GetPosition(j,d)[i]  << " ";
                       }
                     out << std::endl;
                   }
               }
           }
       }

     std::vector<double>::iterator it_expl;
     vnl_vector<double> output_intercept_slope;
     vnl_vector<double>::iterator output_it;
     int file_count = 0;
     for(it_expl = expl.begin(); it_expl != expl.end(); ++it_expl)
       {
         output_intercept_slope = P->GetShapeMatrix()->ComputeMean(*it_expl);
         std::ostringstream ss;
         ss << file_count;
         std::string fname = output_path + "Intercept+TimexSlope" + "_" + ss.str() + ".lpts";
         std::ofstream out(fname.c_str());
         if ( !out )
         {
           errstring += "Could not open point file for output: ";
         }
         else
         {
           int counter = 0;
           for(output_it = output_intercept_slope.begin(); output_it != output_intercept_slope.end(); ++output_it)
           {
             out << *output_it << ' ';
             counter++;
             if(counter == 3)
             {
               out << std::endl;
               counter = 0;
             }
           }
         }
         file_count++;
       }
    }
  catch(itk::ExceptionObject &e)
    {
      errstring = "ITK exception with description: " + std::string(e.GetDescription())
        + std::string("\n at location:") + std::string(e.GetLocation())
        + std::string("\n in file:") + std::string(e.GetFile());
      passed = false;
    }
  catch(...)
    {
      errstring = "Unknown exception thrown";
      passed = false;
    }

  if (passed)
    {
    std::cout << "All tests passed" << std::endl;
    return EXIT_SUCCESS;
    }
  else
    {
    std::cout << "Test failed with the following error:" << std::endl;
    std::cout << errstring << std::endl;
    return EXIT_FAILURE;
    }
}
<|endoftext|>


<commit_before>#ifdef STAN_OPENCL
#include <stan/math/prim/mat.hpp>
#include <stan/math/prim/arr.hpp>
#include <gtest/gtest.h>

TEST(ErrorHandlingOpenCL, checkThrows) {
  const char* function = "test_func";
  const char* msg = "test";
  EXPECT_THROW(stan::math::throw_openCL(function, msg), std::domain_error);
}
#else
#include <gtest/gtest.h>
TEST(ErrorHandlingOpenCL, checkThrowsDummy) { EXPECT_NO_THROW(); }
#endif
<commit_msg>Fix the broken opencl error test<commit_after>#ifdef STAN_OPENCL
#include <stan/math/prim/mat.hpp>
#include <stan/math/prim/arr.hpp>
#include <gtest/gtest.h>

TEST(ErrorHandlingOpenCL, checkThrows) {
  const char* function = "test_func";
  cl::Error e(-5, "CL_OUT_OF_RESOURCES");
  EXPECT_THROW(stan::math::check_ocl_error(function, e), std::system_error);
}
#else
#include <gtest/gtest.h>
TEST(ErrorHandlingOpenCL, checkThrowsDummy) { EXPECT_NO_THROW(); }
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "views/controls/textfield/textfield_views_model.h"
#include "views/test/test_views_delegate.h"
#include "views/views_delegate.h"

namespace views {

#define EXPECT_STR_EQ(ascii, utf16) \
  EXPECT_EQ(ASCIIToWide(ascii), UTF16ToWide(utf16))

TEST(TextfieldViewsModelTest, EditString) {
  TextfieldViewsModel model;
  // append two strings
  model.Append(ASCIIToUTF16("HILL"));
  EXPECT_STR_EQ("HILL", model.text());
  model.Append(ASCIIToUTF16("WORLD"));
  EXPECT_STR_EQ("HILLWORLD", model.text());

  // Insert "E" to make hello
  model.MoveCursorRight(false);
  model.Insert('E');
  EXPECT_STR_EQ("HEILLWORLD", model.text());
  // Replace "I" with "L"
  model.Replace('L');
  EXPECT_STR_EQ("HELLLWORLD", model.text());
  model.Replace('L');
  model.Replace('O');
  EXPECT_STR_EQ("HELLOWORLD", model.text());

  // Delete 6th char "W", then delete 5th char O"
  EXPECT_EQ(5U, model.cursor_pos());
  EXPECT_TRUE(model.Delete());
  EXPECT_STR_EQ("HELLOORLD", model.text());
  EXPECT_TRUE(model.Backspace());
  EXPECT_EQ(4U, model.cursor_pos());
  EXPECT_STR_EQ("HELLORLD", model.text());

  // Move the cursor to start. backspace should fail.
  model.MoveCursorToStart(false);
  EXPECT_FALSE(model.Backspace());
  EXPECT_STR_EQ("HELLORLD", model.text());
  // Move the cursor to the end. delete should fail.
  model.MoveCursorToEnd(false);
  EXPECT_FALSE(model.Delete());
  EXPECT_STR_EQ("HELLORLD", model.text());
  // but backspace should work.
  EXPECT_TRUE(model.Backspace());
  EXPECT_STR_EQ("HELLORL", model.text());
}

TEST(TextfieldViewsModelTest, EmptyString) {
  TextfieldViewsModel model;
  EXPECT_EQ(string16(), model.text());
  EXPECT_EQ(string16(), model.GetSelectedText());
  EXPECT_EQ(string16(), model.GetVisibleText());

  model.MoveCursorLeft(true);
  EXPECT_EQ(0U, model.cursor_pos());
  model.MoveCursorRight(true);
  EXPECT_EQ(0U, model.cursor_pos());

  EXPECT_EQ(string16(), model.GetSelectedText());

  EXPECT_FALSE(model.Delete());
  EXPECT_FALSE(model.Backspace());
}

TEST(TextfieldViewsModelTest, Selection) {
  TextfieldViewsModel model;
  model.Append(ASCIIToUTF16("HELLO"));
  model.MoveCursorRight(false);
  model.MoveCursorRight(true);
  EXPECT_STR_EQ("E", model.GetSelectedText());
  model.MoveCursorRight(true);
  EXPECT_STR_EQ("EL", model.GetSelectedText());

  model.MoveCursorToStart(true);
  EXPECT_STR_EQ("H", model.GetSelectedText());
  model.MoveCursorToEnd(true);
  EXPECT_STR_EQ("ELLO", model.GetSelectedText());
  model.ClearSelection();
  EXPECT_EQ(string16(), model.GetSelectedText());
  model.SelectAll();
  EXPECT_STR_EQ("HELLO", model.GetSelectedText());

  // Select and move cursor
  model.MoveCursorTo(1U, false);
  model.MoveCursorTo(3U, true);
  EXPECT_STR_EQ("EL", model.GetSelectedText());
  model.MoveCursorLeft(false);
  EXPECT_EQ(1U, model.cursor_pos());
  model.MoveCursorTo(1U, false);
  model.MoveCursorTo(3U, true);
  model.MoveCursorRight(false);
  EXPECT_EQ(3U, model.cursor_pos());

  // Select all and move cursor
  model.SelectAll();
  model.MoveCursorLeft(false);
  EXPECT_EQ(0U, model.cursor_pos());
  model.SelectAll();
  model.MoveCursorRight(false);
  EXPECT_EQ(5U, model.cursor_pos());
}

TEST(TextfieldViewsModelTest, SelectionAndEdit) {
  TextfieldViewsModel model;
  model.Append(ASCIIToUTF16("HELLO"));
  model.MoveCursorRight(false);
  model.MoveCursorRight(true);
  model.MoveCursorRight(true);  // select "EL"
  EXPECT_TRUE(model.Backspace());
  EXPECT_STR_EQ("HLO", model.text());

  model.Append(ASCIIToUTF16("ILL"));
  model.MoveCursorRight(true);
  model.MoveCursorRight(true);  // select "LO"
  EXPECT_TRUE(model.Delete());
  EXPECT_STR_EQ("HILL", model.text());
  EXPECT_EQ(1U, model.cursor_pos());
  model.MoveCursorRight(true);  // select "I"
  model.Insert('E');
  EXPECT_STR_EQ("HELL", model.text());
  model.MoveCursorToStart(false);
  model.MoveCursorRight(true);  // select "H"
  model.Replace('B');
  EXPECT_STR_EQ("BELL", model.text());
  model.MoveCursorToEnd(false);
  model.MoveCursorLeft(true);
  model.MoveCursorLeft(true);  // select ">LL"
  model.Replace('E');
  EXPECT_STR_EQ("BEE", model.text());
}

TEST(TextfieldViewsModelTest, Password) {
  TextfieldViewsModel model;
  model.set_is_password(true);
  model.Append(ASCIIToUTF16("HELLO"));
  EXPECT_STR_EQ("*****", model.GetVisibleText());
  EXPECT_STR_EQ("HELLO", model.text());
  EXPECT_TRUE(model.Delete());

  EXPECT_STR_EQ("****", model.GetVisibleText());
  EXPECT_STR_EQ("ELLO", model.text());
  EXPECT_EQ(0U, model.cursor_pos());

  model.SelectAll();
  EXPECT_STR_EQ("ELLO", model.GetSelectedText());
  EXPECT_EQ(0U, model.cursor_pos());

  model.Insert('X');
  EXPECT_STR_EQ("*", model.GetVisibleText());
  EXPECT_STR_EQ("X", model.text());
}

TEST(TextfieldViewsModelTest, Word) {
  TextfieldViewsModel model;
  model.Append(
      ASCIIToUTF16("The answer to Life, the Universe, and Everything"));
  model.MoveCursorToNextWord(false);
  EXPECT_EQ(3U, model.cursor_pos());
  model.MoveCursorToNextWord(false);
  EXPECT_EQ(10U, model.cursor_pos());
  model.MoveCursorToNextWord(false);
  model.MoveCursorToNextWord(false);
  EXPECT_EQ(18U, model.cursor_pos());

  // Should passes the non word char ','
  model.MoveCursorToNextWord(true);
  EXPECT_EQ(23U, model.cursor_pos());
  EXPECT_STR_EQ(", the", model.GetSelectedText());

  // Move to the end.
  model.MoveCursorToNextWord(true);
  model.MoveCursorToNextWord(true);
  model.MoveCursorToNextWord(true);
  EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText());
  // Should be safe to go next word at the end.
  model.MoveCursorToNextWord(true);
  EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText());
  model.Insert('2');
  EXPECT_EQ(19U, model.cursor_pos());

  // Now backwards.
  model.MoveCursorLeft(false);  // leave 2.
  model.MoveCursorToPreviousWord(true);
  EXPECT_EQ(14U, model.cursor_pos());
  EXPECT_STR_EQ("Life", model.GetSelectedText());
  model.MoveCursorToPreviousWord(true);
  EXPECT_STR_EQ("to Life", model.GetSelectedText());
  model.MoveCursorToPreviousWord(true);
  model.MoveCursorToPreviousWord(true);
  model.MoveCursorToPreviousWord(true);  // Select to the begining.
  EXPECT_STR_EQ("The answer to Life", model.GetSelectedText());
  // Should be safe to go pervious word at the begining.
  model.MoveCursorToPreviousWord(true);
  EXPECT_STR_EQ("The answer to Life", model.GetSelectedText());
  model.Replace('4');
  EXPECT_EQ(string16(), model.GetSelectedText());
  EXPECT_STR_EQ("42", model.GetVisibleText());
}

TEST(TextfieldViewsModelTest, TextFragment) {
  TextfieldViewsModel model;
  TextfieldViewsModel::TextFragments fragments;
  // Empty string
  model.GetFragments(&fragments);
  EXPECT_EQ(1U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(0U, fragments[0].end);
  EXPECT_FALSE(fragments[0].selected);

  // Some string
  model.Append(ASCIIToUTF16("Hello world"));
  model.GetFragments(&fragments);
  EXPECT_EQ(1U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(11U, fragments[0].end);
  EXPECT_FALSE(fragments[0].selected);

  // Select 1st word
  model.MoveCursorToNextWord(true);
  model.GetFragments(&fragments);
  EXPECT_EQ(2U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(5U, fragments[0].end);
  EXPECT_TRUE(fragments[0].selected);
  EXPECT_EQ(5U, fragments[1].begin);
  EXPECT_EQ(11U, fragments[1].end);
  EXPECT_FALSE(fragments[1].selected);

  // Select empty string
  model.ClearSelection();
  model.MoveCursorRight(true);
  model.GetFragments(&fragments);
  EXPECT_EQ(3U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(5U, fragments[0].end);
  EXPECT_FALSE(fragments[0].selected);
  EXPECT_EQ(5U, fragments[1].begin);
  EXPECT_EQ(6U, fragments[1].end);
  EXPECT_TRUE(fragments[1].selected);

  EXPECT_EQ(6U, fragments[2].begin);
  EXPECT_EQ(11U, fragments[2].end);
  EXPECT_FALSE(fragments[2].selected);

  // Select to the end.
  model.MoveCursorToEnd(true);
  model.GetFragments(&fragments);
  EXPECT_EQ(2U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(5U, fragments[0].end);
  EXPECT_FALSE(fragments[0].selected);
  EXPECT_EQ(5U, fragments[1].begin);
  EXPECT_EQ(11U, fragments[1].end);
  EXPECT_TRUE(fragments[1].selected);
}

TEST(TextfieldViewsModelTest, SetText) {
  TextfieldViewsModel model;
  model.Append(ASCIIToUTF16("HELLO"));
  model.MoveCursorToEnd(false);
  model.SetText(ASCIIToUTF16("GOODBYE"));
  EXPECT_STR_EQ("GOODBYE", model.text());
  EXPECT_EQ(5U, model.cursor_pos());
  model.SelectAll();
  EXPECT_STR_EQ("GOODBYE", model.GetSelectedText());
  // Selection move the current pos to the begining.
  EXPECT_EQ(0U, model.cursor_pos());
  model.MoveCursorToEnd(false);
  EXPECT_EQ(7U, model.cursor_pos());

  model.SetText(ASCIIToUTF16("BYE"));
  EXPECT_EQ(3U, model.cursor_pos());
  EXPECT_EQ(string16(), model.GetSelectedText());
  model.SetText(ASCIIToUTF16(""));
  EXPECT_EQ(0U, model.cursor_pos());
}

#if defined(OS_WIN)
#define MAYBE_Clipboard DISABLED_Clipboard
#else
#define MAYBE_Clipboard Clipboard
#endif
TEST(TextfieldViewsModelTest, MAYBE_Clipboard) {
  views::ViewsDelegate::views_delegate = new TestViewsDelegate();
  ui::Clipboard* clipboard
      = views::ViewsDelegate::views_delegate->GetClipboard();
  string16 initial_clipboard_text;
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &initial_clipboard_text);
  string16 clipboard_text;
  TextfieldViewsModel model;
  model.Append(ASCIIToUTF16("HELLO WORLD"));
  model.MoveCursorToEnd(false);

  // Test for cut: Empty selection.
  EXPECT_FALSE(model.Cut());
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ(UTF16ToUTF8(initial_clipboard_text), clipboard_text);
  EXPECT_STR_EQ("HELLO WORLD", model.text());
  EXPECT_EQ(11U, model.cursor_pos());

  // Test for cut: Non-empty selection.
  model.MoveCursorToPreviousWord(true);
  EXPECT_TRUE(model.Cut());
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ("WORLD", clipboard_text);
  EXPECT_STR_EQ("HELLO ", model.text());
  EXPECT_EQ(6U, model.cursor_pos());

  // Test for copy: Empty selection.
  model.Copy();
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ("WORLD", clipboard_text);
  EXPECT_STR_EQ("HELLO ", model.text());
  EXPECT_EQ(6U, model.cursor_pos());

  // Test for copy: Non-empty selection.
  model.Append(ASCIIToUTF16("HELLO WORLD"));
  model.SelectAll();
  model.Copy();
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text);
  EXPECT_STR_EQ("HELLO HELLO WORLD", model.text());
  EXPECT_EQ(0U, model.cursor_pos());

  // Test for paste.
  model.ClearSelection();
  model.MoveCursorToEnd(false);
  model.MoveCursorToPreviousWord(true);
  EXPECT_TRUE(model.Paste());
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text);
  EXPECT_STR_EQ("HELLO HELLO HELLO HELLO WORLD", model.text());
  EXPECT_EQ(29U, model.cursor_pos());
}

}  // namespace views
<commit_msg>Delete test view delegate at end of test<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/auto_reset.h"
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "views/controls/textfield/textfield_views_model.h"
#include "views/test/test_views_delegate.h"
#include "views/views_delegate.h"

namespace views {

#define EXPECT_STR_EQ(ascii, utf16) \
  EXPECT_EQ(ASCIIToWide(ascii), UTF16ToWide(utf16))

TEST(TextfieldViewsModelTest, EditString) {
  TextfieldViewsModel model;
  // append two strings
  model.Append(ASCIIToUTF16("HILL"));
  EXPECT_STR_EQ("HILL", model.text());
  model.Append(ASCIIToUTF16("WORLD"));
  EXPECT_STR_EQ("HILLWORLD", model.text());

  // Insert "E" to make hello
  model.MoveCursorRight(false);
  model.Insert('E');
  EXPECT_STR_EQ("HEILLWORLD", model.text());
  // Replace "I" with "L"
  model.Replace('L');
  EXPECT_STR_EQ("HELLLWORLD", model.text());
  model.Replace('L');
  model.Replace('O');
  EXPECT_STR_EQ("HELLOWORLD", model.text());

  // Delete 6th char "W", then delete 5th char O"
  EXPECT_EQ(5U, model.cursor_pos());
  EXPECT_TRUE(model.Delete());
  EXPECT_STR_EQ("HELLOORLD", model.text());
  EXPECT_TRUE(model.Backspace());
  EXPECT_EQ(4U, model.cursor_pos());
  EXPECT_STR_EQ("HELLORLD", model.text());

  // Move the cursor to start. backspace should fail.
  model.MoveCursorToStart(false);
  EXPECT_FALSE(model.Backspace());
  EXPECT_STR_EQ("HELLORLD", model.text());
  // Move the cursor to the end. delete should fail.
  model.MoveCursorToEnd(false);
  EXPECT_FALSE(model.Delete());
  EXPECT_STR_EQ("HELLORLD", model.text());
  // but backspace should work.
  EXPECT_TRUE(model.Backspace());
  EXPECT_STR_EQ("HELLORL", model.text());
}

TEST(TextfieldViewsModelTest, EmptyString) {
  TextfieldViewsModel model;
  EXPECT_EQ(string16(), model.text());
  EXPECT_EQ(string16(), model.GetSelectedText());
  EXPECT_EQ(string16(), model.GetVisibleText());

  model.MoveCursorLeft(true);
  EXPECT_EQ(0U, model.cursor_pos());
  model.MoveCursorRight(true);
  EXPECT_EQ(0U, model.cursor_pos());

  EXPECT_EQ(string16(), model.GetSelectedText());

  EXPECT_FALSE(model.Delete());
  EXPECT_FALSE(model.Backspace());
}

TEST(TextfieldViewsModelTest, Selection) {
  TextfieldViewsModel model;
  model.Append(ASCIIToUTF16("HELLO"));
  model.MoveCursorRight(false);
  model.MoveCursorRight(true);
  EXPECT_STR_EQ("E", model.GetSelectedText());
  model.MoveCursorRight(true);
  EXPECT_STR_EQ("EL", model.GetSelectedText());

  model.MoveCursorToStart(true);
  EXPECT_STR_EQ("H", model.GetSelectedText());
  model.MoveCursorToEnd(true);
  EXPECT_STR_EQ("ELLO", model.GetSelectedText());
  model.ClearSelection();
  EXPECT_EQ(string16(), model.GetSelectedText());
  model.SelectAll();
  EXPECT_STR_EQ("HELLO", model.GetSelectedText());

  // Select and move cursor
  model.MoveCursorTo(1U, false);
  model.MoveCursorTo(3U, true);
  EXPECT_STR_EQ("EL", model.GetSelectedText());
  model.MoveCursorLeft(false);
  EXPECT_EQ(1U, model.cursor_pos());
  model.MoveCursorTo(1U, false);
  model.MoveCursorTo(3U, true);
  model.MoveCursorRight(false);
  EXPECT_EQ(3U, model.cursor_pos());

  // Select all and move cursor
  model.SelectAll();
  model.MoveCursorLeft(false);
  EXPECT_EQ(0U, model.cursor_pos());
  model.SelectAll();
  model.MoveCursorRight(false);
  EXPECT_EQ(5U, model.cursor_pos());
}

TEST(TextfieldViewsModelTest, SelectionAndEdit) {
  TextfieldViewsModel model;
  model.Append(ASCIIToUTF16("HELLO"));
  model.MoveCursorRight(false);
  model.MoveCursorRight(true);
  model.MoveCursorRight(true);  // select "EL"
  EXPECT_TRUE(model.Backspace());
  EXPECT_STR_EQ("HLO", model.text());

  model.Append(ASCIIToUTF16("ILL"));
  model.MoveCursorRight(true);
  model.MoveCursorRight(true);  // select "LO"
  EXPECT_TRUE(model.Delete());
  EXPECT_STR_EQ("HILL", model.text());
  EXPECT_EQ(1U, model.cursor_pos());
  model.MoveCursorRight(true);  // select "I"
  model.Insert('E');
  EXPECT_STR_EQ("HELL", model.text());
  model.MoveCursorToStart(false);
  model.MoveCursorRight(true);  // select "H"
  model.Replace('B');
  EXPECT_STR_EQ("BELL", model.text());
  model.MoveCursorToEnd(false);
  model.MoveCursorLeft(true);
  model.MoveCursorLeft(true);  // select ">LL"
  model.Replace('E');
  EXPECT_STR_EQ("BEE", model.text());
}

TEST(TextfieldViewsModelTest, Password) {
  TextfieldViewsModel model;
  model.set_is_password(true);
  model.Append(ASCIIToUTF16("HELLO"));
  EXPECT_STR_EQ("*****", model.GetVisibleText());
  EXPECT_STR_EQ("HELLO", model.text());
  EXPECT_TRUE(model.Delete());

  EXPECT_STR_EQ("****", model.GetVisibleText());
  EXPECT_STR_EQ("ELLO", model.text());
  EXPECT_EQ(0U, model.cursor_pos());

  model.SelectAll();
  EXPECT_STR_EQ("ELLO", model.GetSelectedText());
  EXPECT_EQ(0U, model.cursor_pos());

  model.Insert('X');
  EXPECT_STR_EQ("*", model.GetVisibleText());
  EXPECT_STR_EQ("X", model.text());
}

TEST(TextfieldViewsModelTest, Word) {
  TextfieldViewsModel model;
  model.Append(
      ASCIIToUTF16("The answer to Life, the Universe, and Everything"));
  model.MoveCursorToNextWord(false);
  EXPECT_EQ(3U, model.cursor_pos());
  model.MoveCursorToNextWord(false);
  EXPECT_EQ(10U, model.cursor_pos());
  model.MoveCursorToNextWord(false);
  model.MoveCursorToNextWord(false);
  EXPECT_EQ(18U, model.cursor_pos());

  // Should passes the non word char ','
  model.MoveCursorToNextWord(true);
  EXPECT_EQ(23U, model.cursor_pos());
  EXPECT_STR_EQ(", the", model.GetSelectedText());

  // Move to the end.
  model.MoveCursorToNextWord(true);
  model.MoveCursorToNextWord(true);
  model.MoveCursorToNextWord(true);
  EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText());
  // Should be safe to go next word at the end.
  model.MoveCursorToNextWord(true);
  EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText());
  model.Insert('2');
  EXPECT_EQ(19U, model.cursor_pos());

  // Now backwards.
  model.MoveCursorLeft(false);  // leave 2.
  model.MoveCursorToPreviousWord(true);
  EXPECT_EQ(14U, model.cursor_pos());
  EXPECT_STR_EQ("Life", model.GetSelectedText());
  model.MoveCursorToPreviousWord(true);
  EXPECT_STR_EQ("to Life", model.GetSelectedText());
  model.MoveCursorToPreviousWord(true);
  model.MoveCursorToPreviousWord(true);
  model.MoveCursorToPreviousWord(true);  // Select to the begining.
  EXPECT_STR_EQ("The answer to Life", model.GetSelectedText());
  // Should be safe to go pervious word at the begining.
  model.MoveCursorToPreviousWord(true);
  EXPECT_STR_EQ("The answer to Life", model.GetSelectedText());
  model.Replace('4');
  EXPECT_EQ(string16(), model.GetSelectedText());
  EXPECT_STR_EQ("42", model.GetVisibleText());
}

TEST(TextfieldViewsModelTest, TextFragment) {
  TextfieldViewsModel model;
  TextfieldViewsModel::TextFragments fragments;
  // Empty string
  model.GetFragments(&fragments);
  EXPECT_EQ(1U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(0U, fragments[0].end);
  EXPECT_FALSE(fragments[0].selected);

  // Some string
  model.Append(ASCIIToUTF16("Hello world"));
  model.GetFragments(&fragments);
  EXPECT_EQ(1U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(11U, fragments[0].end);
  EXPECT_FALSE(fragments[0].selected);

  // Select 1st word
  model.MoveCursorToNextWord(true);
  model.GetFragments(&fragments);
  EXPECT_EQ(2U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(5U, fragments[0].end);
  EXPECT_TRUE(fragments[0].selected);
  EXPECT_EQ(5U, fragments[1].begin);
  EXPECT_EQ(11U, fragments[1].end);
  EXPECT_FALSE(fragments[1].selected);

  // Select empty string
  model.ClearSelection();
  model.MoveCursorRight(true);
  model.GetFragments(&fragments);
  EXPECT_EQ(3U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(5U, fragments[0].end);
  EXPECT_FALSE(fragments[0].selected);
  EXPECT_EQ(5U, fragments[1].begin);
  EXPECT_EQ(6U, fragments[1].end);
  EXPECT_TRUE(fragments[1].selected);

  EXPECT_EQ(6U, fragments[2].begin);
  EXPECT_EQ(11U, fragments[2].end);
  EXPECT_FALSE(fragments[2].selected);

  // Select to the end.
  model.MoveCursorToEnd(true);
  model.GetFragments(&fragments);
  EXPECT_EQ(2U, fragments.size());
  EXPECT_EQ(0U, fragments[0].begin);
  EXPECT_EQ(5U, fragments[0].end);
  EXPECT_FALSE(fragments[0].selected);
  EXPECT_EQ(5U, fragments[1].begin);
  EXPECT_EQ(11U, fragments[1].end);
  EXPECT_TRUE(fragments[1].selected);
}

TEST(TextfieldViewsModelTest, SetText) {
  TextfieldViewsModel model;
  model.Append(ASCIIToUTF16("HELLO"));
  model.MoveCursorToEnd(false);
  model.SetText(ASCIIToUTF16("GOODBYE"));
  EXPECT_STR_EQ("GOODBYE", model.text());
  EXPECT_EQ(5U, model.cursor_pos());
  model.SelectAll();
  EXPECT_STR_EQ("GOODBYE", model.GetSelectedText());
  // Selection move the current pos to the begining.
  EXPECT_EQ(0U, model.cursor_pos());
  model.MoveCursorToEnd(false);
  EXPECT_EQ(7U, model.cursor_pos());

  model.SetText(ASCIIToUTF16("BYE"));
  EXPECT_EQ(3U, model.cursor_pos());
  EXPECT_EQ(string16(), model.GetSelectedText());
  model.SetText(ASCIIToUTF16(""));
  EXPECT_EQ(0U, model.cursor_pos());
}

#if defined(OS_WIN)
#define MAYBE_Clipboard DISABLED_Clipboard
#else
#define MAYBE_Clipboard Clipboard
#endif
TEST(TextfieldViewsModelTest, MAYBE_Clipboard) {
  scoped_ptr<TestViewsDelegate> test_views_delegate(new TestViewsDelegate());
  AutoReset<views::ViewsDelegate*> auto_reset(
      &views::ViewsDelegate::views_delegate, test_views_delegate.get());
  ui::Clipboard* clipboard
      = views::ViewsDelegate::views_delegate->GetClipboard();
  string16 initial_clipboard_text;
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &initial_clipboard_text);
  string16 clipboard_text;
  TextfieldViewsModel model;
  model.Append(ASCIIToUTF16("HELLO WORLD"));
  model.MoveCursorToEnd(false);

  // Test for cut: Empty selection.
  EXPECT_FALSE(model.Cut());
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ(UTF16ToUTF8(initial_clipboard_text), clipboard_text);
  EXPECT_STR_EQ("HELLO WORLD", model.text());
  EXPECT_EQ(11U, model.cursor_pos());

  // Test for cut: Non-empty selection.
  model.MoveCursorToPreviousWord(true);
  EXPECT_TRUE(model.Cut());
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ("WORLD", clipboard_text);
  EXPECT_STR_EQ("HELLO ", model.text());
  EXPECT_EQ(6U, model.cursor_pos());

  // Test for copy: Empty selection.
  model.Copy();
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ("WORLD", clipboard_text);
  EXPECT_STR_EQ("HELLO ", model.text());
  EXPECT_EQ(6U, model.cursor_pos());

  // Test for copy: Non-empty selection.
  model.Append(ASCIIToUTF16("HELLO WORLD"));
  model.SelectAll();
  model.Copy();
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text);
  EXPECT_STR_EQ("HELLO HELLO WORLD", model.text());
  EXPECT_EQ(0U, model.cursor_pos());

  // Test for paste.
  model.ClearSelection();
  model.MoveCursorToEnd(false);
  model.MoveCursorToPreviousWord(true);
  EXPECT_TRUE(model.Paste());
  clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
  EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text);
  EXPECT_STR_EQ("HELLO HELLO HELLO HELLO WORLD", model.text());
  EXPECT_EQ(29U, model.cursor_pos());
}

}  // namespace views
<|endoftext|>