<commit_before>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * 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 Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/fscapi.h"
#include "base/messages.h"
#include "base/util/utils.h"
#include "base/util/StringBuffer.h"

#include <stdio.h>

const size_t StringBuffer::npos = 0xFFFFFFFF;
static size_t growup = 5;

StringBuffer::StringBuffer(const char* str, size_t len) {
    size = 0;
    s = 0;

    // if the given string is null, leave this null,
    // otherwise set it, even empty.
    if (str) {
        size_t slen = strlen(str);
        size_t newlen = (len > slen) ? slen : len ;

        if(newlen) {
            getmem(newlen);
            strncpy(s, str, newlen);
            s[newlen]=0;
        }
        else {  // empty string
            getmem(1);
            s[0] = 0;
        }
    }
}

//Copy Costructor
StringBuffer::StringBuffer(const StringBuffer &sb) {
    size = 0;
    s = NULL;
    append(sb.c_str());
}

StringBuffer::~StringBuffer() {
    freemem();
}

StringBuffer& StringBuffer::append(const char* sNew) {
    if (sNew == NULL) {
        return *this;
    }

    unsigned long len = strlen(sNew);

    if (len == 0) {
        return *this;
    }
    if (s) {
        getmem(strlen(s) + len);
        strcat(s, sNew);
    }
    else {
        getmem(len);
        strcpy(s, sNew);
    }

    return *this;
}

StringBuffer& StringBuffer::append(unsigned long i, bool sign) {
    append(StringBuffer().sprintf(sign ? "%ld" : "%lu", i));

    return *this;
}

StringBuffer& StringBuffer::append(StringBuffer& str) {
    return append(str.getChars());
}

StringBuffer& StringBuffer::append(StringBuffer* str) {
    if (str)
        return append(str->getChars());
    else
        return *this;
}

StringBuffer& StringBuffer::set(const char* sNew) {
    if (sNew) {
        size_t len = strlen(sNew);
        if ( len ) {
            getmem( len );
            strcpy(s, sNew);
        }
        else if (s) {
            s[0]=0; // just make the string empty
        } else {
            getmem( 2 );
            strcpy(s, "");
        }
    }
    else {
        freemem();  // release the string and set it to null
    }

    return *this;
}

StringBuffer& StringBuffer::sprintf(const char* format, ...) {
    va_list ap;

    va_start(ap, format);
    this->vsprintf(format, ap);
    va_end(ap);

    return *this;
}

StringBuffer& StringBuffer::vsprintf(const char* format, va_list ap) {
    va_list aq;

    // ensure minimal size for first iteration
    int realsize = 255;

    do {
        // make a copy to keep ap valid for further iterations
#ifdef va_copy
        va_copy(aq, ap);
#else
        aq = ap;
#endif

        if (size < (unsigned long)realsize) {
            s = (char*)realloc(s, (realsize + 1) * sizeof(char));
            size = realsize;
        }

        realsize = vsnprintf(s, size + 1, format, aq);
        if (realsize == -1) {
            // old-style vnsprintf: exact len unknown, try again with doubled size
            realsize = size * 2;
        }
        va_end(aq);
    } while((unsigned long)realsize > size);

    // free extra memory
    s = (char*)realloc(s, (realsize + 1) * sizeof(char));
    size = realsize;

    return *this;
}

const char* StringBuffer::getChars() const { return s; }

unsigned long StringBuffer::length() const {
    return (s) ? strlen(s) : 0;
}

// Watch out
StringBuffer& StringBuffer::reset() {
    freemem();
    return *this;
}

size_t StringBuffer::find(const char *str, size_t pos) const
{
    if (pos >= length()) {
        return npos;
    }
    char *p = strstr(s+pos, str);
    if(!p)
        return npos;
    return (p-s);
}

size_t StringBuffer::ifind(const char *str, size_t pos) const
{
    if (pos >= length())
        return npos;

    char *ls = strtolower(s+pos);
    char *lstr = strtolower(str);

    char *p = strstr(ls, lstr);

    size_t ret = (p) ? p-ls : npos;

    delete [] ls;
    delete [] lstr;

    return ret;
}

size_t StringBuffer::rfind(const char *str, size_t pos) const
{
    if (pos >= length())
        return npos;

    size_t tmp = StringBuffer::npos;
    int previous = pos;

    tmp = find(str, pos);
    if (tmp == StringBuffer::npos)
        return npos;

    while(1) {

        previous = tmp;
        tmp = find(str, tmp + 1);
        if (tmp == StringBuffer::npos)
            break;
    }

    return previous;

}

size_t StringBuffer::replace(const char *from, const char *to, size_t pos)
{
	size_t ret = npos;

    if (!s)
        return npos;

    if(pos>=length())
        return npos;

    char *p = strstr(s+pos, from);
    if (p) {
        size_t fpos = p - s;
        size_t flen = strlen(from), tlen = strlen(to);
        char *tail = 0;
        int ldiff = tlen - flen ;

        // reallocate if needed
        getmem(length() + ldiff);
        p = s + fpos;            // ensure that p is valid again
        // check is there is a remainder after the replaced token
        if( p[flen] ) {
            tail = new char[length()];
            strcpy(tail, p+flen);
        }
        // copy to in place of from
        strcpy(p, to);
        // copy the remainder of old string, if there is one
        if( tail ) {
            strcpy(p+tlen, tail);
            delete [] tail;
        }
		ret = p - s;
    }
    return ret;
}

// TODO: implement some smarter argorithm to avoid multiple reallocations
int StringBuffer::replaceAll(const char *from, const char *to, size_t pos) {
    int i=0;
    int len = strlen(to);
    size_t next;

    for(next=replace(from, to, pos); next != npos; next=replace(from,to,next + len) ) {
        i++;
    }
    return i;
}

ArrayList& StringBuffer::split(ArrayList &tokens, const char *separator) const {
    tokens.clear();
    size_t seplen = strlen(separator);
    char *base = s;
    char *p = strstr( base, separator );

    while( p )
    {
        StringBuffer token(base, p-base);
        tokens.add( token );
        base = p + seplen;
        p = strstr( base, separator );
    }
    StringBuffer token(base);
    tokens.add( token );

    return tokens;
}

StringBuffer& StringBuffer::join(ArrayList &tokens, const char *separator) {
    StringBuffer *line;
    size_t totlen = 0, seplen = strlen(separator);
    // Calc total size
    for (line=(StringBuffer *)tokens.front();
		 line;
         line=(StringBuffer *)tokens.next() ) {
        totlen += line->length() + seplen;
    }
    // Reserve mem
    reserve(totlen);
    // Join strings
    for (line=(StringBuffer *)tokens.front();
		 line;
         line=(StringBuffer *)tokens.next() ) {
        this->append(line->c_str());
        this->append(separator);
    }
    return *this;
}

StringBuffer StringBuffer::substr(size_t pos, size_t len) const {
    if(pos > strlen(s))
        return StringBuffer("");

	return (StringBuffer(s+pos, len));
}

void StringBuffer::reserve(size_t len) {
    getmem(len);
}

StringBuffer& StringBuffer::upperCase() {
    char* p = NULL;

    for(p = s; *p; p++) {
        *p=toupper(*p);
    }

    return *this;
}

StringBuffer& StringBuffer::lowerCase() {
    char* p = NULL;

    for(p = s; *p; p++) {
        *p=tolower(*p);
    }

    return *this;
}

/**
 * Perform case insensitive compare.
 * @return true if equals
 */
bool StringBuffer::icmp(const char *sc) const {
    return wcscmpIgnoreCase(s, sc);
}

ArrayElement* StringBuffer::clone() {
    return new StringBuffer(s);
}

bool StringBuffer::empty() const {
    if(!s)
        return true;
    if(!*s)
        return true;
    return false;
}

bool StringBuffer::null() const { return (s==0); }

// Member Operators
StringBuffer& StringBuffer::operator= (const char* sc)
    { return set(sc); }
StringBuffer& StringBuffer::operator= (const StringBuffer& sb)
    { return set(sb); }
StringBuffer& StringBuffer::operator+= (const char* sc)
    { append(sc); return *this; }
StringBuffer& StringBuffer::operator+= (const StringBuffer& s)
    { append(s); return *this; }
bool  StringBuffer::operator== (const char* sc) const
{
    if(!s)
        return (sc) ? false : true ;
    if (!sc)
        return false;

    return strcmp(s, sc) == 0;
}
bool  StringBuffer::operator== (const StringBuffer& sb) const
{
    return *this == sb.c_str();
}

bool  StringBuffer::operator!= (const char* sc) const
{
    return !(*this == sc);
}
bool  StringBuffer::operator!= (const StringBuffer& s) const
{
    return !(*this == s.c_str());
}

// Function operators
StringBuffer operator+(const StringBuffer& x, const char *y)
{
  StringBuffer result(x);
  result.append(y);
  return result;
}

//size_t StringBuffer_memcount = 0;

// Private allocator
void StringBuffer::getmem(size_t len)
{
    //fprintf(stderr, "GETMEM len=%ld s=%lx size=%ld\n", len, s, size);
    if(len > size) {
        // Remember the old length (0 for the null string)
        size_t oldlen = length();
        // Realloc the string (like malloc when s is null)
        s = (char *)realloc(s, (len+1) * sizeof(char) );
        //StringBuffer_memcount += (len-size);
        size = len;
        // Make sure s is terminated at the old position
        // (malloc may fill the buffer with rubbish)
        s[oldlen] = 0;
        //fprintf(stderr, "\t\ts=%lx size=%ld alloc=%ld\n", s, size, alloclen);
    }
}

// Private deallocator
void StringBuffer::freemem()
{
    if(s) {
        free(s); s = 0;
        //fprintf(stderr, "FREEMEM s=%lx size=%ld\n", s, size);
    }
    //StringBuffer_memcount -= size;
    size = 0;
}

<commit_msg>added some '#ifdef SYMBIAN' for new Symbian client added a safe check in vsprintf<commit_after>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * 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 Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/fscapi.h"
#include "base/messages.h"
#include "base/util/utils.h"
#include "base/util/StringBuffer.h"

#include <stdio.h>

const size_t StringBuffer::npos = 0xFFFFFFFF;
static size_t growup = 5;

StringBuffer::StringBuffer(const char* str, size_t len) {
    size = 0;
    s = 0;

    // if the given string is null, leave this null,
    // otherwise set it, even empty.
    if (str) {
        size_t slen = strlen(str);
        size_t newlen = (len > slen) ? slen : len ;

        if(newlen) {
            getmem(newlen);
            strncpy(s, str, newlen);
            s[newlen]=0;
        }
        else {  // empty string
            getmem(1);
            s[0] = 0;
        }
    }
}

//Copy Costructor
StringBuffer::StringBuffer(const StringBuffer &sb) {
    size = 0;
    s = NULL;
    append(sb.c_str());
}

StringBuffer::~StringBuffer() {
    freemem();
}

StringBuffer& StringBuffer::append(const char* sNew) {
    if (sNew == NULL) {
        return *this;
    }

    unsigned long len = strlen(sNew);

    if (len == 0) {
        return *this;
    }
    if (s) {
        getmem(strlen(s) + len);
        strcat(s, sNew);
    }
    else {
        getmem(len);
        strcpy(s, sNew);
    }

    return *this;
}

StringBuffer& StringBuffer::append(unsigned long i, bool sign) {
    append(StringBuffer().sprintf(sign ? "%ld" : "%lu", i));

    return *this;
}

StringBuffer& StringBuffer::append(StringBuffer& str) {
    return append(str.getChars());
}

StringBuffer& StringBuffer::append(StringBuffer* str) {
    if (str)
        return append(str->getChars());
    else
        return *this;
}

StringBuffer& StringBuffer::set(const char* sNew) {
    if (sNew) {
        size_t len = strlen(sNew);
        if ( len ) {
            getmem( len );
            strcpy(s, sNew);
        }
        else if (s) {
            s[0]=0; // just make the string empty
        } else {
            getmem( 2 );
            strcpy(s, "");
        }
    }
    else {
        freemem();  // release the string and set it to null
    }

    return *this;
}

StringBuffer& StringBuffer::sprintf(const char* format, ...) {
    PLATFORM_VA_LIST ap;

    PLATFORM_VA_START(ap, format);
    this->vsprintf(format, ap);
    PLATFORM_VA_END(ap);

    return *this;
}

StringBuffer& StringBuffer::vsprintf(const char* format, PLATFORM_VA_LIST ap) {
    PLATFORM_VA_LIST aq;

    // ensure minimal size for first iteration
    int realsize = 255;

    do {
        // make a copy to keep ap valid for further iterations
#ifdef va_copy
        PLATFORM_VA_COPY(aq, ap);
#else
        aq = ap;
#endif

        if (size < (unsigned long)realsize) {
            s = (char*)realloc(s, (realsize + 1) * sizeof(char));
            if (s == NULL) {
                // Out of memory. Flush the string content and return
                size = 0;
                return *this;
            }
            size = realsize;
        }

        realsize = vsnprintf(s, size + 1, format, aq);
        if (realsize == -1) {
            // old-style vnsprintf: exact len unknown, try again with doubled size
            realsize = size * 2;
        }
        PLATFORM_VA_END(aq);
    } while((unsigned long)realsize > size);

    // free extra memory
    s = (char*)realloc(s, (realsize + 1) * sizeof(char));
    size = realsize;

    return *this;
}

const char* StringBuffer::getChars() const { return s; }

unsigned long StringBuffer::length() const {
    return (s) ? strlen(s) : 0;
}

// Watch out
StringBuffer& StringBuffer::reset() {
    freemem();
    return *this;
}

size_t StringBuffer::find(const char *str, size_t pos) const
{
    if (pos >= length()) {
        return npos;
    }
    char *p = strstr(s+pos, str);
    if(!p)
        return npos;
    return (p-s);
}

size_t StringBuffer::ifind(const char *str, size_t pos) const
{
    if (pos >= length())
        return npos;

    char *ls = strtolower(s+pos);
    char *lstr = strtolower(str);

    char *p = strstr(ls, lstr);

    size_t ret = (p) ? p-ls : npos;

    delete [] ls;
    delete [] lstr;

    return ret;
}

size_t StringBuffer::rfind(const char *str, size_t pos) const
{
    if (pos >= length())
        return npos;

    size_t tmp = StringBuffer::npos;
    int previous = pos;

    tmp = find(str, pos);
    if (tmp == StringBuffer::npos)
        return npos;

    while(1) {

        previous = tmp;
        tmp = find(str, tmp + 1);
        if (tmp == StringBuffer::npos)
            break;
    }

    return previous;

}

size_t StringBuffer::replace(const char *from, const char *to, size_t pos)
{
	size_t ret = npos;

    if (!s)
        return npos;

    if(pos>=length())
        return npos;

    char *p = strstr(s+pos, from);
    if (p) {
        size_t fpos = p - s;
        size_t flen = strlen(from), tlen = strlen(to);
        char *tail = 0;
        int ldiff = tlen - flen ;

        // reallocate if needed
        getmem(length() + ldiff);
        p = s + fpos;            // ensure that p is valid again
        // check is there is a remainder after the replaced token
        if( p[flen] ) {
            tail = new char[length()];
            strcpy(tail, p+flen);
        }
        // copy to in place of from
        strcpy(p, to);
        // copy the remainder of old string, if there is one
        if( tail ) {
            strcpy(p+tlen, tail);
            delete [] tail;
        }
		ret = p - s;
    }
    return ret;
}

// TODO: implement some smarter argorithm to avoid multiple reallocations
int StringBuffer::replaceAll(const char *from, const char *to, size_t pos) {
    int i=0;
    int len = strlen(to);
    size_t next;

    for(next=replace(from, to, pos); next != npos; next=replace(from,to,next + len) ) {
        i++;
    }
    return i;
}

ArrayList& StringBuffer::split(ArrayList &tokens, const char *separator) const {
    tokens.clear();
    size_t seplen = strlen(separator);
    char *base = s;
    char *p = strstr( base, separator );

    while( p )
    {
        StringBuffer token(base, p-base);
        tokens.add( token );
        base = p + seplen;
        p = strstr( base, separator );
    }
    StringBuffer token(base);
    tokens.add( token );

    return tokens;
}

StringBuffer& StringBuffer::join(ArrayList &tokens, const char *separator) {
    StringBuffer *line;
    size_t totlen = 0, seplen = strlen(separator);
    // Calc total size
    for (line=(StringBuffer *)tokens.front();
		 line;
         line=(StringBuffer *)tokens.next() ) {
        totlen += line->length() + seplen;
    }
    // Reserve mem
    reserve(totlen);
    // Join strings
    for (line=(StringBuffer *)tokens.front();
		 line;
         line=(StringBuffer *)tokens.next() ) {
        this->append(line->c_str());
        this->append(separator);
    }
    return *this;
}

StringBuffer StringBuffer::substr(size_t pos, size_t len) const {
    if(pos > strlen(s))
        return StringBuffer("");

	return (StringBuffer(s+pos, len));
}

void StringBuffer::reserve(size_t len) {
    getmem(len);
}

StringBuffer& StringBuffer::upperCase() {
    char* p = NULL;

    for(p = s; *p; p++) {
        *p=toupper(*p);
    }

    return *this;
}

StringBuffer& StringBuffer::lowerCase() {
    char* p = NULL;

    for(p = s; *p; p++) {
        *p=tolower(*p);
    }

    return *this;
}

/**
 * Perform case insensitive compare.
 * @return true if equals
 */
bool StringBuffer::icmp(const char *sc) const {
    return wcscmpIgnoreCase(s, sc);
}

ArrayElement* StringBuffer::clone() {
    return new StringBuffer(s);
}

bool StringBuffer::empty() const {
    if(!s)
        return true;
    if(!*s)
        return true;
    return false;
}

bool StringBuffer::null() const { return (s==0); }

// Member Operators
StringBuffer& StringBuffer::operator= (const char* sc)
    { return set(sc); }
StringBuffer& StringBuffer::operator= (const StringBuffer& sb)
    { return set(sb); }
StringBuffer& StringBuffer::operator+= (const char* sc)
    { append(sc); return *this; }
StringBuffer& StringBuffer::operator+= (const StringBuffer& s)
    { append(s); return *this; }
bool  StringBuffer::operator== (const char* sc) const
{
    if(!s)
        return (sc) ? false : true ;
    if (!sc)
        return false;

    return strcmp(s, sc) == 0;
}
bool  StringBuffer::operator== (const StringBuffer& sb) const
{
    return *this == sb.c_str();
}

bool  StringBuffer::operator!= (const char* sc) const
{
    return !(*this == sc);
}
bool  StringBuffer::operator!= (const StringBuffer& s) const
{
    return !(*this == s.c_str());
}

// Function operators
StringBuffer operator+(const StringBuffer& x, const char *y)
{
  StringBuffer result(x);
  result.append(y);
  return result;
}

//size_t StringBuffer_memcount = 0;

// Private allocator
void StringBuffer::getmem(size_t len)
{
    //fprintf(stderr, "GETMEM len=%ld s=%lx size=%ld\n", len, s, size);
    if(len > size) {
        // Remember the old length (0 for the null string)
        size_t oldlen = length();
        // Realloc the string (like malloc when s is null)
        s = (char *)realloc(s, (len+1) * sizeof(char) );
        //StringBuffer_memcount += (len-size);
        size = len;
        // Make sure s is terminated at the old position
        // (malloc may fill the buffer with rubbish)
        s[oldlen] = 0;
        //fprintf(stderr, "\t\ts=%lx size=%ld alloc=%ld\n", s, size, alloclen);
    }
}

// Private deallocator
void StringBuffer::freemem()
{
    if(s) {
        free(s); s = 0;
        //fprintf(stderr, "FREEMEM s=%lx size=%ld\n", s, size);
    }
    //StringBuffer_memcount -= size;
    size = 0;
}

<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "config.h"

#include <cmath>
#include <sys/time.h>
#include <vector>
#include <map>
#include <string>
#include <sstream>

#include <dune/stuff/test/gtest/gtest.h>
#include <dune/stuff/common/exceptions.hh>

#include "common.hh"

void busywait(const int ms)
{
  // "round" up to next full 10 ms to align with native timer res
  const int milliseconds = (ms/10)*10 + 10;
  timeval start, end;
  gettimeofday(&start, NULL);
  do {
   gettimeofday(&end, NULL);
  } while (((end.tv_sec - start.tv_sec)*1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds*1000);
} // ... busywait(...)

namespace Dune {
namespace Stuff {
namespace Test {
namespace internal {

std::pair< size_t, ssize_t > convert_to_scientific(const double number, const size_t precision)
{
  // see http://www.mathworks.com/matlabcentral/newsreader/view_thread/151859
  const double sign = (number > 0.0) ? 1.0 : -1.0;
  const double tmp = std::log10(std::abs(number));
  ssize_t exponent = ((tmp > 0) ? 1 : -1) * std::floor(std::abs(tmp));
  double coefficient = sign * std::pow(10.0, tmp - exponent);
  if (std::abs(coefficient) < 1.0) {
    coefficient *= 10.0;
    exponent -= 1;
  }
  const double factor = std::pow(10, precision);
  return std::make_pair(size_t(std::round(factor * coefficient)), exponent);
} // ... convert_to_scientific(...)

std::string print_vector(const std::vector< double >& vec)
{
  if (vec.empty())
    return "{}";
  else {
    std::stringstream ss;
    ss << "{" << std::setprecision(2) << std::scientific << vec[0];
    for (size_t ii = 1; ii < vec.size(); ++ii)
      ss << ", " << std::setprecision(2) << std::scientific << vec[ii];
    ss << "}";
    return ss.str();
  }
} // ... print_vector(...)

} // namespace internal

void check_eoc_study_for_success(const Dune::Stuff::Common::ConvergenceStudy& study,
                                 const std::map< std::string, std::vector< double > >& results_map)
{
  for (const auto& norm : study.used_norms()) {
    const auto expected_results = study.expected_results(norm);
    const auto results_search = results_map.find(norm);
    EXPECT_NE(results_search, results_map.end())
        << "          norm = " << norm;
    if (results_search == results_map.end())
      return;
    const auto& actual_results = results_search->second;
    EXPECT_LE(actual_results.size(), expected_results.size())
        << "          norm = " << norm;
    if (actual_results.size() > expected_results.size())
      return;
    for (size_t ii = 0; ii < actual_results.size(); ++ii) {
      const auto actual_result   = internal::convert_to_scientific(actual_results[ii], 2);
      const auto expected_result = internal::convert_to_scientific(expected_results[ii], 2);
      const auto actual_exponent = actual_result.second;
      const auto expected_exponent = expected_result.second;
      EXPECT_EQ(actual_exponent, expected_exponent)
          << "          Exponent comparison (in scientific notation, precision 2) failed for\n"
          << "          norm: " << norm << "\n"
          << "          actual_results[" << ii << "]   = " << actual_results[ii] << "\n"
          << "          expected_results[" << ii << "] = " << expected_results[ii];
      if (actual_exponent != expected_exponent)
        return;
      const auto actual_coefficient = actual_result.first;
      const auto expected_coefficient = expected_result.first;
      EXPECT_EQ(actual_coefficient, expected_coefficient)
          << "          Coefficient comparison (in scientific notation, precision 2) failed for\n"
          << "          norm: " << norm << "\n"
          << "          actual_results[" << ii << "]   = " << actual_results[ii] << "\n"
          << "          expected_results[" << ii << "] = " << expected_results[ii];
    }
  }
} // ... check_eoc_study_for_success(...)

void print_collected_eoc_study_results(const std::map< std::string, std::vector< double > >& results, std::ostream& out)
{
  if (results.empty())
    DUNE_THROW(Exceptions::wrong_input_given, "Given results must not be empty!");
  std::vector< std::string > actually_used_norms;
  for (const auto& element : results)
    actually_used_norms.push_back(element.first);

  out << "if (type == \"" << actually_used_norms[0] << "\")\n";
  out << "  return " << internal::print_vector(results.at(actually_used_norms[0])) << ";\n";
  for (size_t ii = 1; ii < actually_used_norms.size(); ++ii) {
    out << "else if (type == \"" << actually_used_norms[ii] << "\")\n";
    out << "  return " << internal::print_vector(results.at(actually_used_norms[ii])) << ";\n";
  }
  out << "else\n";
  out << "  EXPECT_TRUE(false) << \"test results missing for type: \" << type;\n";
  out << "return {};" << std::endl;
} // ... print_collected_eoc_study_results(...)

} // namespace Test
} // namespace Stuff
} // namespace Dune
<commit_msg>[test.common] switch expected/actual to match gtest<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "config.h"

#include <cmath>
#include <sys/time.h>
#include <vector>
#include <map>
#include <string>
#include <sstream>

#include <dune/stuff/test/gtest/gtest.h>
#include <dune/stuff/common/exceptions.hh>

#include "common.hh"

void busywait(const int ms)
{
  // "round" up to next full 10 ms to align with native timer res
  const int milliseconds = (ms/10)*10 + 10;
  timeval start, end;
  gettimeofday(&start, NULL);
  do {
   gettimeofday(&end, NULL);
  } while (((end.tv_sec - start.tv_sec)*1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds*1000);
} // ... busywait(...)

namespace Dune {
namespace Stuff {
namespace Test {
namespace internal {

std::pair< size_t, ssize_t > convert_to_scientific(const double number, const size_t precision)
{
  // see http://www.mathworks.com/matlabcentral/newsreader/view_thread/151859
  const double sign = (number > 0.0) ? 1.0 : -1.0;
  const double tmp = std::log10(std::abs(number));
  ssize_t exponent = ((tmp > 0) ? 1 : -1) * std::floor(std::abs(tmp));
  double coefficient = sign * std::pow(10.0, tmp - exponent);
  if (std::abs(coefficient) < 1.0) {
    coefficient *= 10.0;
    exponent -= 1;
  }
  const double factor = std::pow(10, precision);
  return std::make_pair(size_t(std::round(factor * coefficient)), exponent);
} // ... convert_to_scientific(...)

std::string print_vector(const std::vector< double >& vec)
{
  if (vec.empty())
    return "{}";
  else {
    std::stringstream ss;
    ss << "{" << std::setprecision(2) << std::scientific << vec[0];
    for (size_t ii = 1; ii < vec.size(); ++ii)
      ss << ", " << std::setprecision(2) << std::scientific << vec[ii];
    ss << "}";
    return ss.str();
  }
} // ... print_vector(...)

} // namespace internal

void check_eoc_study_for_success(const Dune::Stuff::Common::ConvergenceStudy& study,
                                 const std::map< std::string, std::vector< double > >& results_map)
{
  for (const auto& norm : study.used_norms()) {
    const auto expected_results = study.expected_results(norm);
    const auto results_search = results_map.find(norm);
    EXPECT_NE(results_search, results_map.end())
        << "          norm = " << norm;
    if (results_search == results_map.end())
      return;
    const auto& actual_results = results_search->second;
    EXPECT_LE(actual_results.size(), expected_results.size())
        << "          norm = " << norm;
    if (actual_results.size() > expected_results.size())
      return;
    for (size_t ii = 0; ii < actual_results.size(); ++ii) {
      const auto actual_result   = internal::convert_to_scientific(actual_results[ii], 2);
      const auto expected_result = internal::convert_to_scientific(expected_results[ii], 2);
      const auto actual_exponent = actual_result.second;
      const auto expected_exponent = expected_result.second;
      EXPECT_EQ(expected_exponent, actual_exponent)
          << "          Exponent comparison (in scientific notation, precision 2) failed for\n"
          << "          norm: " << norm << "\n"
          << "          actual_results[" << ii << "]   = " << actual_results[ii] << "\n"
          << "          expected_results[" << ii << "] = " << expected_results[ii];
      if (actual_exponent != expected_exponent)
        return;
      const auto actual_coefficient = actual_result.first;
      const auto expected_coefficient = expected_result.first;
      EXPECT_EQ(expected_coefficient, actual_coefficient)
          << "          Coefficient comparison (in scientific notation, precision 2) failed for\n"
          << "          norm: " << norm << "\n"
          << "          actual_results[" << ii << "]   = " << actual_results[ii] << "\n"
          << "          expected_results[" << ii << "] = " << expected_results[ii];
    }
  }
} // ... check_eoc_study_for_success(...)

void print_collected_eoc_study_results(const std::map< std::string, std::vector< double > >& results, std::ostream& out)
{
  if (results.empty())
    DUNE_THROW(Exceptions::wrong_input_given, "Given results must not be empty!");
  std::vector< std::string > actually_used_norms;
  for (const auto& element : results)
    actually_used_norms.push_back(element.first);

  out << "if (type == \"" << actually_used_norms[0] << "\")\n";
  out << "  return " << internal::print_vector(results.at(actually_used_norms[0])) << ";\n";
  for (size_t ii = 1; ii < actually_used_norms.size(); ++ii) {
    out << "else if (type == \"" << actually_used_norms[ii] << "\")\n";
    out << "  return " << internal::print_vector(results.at(actually_used_norms[ii])) << ";\n";
  }
  out << "else\n";
  out << "  EXPECT_TRUE(false) << \"test results missing for type: \" << type;\n";
  out << "return {};" << std::endl;
} // ... print_collected_eoc_study_results(...)

} // namespace Test
} // namespace Stuff
} // namespace Dune
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <mpi.h>

//TODO
int simple_sieves(int origin) {
	return 0;
}

int sieves(int origin, int p, int id) {
	// index range from 0 to origin (origin + 1 elements)
	int num = (origin + 1) / p + ((origin + 1) % p? 1: 0);
	assert(num);
	bool *array = new bool[num];
	// The range of process n is [n * num, 2n * num - 1]
	memset(array, true, sizeof(bool) * num);
	if (!id) array[0] = array[1] = false;
	int prime = 0;
	while (prime * prime <= origin) {
		do
			prime++;
		while (!array[prime]);
		MPI_Bcast(&prime, 1, MPI_INT, 0, MPI_COMM_WORLD);
		for (int i = 0; i < num; i++)
			//array[i] isn't prime if 1)array[i] % prime == 0 2)array[i] != prime
			if (array[i] && (id * num + i) % prime == 0 && id * num + i != prime)
				array[i] = !array[i];
	}
	int cnt = 0;
	for (int i = 0; i < num; i++)
		if (array[i] && id * num + i <= origin) {
		 cnt++;
		}
	delete[] array;
	int ans;
	MPI_Reduce(&cnt, &ans, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
	return ans;
}

int main(int argc, char *argv[]) {
	int origin;
	assert(argc >= 2 && sscanf(argv[1], "%d", &origin) >= 0);
	MPI_Init(&argc, &argv);
	int id;
	MPI_Comm_rank(MPI_COMM_WORLD, &id);
	int p;
	MPI_Comm_size(MPI_COMM_WORLD, &p);
	// num: the integer number of each process
	// n / p > sqrt(n) -> n > p ^ 2
	int ans;
	if (p * p > origin)
		ans = simple_sieves(origin);
	else
		ans = sieves(origin, p, id);
	if (!id) printf("Number of prime is %d.\n", ans);
	MPI_Finalize();
	return 0;
}
<commit_msg>finish simple Sieves (for realitive small number)<commit_after>#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <mpi.h>

int simple_sieves(int origin) {
	bool *array = new bool[origin + 1];
	memset(array, true, sizeof(bool) * (origin + 1));
	array[0] = array[1] = false;
	int prime = 0;
	while (prime * prime <= origin) {
		do
			prime++;
		while (!array[prime]);
		printf("%d\n", prime);
		for (int i = prime * prime; i <= origin; i++)
			if (array[i] && i % prime == 0)
				array[i] = !array[i];
	}
	int ans = 0;
	for (int i = 0; i <= origin; i++)
		if (array[i]) ans++;
	return ans;
}

int sieves(int origin, int p, int id) {
	// index range from 0 to origin (origin + 1 elements)
	int num = (origin + 1) / p + ((origin + 1) % p? 1: 0);
	assert(num);
	bool *array = new bool[num];
	// The range of process n is [n * num, 2n * num - 1]
	memset(array, true, sizeof(bool) * num);
	if (!id) array[0] = array[1] = false;
	int prime = 0;
	while (prime * prime <= origin) {
		do
			prime++;
		while (!array[prime]);
		MPI_Bcast(&prime, 1, MPI_INT, 0, MPI_COMM_WORLD);
		for (int i = 0; i < num; i++)
			//array[i] isn't prime if 1)array[i] % prime == 0 2)array[i] != prime
			if (array[i] && (id * num + i) % prime == 0 && id * num + i != prime)
				array[i] = !array[i];
	}
	int cnt = 0;
	for (int i = 0; i < num; i++)
		if (array[i] && id * num + i <= origin) {
		 cnt++;
		}
	delete[] array;
	int ans;
	MPI_Reduce(&cnt, &ans, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
	return ans;
}

int main(int argc, char *argv[]) {
	int origin;
	assert(argc >= 2 && sscanf(argv[1], "%d", &origin) >= 0);
	MPI_Init(&argc, &argv);
	int id;
	MPI_Comm_rank(MPI_COMM_WORLD, &id);
	int p;
	MPI_Comm_size(MPI_COMM_WORLD, &p);
	// num: the integer number of each process
	// n / p > sqrt(n)(low floor) -> n > p ^ 2
	int ans;
	if (p * p > origin)
		ans = simple_sieves(origin);
	else
		ans = sieves(origin, p, id);
	if (!id) printf("Number of prime is %d.\n", ans);
	MPI_Finalize();
	return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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
 *
 * 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 "modules/common/math/math_utils.h"

#include "gtest/gtest.h"

namespace apollo {
namespace common {
namespace math {

TEST(MathUtilsTest, CrossProd) {
  EXPECT_NEAR(CrossProd({0, 0}, {0, 1}, {1, 0}), -1.0, 1e-5);
  EXPECT_NEAR(CrossProd({0, 0}, {1, 0}, {0, 1}), 1.0, 1e-5);
  EXPECT_NEAR(CrossProd({0, 1}, {0, 0}, {1, 0}), 1.0, 1e-5);
  EXPECT_NEAR(CrossProd({1, 2}, {3, 4}, {5, 6}), 0.0, 1e-5);
  EXPECT_NEAR(CrossProd({1, 2}, {3, 4}, {6, 5}), -4.0, 1e-5);
  EXPECT_NEAR(CrossProd({2, 2}, {7, 5}, {3, 4}), 7.0, 1e-5);
}

TEST(MathUtilsTest, InnerProd) {
  EXPECT_NEAR(InnerProd({0, 0}, {0, 1}, {1, 0}), 0.0, 1e-5);
  EXPECT_NEAR(InnerProd({0, 0}, {1, 0}, {0, 1}), 0.0, 1e-5);
  EXPECT_NEAR(InnerProd({0, 1}, {0, 0}, {1, 0}), 1.0, 1e-5);
  EXPECT_NEAR(InnerProd({1, 2}, {3, 4}, {5, 6}), 16.0, 1e-5);
  EXPECT_NEAR(InnerProd({1, 2}, {3, 4}, {6, 5}), 16.0, 1e-5);
  EXPECT_NEAR(InnerProd({2, 2}, {7, 5}, {3, 4}), 11.0, 1e-5);
  EXPECT_NEAR(InnerProd({2, 2}, {0, 0}, {3, 4}), -6.0, 1e-5);
}

TEST(MathUtilsTest, WrapAngle) {
  EXPECT_NEAR(WrapAngle(-1.2), -1.2 + M_PI * 2.0, 1e-6);
  EXPECT_NEAR(WrapAngle(3.4), 3.4, 1e-6);
  EXPECT_NEAR(WrapAngle(5.6), 5.6, 1e-6);
  EXPECT_NEAR(WrapAngle(7.8), 7.8 - M_PI * 2.0, 1e-6);
  EXPECT_NEAR(WrapAngle(12.4), std::fmod(12.4, M_PI * 2.0), 1e-6);
  EXPECT_NEAR(WrapAngle(-12.4), std::fmod(-12.4, M_PI * 2.0) + M_PI * 2.0,
              1e-6);
}

TEST(MathUtilsTest, NormalizeAngle) {
  EXPECT_DOUBLE_EQ(1.5, NormalizeAngle(1.5));
  EXPECT_DOUBLE_EQ(1.5 - M_PI, NormalizeAngle(1.5 + M_PI));
  EXPECT_DOUBLE_EQ(1.5, NormalizeAngle(1.5 + M_PI * 2));
  EXPECT_DOUBLE_EQ(1.5, NormalizeAngle(1.5 - M_PI * 2));
  EXPECT_DOUBLE_EQ(-1.5, NormalizeAngle(-1.5));
  EXPECT_DOUBLE_EQ(-9.0 + M_PI * 2, NormalizeAngle(-9.0));
  EXPECT_DOUBLE_EQ(-M_PI, NormalizeAngle(-M_PI));
  EXPECT_DOUBLE_EQ(-M_PI, NormalizeAngle(M_PI));
  EXPECT_DOUBLE_EQ(-M_PI, NormalizeAngle(-M_PI * 3));
  EXPECT_DOUBLE_EQ(-M_PI, NormalizeAngle(M_PI * 3));
  EXPECT_DOUBLE_EQ(0.0, NormalizeAngle(M_PI * 4));
}

TEST(MathUtilsTest, Square) {
  EXPECT_DOUBLE_EQ(121.0, Square(11.0));
  EXPECT_FLOAT_EQ(144.0f, Square(-12.0f));
  EXPECT_EQ(169, Square(-13));
  EXPECT_EQ(2147395600, Square(46340));
  EXPECT_EQ(-2147479015, Square(46341));  // Overflow!
}

}  // namespace math
}  // namespace common
}  // namespace apollo
<commit_msg>add unit tests<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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
 *
 * 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 "modules/common/math/math_utils.h"

#include "gtest/gtest.h"

namespace apollo {
namespace common {
namespace math {

TEST(MathUtilsTest, CrossProd) {
  EXPECT_NEAR(CrossProd({0, 0}, {0, 1}, {1, 0}), -1.0, 1e-5);
  EXPECT_NEAR(CrossProd({0, 0}, {1, 0}, {0, 1}), 1.0, 1e-5);
  EXPECT_NEAR(CrossProd({0, 1}, {0, 0}, {1, 0}), 1.0, 1e-5);
  EXPECT_NEAR(CrossProd({1, 2}, {3, 4}, {5, 6}), 0.0, 1e-5);
  EXPECT_NEAR(CrossProd({1, 2}, {3, 4}, {6, 5}), -4.0, 1e-5);
  EXPECT_NEAR(CrossProd({2, 2}, {7, 5}, {3, 4}), 7.0, 1e-5);
}

TEST(MathUtilsTest, InnerProd) {
  EXPECT_NEAR(InnerProd({0, 0}, {0, 1}, {1, 0}), 0.0, 1e-5);
  EXPECT_NEAR(InnerProd({0, 0}, {1, 0}, {0, 1}), 0.0, 1e-5);
  EXPECT_NEAR(InnerProd({0, 1}, {0, 0}, {1, 0}), 1.0, 1e-5);
  EXPECT_NEAR(InnerProd({1, 2}, {3, 4}, {5, 6}), 16.0, 1e-5);
  EXPECT_NEAR(InnerProd({1, 2}, {3, 4}, {6, 5}), 16.0, 1e-5);
  EXPECT_NEAR(InnerProd({2, 2}, {7, 5}, {3, 4}), 11.0, 1e-5);
  EXPECT_NEAR(InnerProd({2, 2}, {0, 0}, {3, 4}), -6.0, 1e-5);
}

TEST(MathUtilsTest, WrapAngle) {
  EXPECT_NEAR(WrapAngle(-1.2), -1.2 + M_PI * 2.0, 1e-6);
  EXPECT_NEAR(WrapAngle(3.4), 3.4, 1e-6);
  EXPECT_NEAR(WrapAngle(5.6), 5.6, 1e-6);
  EXPECT_NEAR(WrapAngle(7.8), 7.8 - M_PI * 2.0, 1e-6);
  EXPECT_NEAR(WrapAngle(12.4), std::fmod(12.4, M_PI * 2.0), 1e-6);
  EXPECT_NEAR(WrapAngle(-12.4), std::fmod(-12.4, M_PI * 2.0) + M_PI * 2.0,
              1e-6);
}

TEST(MathUtilsTest, NormalizeAngle) {
  EXPECT_DOUBLE_EQ(1.5, NormalizeAngle(1.5));
  EXPECT_DOUBLE_EQ(1.5 - M_PI, NormalizeAngle(1.5 + M_PI));
  EXPECT_DOUBLE_EQ(1.5, NormalizeAngle(1.5 + M_PI * 2));
  EXPECT_DOUBLE_EQ(1.5, NormalizeAngle(1.5 - M_PI * 2));
  EXPECT_DOUBLE_EQ(-1.5, NormalizeAngle(-1.5));
  EXPECT_DOUBLE_EQ(-9.0 + M_PI * 2, NormalizeAngle(-9.0));
  EXPECT_DOUBLE_EQ(-M_PI, NormalizeAngle(-M_PI));
  EXPECT_DOUBLE_EQ(-M_PI, NormalizeAngle(M_PI));
  EXPECT_DOUBLE_EQ(-M_PI, NormalizeAngle(-M_PI * 3));
  EXPECT_DOUBLE_EQ(-M_PI, NormalizeAngle(M_PI * 3));
  EXPECT_DOUBLE_EQ(0.0, NormalizeAngle(M_PI * 4));
}

TEST(MathUtilsTest, Square) {
  EXPECT_DOUBLE_EQ(121.0, Square(11.0));
  EXPECT_FLOAT_EQ(144.0f, Square(-12.0f));
  EXPECT_EQ(169, Square(-13));
  EXPECT_EQ(2147395600, Square(46340));
  EXPECT_EQ(-2147479015, Square(46341));  // Overflow!
}

TEST(MathUtilsTest, Sqr) {
  EXPECT_DOUBLE_EQ(121.0, Sqr(11.0));
  EXPECT_DOUBLE_EQ(0.25, Sqr(0.5));
  EXPECT_DOUBLE_EQ(169.0, Sqr(-13.0));
}

TEST(MathUtilsTest, Sigmoid) {
  EXPECT_DOUBLE_EQ(0.5, Sigmoid(0.0));
}

TEST(MathUtilsTest, Clamp) {
  EXPECT_EQ(1, Clamp(1, 0, 6));
  EXPECT_EQ(6, Clamp(7, 0, 6));
  EXPECT_EQ(0, Clamp(-1, 0, 6));
  EXPECT_EQ(0, Clamp(0, 0, 6)); // test lower bound as input
  EXPECT_EQ(6, Clamp(6, 0, 6)); // test upper bound as input
}

TEST(MathUtilsTest, RotateAxis) {
  double x,y;
  double expected_x,expected_y;
  expected_x = sqrt(2);
  expected_y = 0;
  RotateAxis(M_PI/4, 1.0, 1.0, &x, &y);
  EXPECT_DOUBLE_EQ(expected_x, x);
  EXPECT_NEAR(expected_y, y, 1e-5);

  expected_x = 1;
  expected_y = 0;
  RotateAxis(M_PI/2, 0.0, 1.0, &x, &y);
  EXPECT_DOUBLE_EQ(expected_x, x);
  EXPECT_NEAR(expected_y, y,  1e-5);

  expected_x = -1;
  expected_y = 0;
  RotateAxis(M_PI, 1.0, 0.0, &x, &y);
  EXPECT_DOUBLE_EQ(expected_x, x);
  EXPECT_NEAR(expected_y, y,  1e-5);
}

}  // namespace math
}  // namespace common
}  // namespace apollo
<|endoftext|>


<commit_before>/*
    Crystal Space Windowing System: dialog window class
    Copyright (C) 1998,1999 by Andrew Zabolotny <bit@eltech.ru>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "cssys/csinput.h"
#include "csws/cswindow.h"
#include "csws/csdialog.h"
#include "csws/csskin.h"

#define SKIN ((csDialogSkin *)skinslice)

csDialog::csDialog (csComponent *iParent, csDialogFrameStyle iFrameStyle)
  : csComponent (iParent), FrameBitmap(NULL), delFrameBitmap(false)
{
  SetPalette (CSPAL_DIALOG);
  state |= CSS_SELECTABLE;
  DragStyle = 0;
  first = NULL;
  GridX = GridY = -1;
  SnapSizeToGrid = false;
  if (parent)
    parent->SendCommand (cscmdWindowSetClient, (void *)this);

  // If our parent is a dialog as well, mark ourselves as transparent
  // to avoid untiled textures as backgrounds.
  if (parent)
  {
    char *ps = parent->GetSkinName ();
    if (ps && !strcmp (ps, "Dialog"))
      SetAlpha (255);
  }

	if (FrameStyle == csdfsBitmap)
		SetState (CSS_TRANSPARENT, true);

  ApplySkin (GetSkin ());
  SetFrameStyle (iFrameStyle);
}

csDialog::~csDialog()
{
 if (delFrameBitmap && FrameBitmap) delete FrameBitmap;
}

bool csDialog::HandleEvent (iEvent &Event)
{
  if (csComponent::HandleEvent (Event))
    return true;

  switch (Event.Type)
  {
    case csevMouseMove:
    case csevMouseDown:
      if (HandleDragEvent (Event, BorderWidth, BorderHeight))
        return true;
      break;
    case csevKeyDown:
      switch (Event.Key.Code)
      {
        case CSKEY_TAB:
          if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == CSMASK_SHIFT)
          {
            SetFocused (PrevGroup ());
            AdjustFocused (false);
            return true;
          }
          else if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == 0)
          {
            SetFocused (NextGroup ());
            AdjustFocused (true);
            return true;
          } /* endif */
          break;
        case CSKEY_LEFT:
        case CSKEY_UP:
          if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == 0)
          {
            SetFocused (PrevControl ());
            AdjustFocused (false);
            return true;
          }
          break;
        case CSKEY_RIGHT:
        case CSKEY_DOWN:
          if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == 0)
          {
            SetFocused (NextControl ());
            AdjustFocused (true);
            return true;
          }
          break;
        case CSKEY_ENTER:
          if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == 0)
          {
            csComponent *def = GetDefault ();
            if (def->SendCommand (cscmdActivate, NULL) != def)
              if (def != focused)
                focused->SendCommand (cscmdActivate, NULL);
            return true;
          }
          break;
      } /* endswitch */
      break;
    case csevCommand:
      if (parent)
        return parent->HandleEvent (Event);
      break;
  } /* endswitch */
  return false;
}

void csDialog::AdjustFocused (bool forward)
{
  int i = 10;
  while (i--)
  {
    if (!focused->GetState (CSS_DISABLED))
      break;
    SetFocused (forward ? NextControl () : PrevControl ());
  }
}

bool csDialog::PlaceItems ()
{
  if ((GridX >= 0) && (GridY >= 0))
  {
    if (!first)
      first = focused;
    if (!first)
      return true;

    csComponent *cur = first;
    int curX = BorderWidth + GridX, curY = BorderHeight + GridY;
    int maxX = -1, maxY = -1;
    do
    {
      int lastX, lastY;
      for ( ; ; )
      {
        lastX = curX + cur->bound.Width ();
        lastY = curY + cur->bound.Height ();
        if (lastX > bound.Width () - BorderWidth)
        {
          if (curX == BorderWidth + GridX)
            break;
          curX = BorderWidth + GridX;
          curY = maxY + GridY;
        }
        else
          break;
      } /* endfor */
      if (!cur->bound.IsEmpty ())
      {
        cur->SetRect (curX, curY, lastX, lastY);
        if (lastX > maxX)
          maxX = lastX;
        if (lastY > maxY)
          maxY = lastY;
        curX = lastX + GridX;
      } /* endif */
      cur = cur->next;
    } while (cur != first); /* enddo */
    if (SnapSizeToGrid)
      return csComponent::SetRect (bound.xmin, bound.ymin,
        bound.xmin + maxX + GridX + BorderWidth,
        bound.ymin + maxY + GridY + BorderHeight);
  } /* endif */
  return true;
}

bool csDialog::SetRect (int xmin, int ymin, int xmax, int ymax)
{
  if (csComponent::SetRect (xmin, ymin, xmax, ymax))
    return PlaceItems ();
  return false;
}

static bool do_checksize (csComponent *comp, void *param)
{
  csRect *r = (csRect *)param;
  if (comp->bound.xmin < r->xmin)
    r->xmin = comp->bound.xmin;
  if (comp->bound.ymin < r->ymin)
    r->ymin = comp->bound.ymin;
  if (comp->bound.xmax > r->xmax)
    r->xmax = comp->bound.xmax;
  if (comp->bound.ymax > r->ymax)
    r->ymax = comp->bound.ymax;
  return false;
}

bool csDialog::do_topleft (csComponent *comp, void *param)
{
  csDialog *self = (csDialog *)param;
  comp->SetPos (self->BorderWidth + self->GridX,
    self->BorderHeight + self->GridY);
  return false;
}

void csDialog::SuggestSize (int &w, int &h)
{
  // If we have no children, we have some default size
  if (!top)
  {
    w = h = 8;
    return;
  }

  /// If we never auto-placed the items, place them at top-left corner
  if ((GridX >= 0) && (GridY >= 0) && !first)
    ForEach (do_topleft, this);
  csRect rect (999999, 999999, 0, 0);
  ForEach (do_checksize, &rect);
  if (rect.xmin == 999999)
    rect.xmin = BorderWidth;
  if (rect.ymin == 999999)
    rect.ymin = BorderHeight;
  w = rect.xmin + rect.xmax;
  h = rect.ymin + rect.ymax;
}

void csDialog::FixSize (int &newW, int &newH)
{
  if ((GridX >= 0) && (GridY >= 0))
  {
    int minw,minh;
    minw = (BorderWidth + GridX) * 2;
    minh = (BorderHeight + GridY) * 2;
    if (first)
    {
      minw += first->bound.Width ();
      minh += first->bound.Height ();
    }
    // Don't allow too small windows
    if (newW < minw) newW = minw;
    if (newH < minh) newH = minh;
  }
}

void csDialog::SetBorderSize (int w, int h)
{
  BorderWidth = w;
  BorderHeight = h;
  csComponent::SetRect (bound);
}

void csDialog::SetFrameStyle (csDialogFrameStyle iFrameStyle)
{
  FrameStyle = iFrameStyle;
  SKIN->SetBorderSize (*this);
  csComponent::SetRect (bound);
  Invalidate ();
}

void csDialog::SetAlpha (uint8 iAlpha)
{
	Alpha = iAlpha;

	if (Alpha || FrameStyle == csdfsBitmap)
  	SetState (CSS_TRANSPARENT, true);
  else
  	SetState (CSS_TRANSPARENT, false);
}

void
csDialog::SetFrameBitmap(csPixmap *iFrameBitmap, bool iDelFrameBitmap)
{
	// Delete the previous bitmap, if it needs to be
	if (delFrameBitmap && FrameBitmap)
	{
		delete FrameBitmap;
		delFrameBitmap=false;
		FrameBitmap=NULL;
	}

	// Set the new one only	if there's something to set
	if (iFrameBitmap) {
		FrameBitmap = iFrameBitmap;
		delFrameBitmap = iDelFrameBitmap;
	}
}

<commit_msg>Fixed my formatting errors.<commit_after>/*
    Crystal Space Windowing System: dialog window class
    Copyright (C) 1998,1999 by Andrew Zabolotny <bit@eltech.ru>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "cssys/csinput.h"
#include "csws/cswindow.h"
#include "csws/csdialog.h"
#include "csws/csskin.h"

#define SKIN ((csDialogSkin *)skinslice)

csDialog::csDialog (csComponent *iParent, csDialogFrameStyle iFrameStyle)
  : csComponent (iParent), FrameBitmap(NULL), delFrameBitmap(false)
{
  SetPalette (CSPAL_DIALOG);
  state |= CSS_SELECTABLE;
  DragStyle = 0;
  first = NULL;
  GridX = GridY = -1;
  SnapSizeToGrid = false;
  if (parent)
    parent->SendCommand (cscmdWindowSetClient, (void *)this);

  // If our parent is a dialog as well, mark ourselves as transparent
  // to avoid untiled textures as backgrounds.
  if (parent)
  {
    char *ps = parent->GetSkinName ();
    if (ps && !strcmp (ps, "Dialog"))
      SetAlpha (255);
  }

  if (FrameStyle == csdfsBitmap)
    SetState (CSS_TRANSPARENT, true);

  ApplySkin (GetSkin ());
  SetFrameStyle (iFrameStyle);
}

csDialog::~csDialog()
{
 if (delFrameBitmap && FrameBitmap) delete FrameBitmap;
}

bool csDialog::HandleEvent (iEvent &Event)
{
  if (csComponent::HandleEvent (Event))
    return true;

  switch (Event.Type)
  {
    case csevMouseMove:
    case csevMouseDown:
      if (HandleDragEvent (Event, BorderWidth, BorderHeight))
        return true;
      break;
    case csevKeyDown:
      switch (Event.Key.Code)
      {
        case CSKEY_TAB:
          if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == CSMASK_SHIFT)
          {
            SetFocused (PrevGroup ());
            AdjustFocused (false);
            return true;
          }
          else if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == 0)
          {
            SetFocused (NextGroup ());
            AdjustFocused (true);
            return true;
          } /* endif */
          break;
        case CSKEY_LEFT:
        case CSKEY_UP:
          if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == 0)
          {
            SetFocused (PrevControl ());
            AdjustFocused (false);
            return true;
          }
          break;
        case CSKEY_RIGHT:
        case CSKEY_DOWN:
          if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == 0)
          {
            SetFocused (NextControl ());
            AdjustFocused (true);
            return true;
          }
          break;
        case CSKEY_ENTER:
          if ((Event.Key.Modifiers & CSMASK_ALLSHIFTS) == 0)
          {
            csComponent *def = GetDefault ();
            if (def->SendCommand (cscmdActivate, NULL) != def)
              if (def != focused)
                focused->SendCommand (cscmdActivate, NULL);
            return true;
          }
          break;
      } /* endswitch */
      break;
    case csevCommand:
      if (parent)
        return parent->HandleEvent (Event);
      break;
  } /* endswitch */
  return false;
}

void csDialog::AdjustFocused (bool forward)
{
  int i = 10;
  while (i--)
  {
    if (!focused->GetState (CSS_DISABLED))
      break;
    SetFocused (forward ? NextControl () : PrevControl ());
  }
}

bool csDialog::PlaceItems ()
{
  if ((GridX >= 0) && (GridY >= 0))
  {
    if (!first)
      first = focused;
    if (!first)
      return true;

    csComponent *cur = first;
    int curX = BorderWidth + GridX, curY = BorderHeight + GridY;
    int maxX = -1, maxY = -1;
    do
    {
      int lastX, lastY;
      for ( ; ; )
      {
        lastX = curX + cur->bound.Width ();
        lastY = curY + cur->bound.Height ();
        if (lastX > bound.Width () - BorderWidth)
        {
          if (curX == BorderWidth + GridX)
            break;
          curX = BorderWidth + GridX;
          curY = maxY + GridY;
        }
        else
          break;
      } /* endfor */
      if (!cur->bound.IsEmpty ())
      {
        cur->SetRect (curX, curY, lastX, lastY);
        if (lastX > maxX)
          maxX = lastX;
        if (lastY > maxY)
          maxY = lastY;
        curX = lastX + GridX;
      } /* endif */
      cur = cur->next;
    } while (cur != first); /* enddo */
    if (SnapSizeToGrid)
      return csComponent::SetRect (bound.xmin, bound.ymin,
        bound.xmin + maxX + GridX + BorderWidth,
        bound.ymin + maxY + GridY + BorderHeight);
  } /* endif */
  return true;
}

bool csDialog::SetRect (int xmin, int ymin, int xmax, int ymax)
{
  if (csComponent::SetRect (xmin, ymin, xmax, ymax))
    return PlaceItems ();
  return false;
}

static bool do_checksize (csComponent *comp, void *param)
{
  csRect *r = (csRect *)param;
  if (comp->bound.xmin < r->xmin)
    r->xmin = comp->bound.xmin;
  if (comp->bound.ymin < r->ymin)
    r->ymin = comp->bound.ymin;
  if (comp->bound.xmax > r->xmax)
    r->xmax = comp->bound.xmax;
  if (comp->bound.ymax > r->ymax)
    r->ymax = comp->bound.ymax;
  return false;
}

bool csDialog::do_topleft (csComponent *comp, void *param)
{
  csDialog *self = (csDialog *)param;
  comp->SetPos (self->BorderWidth + self->GridX,
    self->BorderHeight + self->GridY);
  return false;
}

void csDialog::SuggestSize (int &w, int &h)
{
  // If we have no children, we have some default size
  if (!top)
  {
    w = h = 8;
    return;
  }

  /// If we never auto-placed the items, place them at top-left corner
  if ((GridX >= 0) && (GridY >= 0) && !first)
    ForEach (do_topleft, this);
  csRect rect (999999, 999999, 0, 0);
  ForEach (do_checksize, &rect);
  if (rect.xmin == 999999)
    rect.xmin = BorderWidth;
  if (rect.ymin == 999999)
    rect.ymin = BorderHeight;
  w = rect.xmin + rect.xmax;
  h = rect.ymin + rect.ymax;
}

void csDialog::FixSize (int &newW, int &newH)
{
  if ((GridX >= 0) && (GridY >= 0))
  {
    int minw,minh;
    minw = (BorderWidth + GridX) * 2;
    minh = (BorderHeight + GridY) * 2;
    if (first)
    {
      minw += first->bound.Width ();
      minh += first->bound.Height ();
    }
    // Don't allow too small windows
    if (newW < minw) newW = minw;
    if (newH < minh) newH = minh;
  }
}

void csDialog::SetBorderSize (int w, int h)
{
  BorderWidth = w;
  BorderHeight = h;
  csComponent::SetRect (bound);
}

void csDialog::SetFrameStyle (csDialogFrameStyle iFrameStyle)
{
  FrameStyle = iFrameStyle;
  SKIN->SetBorderSize (*this);
  csComponent::SetRect (bound);
  Invalidate ();
}

void csDialog::SetAlpha (uint8 iAlpha)
{
	Alpha = iAlpha;

  if (Alpha || FrameStyle == csdfsBitmap)
    SetState (CSS_TRANSPARENT, true);
  else
    SetState (CSS_TRANSPARENT, false);
}

void
csDialog::SetFrameBitmap(csPixmap *iFrameBitmap, bool iDelFrameBitmap)
{
	// Delete the previous bitmap, if it needs to be
	if (delFrameBitmap && FrameBitmap)
	{
  	  delete FrameBitmap;
	  delFrameBitmap=false;
	  FrameBitmap=NULL;
	}

	// Set the new one only	if there's something to set
	if (iFrameBitmap) {
	  FrameBitmap = iFrameBitmap;
	  delFrameBitmap = iDelFrameBitmap;
	}
}

<|endoftext|>


<commit_before>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

CV_ENUM(AgastType, AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d,
                   AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16)

typedef std::tr1::tuple<string, AgastType> File_Type_t;
typedef perf::TestBaseWithParam<File_Type_t> agast;

#define AGAST_IMAGES \
    "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\
    "stitching/a3.png"

PERF_TEST_P(agast, detect, testing::Combine(
                            testing::Values(AGAST_IMAGES),
                            AgastType::all()
                          ))
{
    string filename = getDataPath(get<0>(GetParam()));
    int type = get<1>(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);

    if (frame.empty())
        FAIL() << "Unable to load source image " << filename;

    declare.in(frame);

    Ptr<FeatureDetector> fd = AgastFeatureDetector::create(20, true, type);
    ASSERT_FALSE( fd.empty() );
    vector<KeyPoint> points;

    TEST_CYCLE() fd->detect(frame, points);

    SANITY_CHECK_KEYPOINTS(points);
}
<commit_msg>Adjust AGAST perftest to be at parity (better) with FAST ones.<commit_after>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

CV_ENUM(AgastType, AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d,
                   AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16)

typedef std::tr1::tuple<string, AgastType> File_Type_t;
typedef perf::TestBaseWithParam<File_Type_t> agast;

#define AGAST_IMAGES \
    "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\
    "stitching/a3.png"

PERF_TEST_P(agast, detect, testing::Combine(
                            testing::Values(AGAST_IMAGES),
                            AgastType::all()
                          ))
{
    string filename = getDataPath(get<0>(GetParam()));
    int type = get<1>(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);

    if (frame.empty())
        FAIL() << "Unable to load source image " << filename;

    declare.in(frame);

    Ptr<FeatureDetector> fd = AgastFeatureDetector::create(70, true, type);
    ASSERT_FALSE( fd.empty() );
    vector<KeyPoint> points;

    TEST_CYCLE() fd->detect(frame, points);

    SANITY_CHECK_KEYPOINTS(points);
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream>
#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/xfeatures2d.hpp"

#include <opencv2/line_descriptor.hpp>

#include <opencv2/imgproc.hpp>

using namespace cv;
using namespace cv::xfeatures2d;

void readme();

/** @function main */
int main( int argc, char** argv )
{
  if( argc != 3 )
  { readme(); return -1; }

  Mat img_object = imread( argv[1], IMREAD_GRAYSCALE );
  Mat img_scene = imread( argv[2], IMREAD_GRAYSCALE );

  if( !img_object.data || !img_scene.data )
  { std::cout<< " --(!) Error reading images " << std::endl; return -1; }

  //-- Step 1: Detect the keypoints using SURF Detector
  int minHessian = 400;

  std::vector<KeyPoint> keypoints_object, keypoints_scene;

  //-- Step 2: Calculate descriptors (feature vectors)
  int surfNFeatures = 100;
  auto extractor = cv::xfeatures2d::SurfFeatureDetector::create(surfNFeatures, 5, 2);

  Mat descriptors_object, descriptors_scene;

  extractor->detectAndCompute( img_object, noArray(), keypoints_object, descriptors_object );
  extractor->detectAndCompute( img_scene, noArray(), keypoints_scene, descriptors_scene );

  //-- Step 3: Matching descriptor vectors using FLANN matcher
  FlannBasedMatcher matcher;
  std::vector< DMatch > matches;
  matcher.match( descriptors_object, descriptors_scene, matches );

  double max_dist = 0; double min_dist = 100;

  //-- Quick calculation of max and min distances between keypoints
  for( int i = 0; i < descriptors_object.rows; i++ )
  { double dist = matches[i].distance;
    if( dist < min_dist ) min_dist = dist;
    if( dist > max_dist ) max_dist = dist;
  }

  printf("-- Max dist : %f \n", max_dist );
  printf("-- Min dist : %f \n", min_dist );

  //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist )
  std::vector< DMatch > good_matches;

  for( int i = 0; i < descriptors_object.rows; i++ )
  { if( matches[i].distance < 3*min_dist )
     { good_matches.push_back( matches[i]); }
  }

  Mat img_matches;
  drawMatches( img_object, keypoints_object, img_scene, keypoints_scene,
               good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
               std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );

  //-- Localize the object
  std::vector<Point2f> obj;
  std::vector<Point2f> scene;

  for( int i = 0; i < good_matches.size(); i++ )
  {
    //-- Get the keypoints from the good matches
    obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt );
    scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt );
  }

  Mat H = findHomography( obj, scene, RANSAC );

  //-- Get the corners from the image_1 ( the object to be "detected" )
  std::vector<Point2f> obj_corners(4);
  obj_corners[0] = cvPoint(0,0); obj_corners[1] = cvPoint( img_object.cols, 0 );
  obj_corners[2] = cvPoint( img_object.cols, img_object.rows ); obj_corners[3] = cvPoint( 0, img_object.rows );
  std::vector<Point2f> scene_corners(4);

  perspectiveTransform( obj_corners, scene_corners, H);

  //-- Draw lines between the corners (the mapped object in the scene - image_2 )
  line( img_matches, scene_corners[0] + Point2f( img_object.cols, 0), scene_corners[1] + Point2f( img_object.cols, 0), Scalar(0, 255, 0), 4 );
  line( img_matches, scene_corners[1] + Point2f( img_object.cols, 0), scene_corners[2] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
  line( img_matches, scene_corners[2] + Point2f( img_object.cols, 0), scene_corners[3] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
  line( img_matches, scene_corners[3] + Point2f( img_object.cols, 0), scene_corners[0] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );

  //-- Show detected matches
  imshow( "Good Matches & Object detection", img_matches );

  waitKey(0);
  return 0;
  }

  /** @function readme */
  void readme()
  { std::cout << " Usage: ./SURF_descriptor <img1> <img2>" << std::endl; }
<commit_msg>homography working correctly!<commit_after>#include <stdio.h>
#include <iostream>
#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/xfeatures2d.hpp"

#include <opencv2/line_descriptor.hpp>

#include <opencv2/imgproc.hpp>

using namespace cv;
using namespace cv::xfeatures2d;

void readme();

/** @function main */
int main( int argc, char** argv )
{
  if( argc != 3 )
  { readme(); return -1; }

  Mat img_object = imread( argv[1], IMREAD_GRAYSCALE );
  Mat img_scene = imread( argv[2], IMREAD_GRAYSCALE );

  if( !img_object.data || !img_scene.data )
  { std::cout<< " --(!) Error reading images " << std::endl; return -1; }

  //-- Step 1: Detect the keypoints using SURF Detector
  int minHessian = 400;

  std::vector<KeyPoint> keypoints_object, keypoints_scene;

  //-- Step 2: Calculate descriptors (feature vectors)
  int surfNFeatures = 1000;
  auto extractor = cv::xfeatures2d::SurfFeatureDetector::create(surfNFeatures, 5, 2);

  Mat descriptors_object, descriptors_scene;

  extractor->detectAndCompute( img_object, noArray(), keypoints_object, descriptors_object );
  extractor->detectAndCompute( img_scene, noArray(), keypoints_scene, descriptors_scene );

  //-- Step 3: Matching descriptor vectors using FLANN matcher
  FlannBasedMatcher matcher;
  std::vector< DMatch > matches;
  matcher.match( descriptors_object, descriptors_scene, matches );

  double max_dist = 0; double min_dist = 100;

  //-- Quick calculation of max and min distances between keypoints
  for( int i = 0; i < descriptors_object.rows; i++ )
  { double dist = matches[i].distance;
    if( dist < min_dist ) min_dist = dist;
    if( dist > max_dist ) max_dist = dist;
  }

  printf("-- Max dist : %f \n", max_dist );
  printf("-- Min dist : %f \n", min_dist );

  //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist )
  std::vector< DMatch > good_matches;

  for( int i = 0; i < descriptors_object.rows; i++ )
  { if( matches[i].distance < 3*min_dist )
     { good_matches.push_back( matches[i]); }
  }

  Mat img_matches;
  drawMatches( img_object, keypoints_object, img_scene, keypoints_scene,
               good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
               std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );

  //-- Localize the object
  std::vector<Point2f> obj;
  std::vector<Point2f> scene;

  for( int i = 0; i < good_matches.size(); i++ )
  {
    //-- Get the keypoints from the good matches
    obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt );
    scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt );
  }

  Mat H = findHomography( obj, scene, RANSAC );

  //-- Get the corners from the image_1 ( the object to be "detected" )
  std::vector<Point2f> obj_corners(4);
  obj_corners[0] = cvPoint(0,0); obj_corners[1] = cvPoint( img_object.cols, 0 );
  obj_corners[2] = cvPoint( img_object.cols, img_object.rows ); obj_corners[3] = cvPoint( 0, img_object.rows );
  std::vector<Point2f> scene_corners(4);

  perspectiveTransform( obj_corners, scene_corners, H);

  //-- Draw lines between the corners (the mapped object in the scene - image_2 )
  line( img_matches, scene_corners[0] + Point2f( img_object.cols, 0), scene_corners[1] + Point2f( img_object.cols, 0), Scalar(0, 255, 0), 4 );
  line( img_matches, scene_corners[1] + Point2f( img_object.cols, 0), scene_corners[2] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
  line( img_matches, scene_corners[2] + Point2f( img_object.cols, 0), scene_corners[3] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
  line( img_matches, scene_corners[3] + Point2f( img_object.cols, 0), scene_corners[0] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );

  //-- Show detected matches
  imshow( "Good Matches & Object detection", img_matches );

  waitKey(0);
  return 0;
  }

  /** @function readme */
  void readme()
  { std::cout << " Usage: ./SURF_descriptor <img1> <img2>" << std::endl; }
<|endoftext|>


<commit_before>
#include "include/Shapes.h"

double sumOfArea(const std::vector<Shape *> & shapes) {

    double total =0;

    for (Shape *shapePoint: shapes)
        total += shapePoint->area();

    return total;

}

double sumOfPerimeter(const std::vector<Shape *> & shapes){

    double total = 0;

    for (Shape *shapePoint: shapes)
        total += shapePoint->perimeter();

    return total;

}

Shape* theLargestArea(const std::vector<Shape *> & shapes){

    Shape *largestShape = nullptr;
    double largestArea = 0;

    for (Shape *shapePoint: shapes)
        if(shapePoint->area() >= largestArea){
            largestArea = shapePoint->area();
            largestShape = shapePoint;
        }

    return largestShape;

}

double distanceOfVertexs(const vertex vertex_1, const vertex vertex_2) {
    double diff_X, diff_Y, distance;

    diff_X = vertex_1.x - vertex_2.x;
    diff_Y = vertex_1.y - vertex_2.y;

    distance = sqrt(((diff_X * diff_X) + (diff_Y * diff_Y)));

    return distance;
}

void sortByDecreasingPerimeter(std::vector<Shape *> & shapes) {
    // use the shakeSort
    int left = 0;
    int right = shapes.size()-1;
    int shift = 0;
    Shape *temp;

    while(left < right){
        for(int i = left; i < right; i++) {
            if(shapes[i]->perimeter() < shapes[i+1]->perimeter()){
                temp = shapes[i];
                shapes[i] = shapes[i+1];
                shapes[i+1] = temp;
                shift = i;
            }
        }
        right = shift;
        for(int i = right; i > left; i--){
            if(shapes[i]->perimeter() > shapes[i-1]->perimeter()){
                temp = shapes[i];
                shapes[i] = shapes[i-1];
                shapes[i-1] = temp;
                shift = i;
            }
        }
        left = shift;
    }
}
<commit_msg>Delete Shapes.cpp<commit_after><|endoftext|>


<commit_before>#include "DxLib.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

const int NORMAL = 0;
const int GRAPH_NUM = 1759;
struct Graph
{
	int graph;
	bool fin_flag = true;;
};
// WinMain֐
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
	LPSTR lpCmdLine, int nCmdShow)
{
	ChangeWindowMode(TRUE);
	// ʃ[h̐ݒ
	SetGraphMode(640, 480, 16);

	// cwCu
	if (DxLib_Init() == -1) return -1;
	//Loadfile-----------------------------------------
	const char dir[] = "Rmai_graph/";
	const char type[] = ".bmp";
	char str[4];
	int num = 0;
	int error_flag = 0;
	char str_num1[2];
	char str_num2[3];
	char str_num[3];
	char str_[100] = "\0";
	char filename[100] = "\0";
	struct Graph
	{
		int graph;
		bool flag = false;
	};
	Graph gr[100];

	//action
	struct Action
	{
		int begin;
		int end;
	};
	Action action[100];
	int sum;

	for (int i = 0; i < 100; i++) {
		action[i].begin = num;
		for (int j = 1; j < 100; j++) {
			sprintf(str, "%d", i);
			if (i < 10) {
				str[2] = str[0];
				str[0] = '0';
				str[1] = '0';
			}
			else if (i < 100) {
				str[2] = str[1];
				str[1] = str[0];
				str[0] = '0';
			}
			str[3] = '\0';

			filename[0] = '\0';
			sprintf(str_num, "%d", j);

			strcat(filename, dir);
			strcat(filename, str);
			strcat(filename, " (");
			strcat(filename, str_num);
			strcat(filename, ").bmp");
			strcpy(str_, filename);
			gr[num].graph = LoadGraph(filename);
			if (gr[num].graph == -1) {
				gr[num-1].flag = true;
				error_flag++;
				break;
			}
			else {
				num++;
				error_flag = 0;
			}
		}
		if (error_flag == 2) {
			break;
		}
		action[i].end = num-1;
	}
	//----------------------------------------------

	//FPS-------------------------------------------
	const int FPS = 60;
	int count;

	int aa = LoadGraph("Rmai_graph/001 (1).bmp");
	// OtBbN̕`𗠉ʂɃZbg
	SetDrawScreen(DX_SCREEN_BACK);

	int acnum = 0;

	while (1)
	{
		// ʂ(^ɂ)
		ClearDrawScreen();
		//`----------------------------------------------------
		//printfDx("%d %d\n", action[1].begin, action[1].end);
		DrawGraph(0, 0, gr[acnum].graph, true);
		DrawGraph(100, 100, aa, true);
		++acnum;
		if (acnum > action[0].end) {
			acnum = action[0].begin;
		}

		// ʂ̓e\ʂɃRs[
		ScreenFlip();

		// Windows L̖ʓ|ȏcwCuɂ点
		// -1 ԂĂ烋[v𔲂
		if (ProcessMessage() < 0) break;

		// drbL[Ă烋[v甲
		if (CheckHitKey(KEY_INPUT_ESCAPE)) break;

		//Sleep(1000 / 60);
	}

	// cwCugp̏I
	DxLib_End();

	// \tg̏I
	return 0;
}<commit_msg>fpsを30固定<commit_after>#include "DxLib.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

const int NORMAL = 0;
const int GRAPH_NUM = 1759;
struct Graph
{
	int graph;
	bool fin_flag = true;;
};
// WinMain֐
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
	LPSTR lpCmdLine, int nCmdShow)
{
	ChangeWindowMode(TRUE);
	// ʃ[h̐ݒ
	SetGraphMode(640, 480, 16);

	// cwCu
	if (DxLib_Init() == -1) return -1;
	//Loadfile-----------------------------------------
	const char dir[] = "Rmai_graph/";
	const char type[] = ".bmp";
	char str[4];
	int num = 0;
	int error_flag = 0;
	char str_num[3];
	char str_[100] = "\0";
	char filename[100] = "\0";
	struct Graph
	{
		int graph;
		bool flag = false;
	};
	Graph gr[100];

	//action
	struct Action
	{
		int begin;
		int end;
	};
	Action action[100];

	for (int i = 0; i < 100; i++) {
		action[i].begin = num;
		for (int j = 1; j < 100; j++) {
			sprintf(str, "%d", i);
			if (i < 10) {
				str[2] = str[0];
				str[0] = '0';
				str[1] = '0';
			}
			else if (i < 100) {
				str[2] = str[1];
				str[1] = str[0];
				str[0] = '0';
			}
			str[3] = '\0';

			filename[0] = '\0';
			sprintf(str_num, "%d", j);

			strcat(filename, dir);
			strcat(filename, str);
			strcat(filename, " (");
			strcat(filename, str_num);
			strcat(filename, ").bmp");
			strcpy(str_, filename);
			gr[num].graph = LoadGraph(filename);
			if (gr[num].graph == -1) {
				gr[num-1].flag = true;
				error_flag++;
				break;
			}
			else {
				num++;
				error_flag = 0;
			}
		}
		if (error_flag == 2) {
			break;
		}
		action[i].end = num-1;
	}
	//----------------------------------------------

	//FPS-------------------------------------------
	const int FPS = 30;
	int count_fps = 0;
	int start_fps;
	int wait_fps;

	int aa = LoadGraph("Rmai_graph/001 (1).bmp");
	// OtBbN̕`𗠉ʂɃZbg
	SetDrawScreen(DX_SCREEN_BACK);

	int acnum = 0;

	while (1)
	{
		// ʂ(^ɂ)
		ClearDrawScreen();

		//`----------------------------------------------------
		//printfDx("%d %d\n", action[1].begin, action[1].end);
		DrawGraph(0, 0, gr[acnum].graph, true);
		DrawGraph(100, 100, aa, true);
		++acnum;
		if (acnum > action[0].end) {
			acnum = action[0].begin;
		}
		//------------------------------------------------------------

		//FPS---------------------------------------------------------
		Sleep(1000 / 60);
		//------------------------------------------------------------

		// ʂ̓e\ʂɃRs[
		ScreenFlip();

		// Windows L̖ʓ|ȏcwCuɂ点
		// -1 ԂĂ烋[v𔲂
		if (ProcessMessage() < 0) break;

		// drbL[Ă烋[v甲
		if (CheckHitKey(KEY_INPUT_ESCAPE)) break;

	}

	// cwCugp̏I
	DxLib_End();

	// \tg̏I
	return 0;
}<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkBasicArchitectureTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkScalar.h"
#include "itkVector.h"
#include "itkRandomImageSource.h"
#include "itkShrinkImage.h"
#include "itkWriteVTKImage.h"
#include "itkReadVTKImage.h"
#include "itkCommand.h"
#include "itkOutputWindow.h"

// The following two classes are used to support callbacks
// on the shrink filter in the pipeline that follows later
class ShowProgressObject
{
public:
  ShowProgressObject(itk::ProcessObject* o)
    {m_Process = o;}
  void ShowProgress()
    {std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
  itk::ProcessObject::Pointer m_Process;
};

class StartEndEvent
{
public:
  void Start()
    {std::cout << "start event" << std::endl;}
  void End()
    {std::cout << "end event " << std::endl;}
};

void main()
{
  // Uncomment the following if you want to see each message independently
  // itk::OutputWindow::GetInstance()->PromptUserOn();

  // Test the creation of an image with native type
  //
  itk::Image<float,2>::Pointer if2 = itk::Image<float,2>::New();

  std::cout << std::endl
            << "Image dimension is " << itk::Image<float,5>::ImageDimension
            << std::endl;
  std::cout << "Image dimension is " << itk::Image<short,1>::ImageDimension
            << std::endl;

  // Begin by creating a simple pipeline. Use the Scalar class as a pixel.
  //
  // Create a typedef to make the code more digestable
  typedef itk::Image<itk::Scalar<float>,2> FloatImage2DType;

  // Create a source object (in this case a reader)
  itk::ReadVTKImage<FloatImage2DType>::Pointer reader;
  reader = itk::ReadVTKImage<FloatImage2DType>::New();
  reader->SetFileName("junkInput.vtk");

  // Create another source object (in this case a random image generator).
  // The source object is templated on the output type.
  //
  itk::RandomImageSource<FloatImage2DType>::Pointer random;
  random = itk::RandomImageSource<FloatImage2DType>::New();

  // Create a filter...shrink the image by an integral amount. We also
  // add some callbacks to the start, progress, and end filter execution
  // methods. The filter is templated on the input and output data types.
  //
  itk::ShrinkImage<FloatImage2DType,FloatImage2DType>::Pointer shrink;
  shrink = itk::ShrinkImage<FloatImage2DType,FloatImage2DType>::New();
  shrink->SetInput(random->GetOutput());
  shrink->SetShrinkFactor(2);
  shrink->DebugOn();
  // Create objects for managing start, progress, and end events in this filter
  ShowProgressObject progressWatch(shrink);
  StartEndEvent startEndWatch;
  // Create a command to call ShowProgress when progress event is triggered
  itk::SimpleMemberCommand<ShowProgressObject>::Pointer command;
  command = itk::SimpleMemberCommand<ShowProgressObject>::New();
  command->SetCallbackFunction(&progressWatch,
                               ShowProgressObject::ShowProgress);
  shrink->AddObserver(itk::Command::ProgressEvent, command);
  // Create a command to call StartEndEvent when start event is triggered
  itk::SimpleMemberCommand<StartEndEvent>::Pointer start;
  start = itk::SimpleMemberCommand<StartEndEvent>::New();
  start->SetCallbackFunction(&startEndWatch, StartEndEvent::Start);
  shrink->AddObserver(itk::Command::StartEvent, start);
  // Create a command to call StartEndEvent when end event is triggered
  itk::SimpleMemberCommand<StartEndEvent>::Pointer end;
  end = itk::SimpleMemberCommand<StartEndEvent>::New();
  end->SetCallbackFunction(&startEndWatch, StartEndEvent::End);
  shrink->AddObserver(itk::Command::EndEvent, end);

  // Create a mapper (in this case a writer). A mapper
  // is templated on the input type.
  //
  itk::WriteVTKImage<FloatImage2DType>::Pointer writer;
  writer = itk::WriteVTKImage<FloatImage2DType>::New();
  writer->SetInput(shrink->GetOutput());
  writer->SetFileName("junkImage.vtk");
  writer->SetFileTypeToASCII();
  writer->DebugOn();
  writer->Write();

  exit(EXIT_SUCCESS);
}

<commit_msg>ENH: add an allevent watcher<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkBasicArchitectureTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkScalar.h"
#include "itkVector.h"
#include "itkRandomImageSource.h"
#include "itkShrinkImage.h"
#include "itkWriteVTKImage.h"
#include "itkReadVTKImage.h"
#include "itkCommand.h"
#include "itkOutputWindow.h"

// this class is used to send output to stdout and not the itk window
class TextOutput : public itk::OutputWindow
{
public:
  virtual void DisplayText(const char* s)
    {
      std::cout << s << std::endl;
    }
};

// The following three classes are used to support callbacks
// on the shrink filter in the pipeline that follows later
class ShowProgressObject
{
public:
  ShowProgressObject(itk::ProcessObject* o)
    {m_Process = o;}
  void ShowProgress()
    {std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
  itk::ProcessObject::Pointer m_Process;
};

class StartEndEvent
{
public:
  void Start()
    {std::cout << "start event" << std::endl;}
  void End()
    {std::cout << "end event " << std::endl;}
};

class AllEvents
{
public:
  void WatchEvents(itk::LightObject *caller, unsigned long event)
    {
      const char* eventName = 0;
      switch(event)
        {
        case itk::Command::DeleteEvent:
          eventName = "DeleteEvent";
          break;
        case itk::Command::StartEvent:
          eventName = "StartEvent";
          break;
        case itk::Command::EndEvent:
          eventName = "EndEvent";
          break;
        case itk::Command::ProgressEvent:
          {
          itk::ProcessObject* obj = dynamic_cast<itk::ProcessObject*>(caller);
          std::cout << "AnyEvent Progress " << obj->GetProgress() << std::endl;
          eventName = "ProgressEvent";
          break;
          }
        case itk::Command::PickEvent:
          eventName = "PickEvent";
          break;
        case itk::Command::StartPickEvent:
          eventName = "StartPickEvent";
          break;
        case itk::Command::AbortCheckEvent:
          eventName = "AbortCheckEvent";
          break;
        case itk::Command::ExitEvent:
          eventName = "ExitEvent";
          break;
        default:
          eventName = "UserEvent";
        }
      std::cout << "Event name: " << eventName << " Id: " << event << std::endl;
    }
};

int main()
{
  // Comment the following if you want to use the itk text output window
  itk::OutputWindow::SetInstance(new TextOutput);
  // Uncomment the following if you want to see each message independently
  // itk::OutputWindow::GetInstance()->PromptUserOn();

  // Test the creation of an image with native type
  //
  itk::Image<float,2>::Pointer if2 = itk::Image<float,2>::New();

  std::cout << std::endl
            << "Image dimension is " << itk::Image<float,5>::ImageDimension
            << std::endl;
  std::cout << "Image dimension is " << itk::Image<short,1>::ImageDimension
            << std::endl;

  // Begin by creating a simple pipeline. Use the Scalar class as a pixel.
  //
  // Create a typedef to make the code more digestable
  typedef itk::Image<itk::Scalar<float>,2> FloatImage2DType;

  // Create a source object (in this case a reader)
  itk::ReadVTKImage<FloatImage2DType>::Pointer reader;
  reader = itk::ReadVTKImage<FloatImage2DType>::New();
  reader->SetFileName("junkInput.vtk");

  // Create another source object (in this case a random image generator).
  // The source object is templated on the output type.
  //
  itk::RandomImageSource<FloatImage2DType>::Pointer random;
  random = itk::RandomImageSource<FloatImage2DType>::New();

  // Create a filter...shrink the image by an integral amount. We also
  // add some callbacks to the start, progress, and end filter execution
  // methods. The filter is templated on the input and output data types.
  //
  itk::ShrinkImage<FloatImage2DType,FloatImage2DType>::Pointer shrink;
  shrink = itk::ShrinkImage<FloatImage2DType,FloatImage2DType>::New();
  shrink->SetInput(random->GetOutput());
  shrink->SetShrinkFactor(2);
  shrink->DebugOn();

  // Create a command to call ShowProgress when progress event is triggered
  ShowProgressObject progressWatch(shrink);
  itk::SimpleMemberCommand<ShowProgressObject>::Pointer command;
  command = itk::SimpleMemberCommand<ShowProgressObject>::New();
  command->SetCallbackFunction(&progressWatch,
                               ShowProgressObject::ShowProgress);
  shrink->AddObserver(itk::Command::ProgressEvent, command);

  // Create a command to call StartEndEvent when start event is triggered
  StartEndEvent startEndWatch;
  itk::SimpleMemberCommand<StartEndEvent>::Pointer start;
  start = itk::SimpleMemberCommand<StartEndEvent>::New();
  start->SetCallbackFunction(&startEndWatch, StartEndEvent::Start);
  shrink->AddObserver(itk::Command::StartEvent, start);

  // Create a command to call StartEndEvent when end event is triggered
  itk::SimpleMemberCommand<StartEndEvent>::Pointer end;
  end = itk::SimpleMemberCommand<StartEndEvent>::New();
  end->SetCallbackFunction(&startEndWatch, StartEndEvent::End);
  shrink->AddObserver(itk::Command::EndEvent, end);

  // Create a command that to call AnyEvent when event is fired
  AllEvents allWatch;
  itk::MemberCommand<AllEvents>::Pointer allEvents;
  allEvents = itk::MemberCommand<AllEvents>::New();
  allEvents->SetCallbackFunction(&allWatch,
                                 AllEvents::WatchEvents);
  shrink->AddObserver(itk::Command::AnyEvent, allEvents);

  // Create a mapper (in this case a writer). A mapper
  // is templated on the input type.
  //
  itk::WriteVTKImage<FloatImage2DType>::Pointer writer;
  writer = itk::WriteVTKImage<FloatImage2DType>::New();
  writer->SetInput(shrink->GetOutput());
  writer->SetFileName("junkImage.vtk");
  writer->SetFileTypeToASCII();
  writer->DebugOn();
  writer->Write();

  return EXIT_SUCCESS;
}

<|endoftext|>