<commit_before>/***********************************************************************
    filename:   SVGBasicShape.cpp
    created:    30th July 2013
    author:     Lukas Meindl
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/svg/SVGBasicShape.h"

#include "CEGUI/svg/SVGTesselator.h"

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
SVGBasicShape::SVGBasicShape(const SVGPaintStyle& paint_style,
                             const glm::mat3x3& transformation) :
    d_paintStyle(paint_style),
    d_transformation(transformation)
{
}

//----------------------------------------------------------------------------//
SVGBasicShape::~SVGBasicShape()
{
}

//----------------------------------------------------------------------------//
SVGRect::SVGRect(const SVGPaintStyle& paint_style,
                 const glm::mat3x3& transformation,
                 const float x,
                 const float y,
                 const float width,
                 const float height,
                 const float rx,
                 const float ry) :
    SVGBasicShape(paint_style, transformation),
    d_x(x),
    d_y(y),
    d_width(width),
    d_height(height),
    d_rx(rx),
    d_ry(ry)
{
}

//----------------------------------------------------------------------------//
void SVGRect::render(std::vector<GeometryBuffer*>& geometry_buffers,
                     const SVGImage::SVGImageRenderSettings& render_settings) const
{
    SVGTesselator::tesselateAndRenderRect(this,
                                          geometry_buffers,
                                          render_settings);
}

//----------------------------------------------------------------------------//
SVGCircle::SVGCircle(const SVGPaintStyle& paint_style,
                     const glm::mat3x3& transformation,
                     const float cx,
                     const float cy,
                     const float r) :
    SVGBasicShape(paint_style, transformation),
    d_cx(cx),
    d_cy(cy),
    d_r(r)
{
}

//----------------------------------------------------------------------------//
void SVGCircle::render(std::vector<GeometryBuffer*>& geometry_buffers,
                       const SVGImage::SVGImageRenderSettings& render_settings) const
{
    SVGTesselator::tesselateAndRenderCircle(this,
                                            geometry_buffers,
                                            render_settings);
}

//----------------------------------------------------------------------------//
SVGLine::SVGLine(const SVGPaintStyle& paint_style,
                 const glm::mat3x3& transformation,
                 const float x1,
                 const float y1,
                 const float x2,
                 const float y2) :
    SVGBasicShape(paint_style, transformation),
    d_x1(x1),
    d_y1(y1),
    d_x2(x2),
    d_y2(y2)
{
}

//----------------------------------------------------------------------------//
SVGLine::SVGLine(const SVGPaintStyle& paint_style,
                 const glm::mat3x3& transformation,
                 const glm::vec2& line_start,
                 const glm::vec2& line_end) :
    SVGBasicShape(paint_style, transformation),
    d_x1(line_start.x),
    d_y1(line_start.y),
    d_x2(line_end.x),
    d_y2(line_end.y)
{
}

//----------------------------------------------------------------------------//
void SVGLine::render(std::vector<GeometryBuffer*>& geometry_buffers,
                     const SVGImage::SVGImageRenderSettings& render_settings) const
{
    SVGTesselator::tesselateAndRenderLine(this,
                                          geometry_buffers,
                                          render_settings);
}

//----------------------------------------------------------------------------//
SVGPolyline::SVGPolyline(const SVGPaintStyle& paint_style,
                         const glm::mat3x3& transformation,
                         const PolylinePointsList& points) :
    SVGBasicShape(paint_style, transformation),
    d_points(points)
{
}

//----------------------------------------------------------------------------//
void SVGPolyline::render(std::vector<GeometryBuffer*>& geometry_buffers,
                         const SVGImage::SVGImageRenderSettings& render_settings) const
{
    SVGTesselator::tesselateAndRenderPolyline(this,
                                              geometry_buffers,
                                              render_settings);
}

//----------------------------------------------------------------------------//
}

<commit_msg>MOD: format<commit_after>/***********************************************************************
    filename:   SVGBasicShape.cpp
    created:    30th July 2013
    author:     Lukas Meindl
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/svg/SVGBasicShape.h"

#include "CEGUI/svg/SVGTesselator.h"

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
SVGBasicShape::SVGBasicShape(const SVGPaintStyle& paint_style,
                             const glm::mat3x3& transformation) :
    d_paintStyle(paint_style),
    d_transformation(transformation)
{
}

//----------------------------------------------------------------------------//
SVGBasicShape::~SVGBasicShape()
{
}

//----------------------------------------------------------------------------//
SVGRect::SVGRect(const SVGPaintStyle& paint_style,
                 const glm::mat3x3& transformation,
                 const float x,
                 const float y,
                 const float width,
                 const float height,
                 const float rx,
                 const float ry) :
    SVGBasicShape(paint_style, transformation),
    d_x(x),
    d_y(y),
    d_width(width),
    d_height(height),
    d_rx(rx),
    d_ry(ry)
{
}

//----------------------------------------------------------------------------//
void SVGRect::render(std::vector<GeometryBuffer*>& geometry_buffers,
                     const SVGImage::SVGImageRenderSettings& render_settings) const
{
    SVGTesselator::tesselateRect(this,
                                 geometry_buffers,
                                 render_settings);
}

//----------------------------------------------------------------------------//
SVGCircle::SVGCircle(const SVGPaintStyle& paint_style,
                     const glm::mat3x3& transformation,
                     const float cx,
                     const float cy,
                     const float r) :
    SVGBasicShape(paint_style, transformation),
    d_cx(cx),
    d_cy(cy),
    d_r(r)
{
}

//----------------------------------------------------------------------------//
void SVGCircle::render(std::vector<GeometryBuffer*>& geometry_buffers,
                       const SVGImage::SVGImageRenderSettings& render_settings) const
{
    SVGTesselator::tesselateCircle(this,
                                   geometry_buffers,
                                   render_settings);
}

//----------------------------------------------------------------------------//
SVGLine::SVGLine(const SVGPaintStyle& paint_style,
                 const glm::mat3x3& transformation,
                 const float x1,
                 const float y1,
                 const float x2,
                 const float y2) :
    SVGBasicShape(paint_style, transformation),
    d_x1(x1),
    d_y1(y1),
    d_x2(x2),
    d_y2(y2)
{
}

//----------------------------------------------------------------------------//
SVGLine::SVGLine(const SVGPaintStyle& paint_style,
                 const glm::mat3x3& transformation,
                 const glm::vec2& line_start,
                 const glm::vec2& line_end) :
    SVGBasicShape(paint_style, transformation),
    d_x1(line_start.x),
    d_y1(line_start.y),
    d_x2(line_end.x),
    d_y2(line_end.y)
{
}

//----------------------------------------------------------------------------//
void SVGLine::render(std::vector<GeometryBuffer*>& geometry_buffers,
                     const SVGImage::SVGImageRenderSettings& render_settings) const
{
    SVGTesselator::tesselateLine(this,
                                 geometry_buffers,
                                 render_settings);
}

//----------------------------------------------------------------------------//
SVGPolyline::SVGPolyline(const SVGPaintStyle& paint_style,
                         const glm::mat3x3& transformation,
                         const PolylinePointsList& points) :
    SVGBasicShape(paint_style, transformation),
    d_points(points)
{
}

//----------------------------------------------------------------------------//
void SVGPolyline::render(std::vector<GeometryBuffer*>& geometry_buffers,
                         const SVGImage::SVGImageRenderSettings& render_settings) const
{
    SVGTesselator::tesselatePolyline(this,
                                     geometry_buffers,
                                     render_settings);
}

//----------------------------------------------------------------------------//
}

<|endoftext|>


<commit_before>/// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions (c) 2011 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 "libcef/renderer/render_process_observer.h"
#include "libcef/common/cef_messages.h"
#include "libcef/common/content_client.h"

#include "base/bind.h"
#include "base/path_service.h"
#include "googleurl/src/gurl.h"
#include "googleurl/src/url_util.h"
#include "media/base/media.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h"

CefRenderProcessObserver::CefRenderProcessObserver() {
  // Note that under Linux, the media library will normally already have
  // been initialized by the Zygote before this instance became a Renderer.
  FilePath media_path;
  PathService::Get(base::DIR_MODULE, &media_path);
  if (!media_path.empty())
    media::InitializeMediaLibrary(media_path);
}

CefRenderProcessObserver::~CefRenderProcessObserver() {
}

bool CefRenderProcessObserver::OnControlMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(CefRenderProcessObserver, message)
    IPC_MESSAGE_HANDLER(CefProcessMsg_ModifyCrossOriginWhitelistEntry,
                        OnModifyCrossOriginWhitelistEntry)
    IPC_MESSAGE_HANDLER(CefProcessMsg_ClearCrossOriginWhitelist,
                        OnClearCrossOriginWhitelist)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void CefRenderProcessObserver::WebKitInitialized() {
  WebKit::WebRuntimeFeatures::enableMediaPlayer(
      media::IsMediaLibraryInitialized());

  // Notify the render process handler.
  CefRefPtr<CefApp> application = CefContentClient::Get()->application();
  if (application.get()) {
    CefRefPtr<CefRenderProcessHandler> handler =
        application->GetRenderProcessHandler();
    if (handler.get())
      handler->OnWebKitInitialized();
  }
}

void CefRenderProcessObserver::OnModifyCrossOriginWhitelistEntry(
    bool add,
    const std::string& source_origin,
    const std::string& target_protocol,
    const std::string& target_domain,
    bool allow_target_subdomains) {
  GURL gurl = GURL(source_origin);
  if (add) {
    WebKit::WebSecurityPolicy::addOriginAccessWhitelistEntry(
        gurl,
        WebKit::WebString::fromUTF8(target_protocol),
        WebKit::WebString::fromUTF8(target_domain),
        allow_target_subdomains);
  } else {
    WebKit::WebSecurityPolicy::removeOriginAccessWhitelistEntry(
        gurl,
        WebKit::WebString::fromUTF8(target_protocol),
        WebKit::WebString::fromUTF8(target_domain),
        allow_target_subdomains);
  }
}

void CefRenderProcessObserver::OnClearCrossOriginWhitelist() {
  WebKit::WebSecurityPolicy::resetOriginAccessWhitelists();
}
<commit_msg>CEF3: Disable unimplemented WebKit notifications and geolocation features.<commit_after>/// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions (c) 2011 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 "libcef/renderer/render_process_observer.h"
#include "libcef/common/cef_messages.h"
#include "libcef/common/content_client.h"

#include "base/bind.h"
#include "base/path_service.h"
#include "googleurl/src/gurl.h"
#include "googleurl/src/url_util.h"
#include "media/base/media.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h"

CefRenderProcessObserver::CefRenderProcessObserver() {
  // Note that under Linux, the media library will normally already have
  // been initialized by the Zygote before this instance became a Renderer.
  FilePath media_path;
  PathService::Get(base::DIR_MODULE, &media_path);
  if (!media_path.empty())
    media::InitializeMediaLibrary(media_path);
}

CefRenderProcessObserver::~CefRenderProcessObserver() {
}

bool CefRenderProcessObserver::OnControlMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(CefRenderProcessObserver, message)
    IPC_MESSAGE_HANDLER(CefProcessMsg_ModifyCrossOriginWhitelistEntry,
                        OnModifyCrossOriginWhitelistEntry)
    IPC_MESSAGE_HANDLER(CefProcessMsg_ClearCrossOriginWhitelist,
                        OnClearCrossOriginWhitelist)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void CefRenderProcessObserver::WebKitInitialized() {
  WebKit::WebRuntimeFeatures::enableMediaPlayer(
      media::IsMediaLibraryInitialized());

  // TODO(cef): Enable these once the implementation supports it.
  WebKit::WebRuntimeFeatures::enableNotifications(false);
  WebKit::WebRuntimeFeatures::enableGeolocation(false);

  // Notify the render process handler.
  CefRefPtr<CefApp> application = CefContentClient::Get()->application();
  if (application.get()) {
    CefRefPtr<CefRenderProcessHandler> handler =
        application->GetRenderProcessHandler();
    if (handler.get())
      handler->OnWebKitInitialized();
  }
}

void CefRenderProcessObserver::OnModifyCrossOriginWhitelistEntry(
    bool add,
    const std::string& source_origin,
    const std::string& target_protocol,
    const std::string& target_domain,
    bool allow_target_subdomains) {
  GURL gurl = GURL(source_origin);
  if (add) {
    WebKit::WebSecurityPolicy::addOriginAccessWhitelistEntry(
        gurl,
        WebKit::WebString::fromUTF8(target_protocol),
        WebKit::WebString::fromUTF8(target_domain),
        allow_target_subdomains);
  } else {
    WebKit::WebSecurityPolicy::removeOriginAccessWhitelistEntry(
        gurl,
        WebKit::WebString::fromUTF8(target_protocol),
        WebKit::WebString::fromUTF8(target_domain),
        allow_target_subdomains);
  }
}

void CefRenderProcessObserver::OnClearCrossOriginWhitelist() {
  WebKit::WebSecurityPolicy::resetOriginAccessWhitelists();
}
<|endoftext|>


<commit_before>#include <net/openssl/init.hpp>

#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <kernel/rng.hpp>
#include <cassert>

extern "C" void ios_rand_seed(const void* buf, int num)
{
  rng_absorb(buf, num);
}
extern "C" int ios_rand_bytes(unsigned char* buf, int num)
{
  rng_extract(buf, num);
  return 1;
}
extern "C" void ios_rand_cleanup()
{
  /** do nothing **/
}
extern "C" void ios_rand_add(const void* buf, int num, double)
{
  rng_absorb(buf, num);
}
extern "C" int ios_rand_pseudorand(unsigned char* buf, int num)
{
  rng_absorb(buf, num);
  return 1;
}
extern "C" int ios_rand_status()
{
  return 1;
}

namespace openssl
{
  void setup_rng()
  {
    RAND_METHOD ios_rand {
      ios_rand_seed,
      ios_rand_bytes,
      ios_rand_cleanup,
      ios_rand_add,
      ios_rand_pseudorand,
      ios_rand_status
    };
    RAND_set_rand_method(&ios_rand);
  }
  void verify_rng()
  {
    auto* rm = RAND_get_rand_method();
    int random_value = 0;
    int rc = RAND_bytes((uint8_t*) &random_value, sizeof(random_value));
    assert(rc == 0 || rc == 1);
  }

  /* SSL library initialisation */
  void init()
  {
    static bool init_once = false;
    if (init_once == false)
    {
      init_once = true;
      SSL_library_init();
      OpenSSL_add_all_algorithms();
      SSL_load_error_strings();
      ERR_load_BIO_strings();
      ERR_load_crypto_strings();
    }
  }
}
<commit_msg>openssl: Print version info on init<commit_after>#include <net/openssl/init.hpp>

#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <kernel/rng.hpp>
#include <cassert>
#include <info>

extern "C" void ios_rand_seed(const void* buf, int num)
{
  rng_absorb(buf, num);
}
extern "C" int ios_rand_bytes(unsigned char* buf, int num)
{
  rng_extract(buf, num);
  return 1;
}
extern "C" void ios_rand_cleanup()
{
  /** do nothing **/
}
extern "C" void ios_rand_add(const void* buf, int num, double)
{
  rng_absorb(buf, num);
}
extern "C" int ios_rand_pseudorand(unsigned char* buf, int num)
{
  rng_absorb(buf, num);
  return 1;
}
extern "C" int ios_rand_status()
{
  return 1;
}

namespace openssl
{
  void setup_rng()
  {
    RAND_METHOD ios_rand {
      ios_rand_seed,
      ios_rand_bytes,
      ios_rand_cleanup,
      ios_rand_add,
      ios_rand_pseudorand,
      ios_rand_status
    };
    RAND_set_rand_method(&ios_rand);
  }
  void verify_rng()
  {
    auto* rm = RAND_get_rand_method();
    int random_value = 0;
    int rc = RAND_bytes((uint8_t*) &random_value, sizeof(random_value));
    assert(rc == 0 || rc == 1);
  }

  /* SSL library initialisation */
  void init()
  {
    static bool init_once = false;
    if (init_once == false)
    {
      INFO("OpenSSL", "Initializing (%s)", OPENSSL_VERSION_TEXT);
      init_once = true;
      SSL_library_init();
      OpenSSL_add_all_algorithms();
      SSL_load_error_strings();
      ERR_load_BIO_strings();
      ERR_load_crypto_strings();
    }
  }
}
<|endoftext|>


<commit_before>#include "show_result.hpp"

void save_result(const char* source_path, char const postFix[], char const outputFormat[], cv::Mat& image)
{
    char* destination_path = (char*)calloc( strlen(source_path) + strlen(postFix) + strlen(outputFormat) + strlen("\0"), sizeof(char) );

    const char* lastSlash = strrchr ( source_path, '.' );
    int lastSlashPos = lastSlash - source_path;

    strncpy( destination_path, source_path, lastSlashPos );

    int len = strlen( destination_path );
    strcpy( destination_path + len, postFix );

    len += strlen( postFix );
    strcpy( destination_path + len, source_path + lastSlashPos );

    len = strlen( destination_path );
    strcpy( destination_path + len, outputFormat );

    cv::imwrite( destination_path, image);
}

void p_around(unsigned char* data, int before, int after)
{
    for(int i = -before; i < after; ++i )
    {
        if(i == 0)
        {
            std::cout << "MARKER";
        }
        std::cout << data[i];
    }
}

void draw_clusterNumber(cv::Mat& image, std::vector<IndexTransitionCluster> const & result)
{
    std::vector<IndexTransitionCluster> textPoint(result);
    std::stable_sort( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
        if(el1.get_clusterNumber() < el2.get_clusterNumber())
        {
            return true;
        }
        else
        {
            return false;
        }
    } );
    textPoint.erase( unique( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
        if(el1.get_clusterNumber() == el2.get_clusterNumber())
        {
            return true;
        }
        else
        {
            return false;
        }
    } ), textPoint.end() );
    std::for_each(textPoint.begin(), textPoint.end(), [&image](auto el){
        cv::putText(image, std::to_string(el.get_clusterNumber()), cv::Point(el.col, el.row ), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cv::Scalar(200,20,250));//, 1, 8, false);
        std::cout<<el.get_clusterNumber()<<" "<<el.row<<" "<<el.col<<"\n";
    });
    std::cout<< result.size()<< "\n";
    std::cout<< textPoint.size()<< "\n";
}

cv::Mat show_result(cv::Mat const img, std::vector<IndexTransitionCluster> const & result )
{
    cv::Mat image = img.clone();
    cv::namedWindow( "show_result", cv::WINDOW_AUTOSIZE );
    cv::imshow( "show_result", image );
    cv::waitKey(0);

    if(image.isContinuous())
    {
        for_each(result.begin(), result.end(), [&image](auto el){
            image.data[el.index( image )] = 255;
            image.data[el.index( image ) + 1] = 0;
            image.data[el.index( image ) + 2] = 255;
        });
        draw_clusterNumber(image, result);
        cv::imshow( "show_result", image );
    }
    else
    {
        std::cout<<"notcontionuous\n";
        return image;
    }
//    cv::waitKey(0);

    cv::Mat blackImage(image.rows, image.cols, CV_8UC3, cv::Scalar(0,0,0));
    for_each(result.begin(), result.end(), [&blackImage](auto el){
        blackImage.data[el.index( blackImage )] = 255;
        blackImage.data[el.index( blackImage ) + 1] = 0;
        blackImage.data[el.index( blackImage ) + 2] = 255;
    });
    draw_clusterNumber(blackImage, result);
    cv::imshow( "show_result", blackImage );
    cv::waitKey(0);
    return blackImage;
}

std::vector<IndexTransitionCluster> test_on_image(const char* path, double factor, double eps, uint minPts)
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return std::vector<IndexTransitionCluster>();
    }

    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
    cv::Mat imageCpy = image.clone();
    cv::Mat imageCpy2 = image.clone();
    cv::Mat blackImage;

    TYPE acceptanceLevel = 60;
    ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
    double lightThreshold = 0.2;
    double colorThreshold = 0.2;

    IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance);
    auto result = entryProcess.iterate_HV();
    std::cout << result.size() << '\n';
    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    save_result(path, "_noisy", ".png", blackImage);
    ColorBalance cba( image, 5u, 6 );
    ColorStruct secondBalance = cba.balance( result );

    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    save_result(path, "_detect1", ".png", blackImage);
    result.resize( 0 );

    lightThreshold = 0.2;
    colorThreshold = 0.2;
    IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, ColorStruct{ 0.82, 1.05, 1.14 });//secondBalance);
    result = secondProcess.iterate_HV();

    blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
    save_result(path, "_detect_balanced", ".png", blackImage);

    Clustering clustering( result, Distance::distance_fast, eps, minPts);
    clustering.points_clustering(&Clustering::check_point_zone_linear);
    auto clusters = clustering.getRefVIndexTransitionCluster();
    blackImage = show_result(imageCpy, clusters);
    save_result(path, "_detect_cluster", ".png", blackImage);

    return clusters;
}

int broad_HUE(char* path)
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return -1;
    }

    cvtColor(image, image, CV_BGR2HSV);
    for(int i =2; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    cvtColor(image, image, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", image );
    save_result(path, "_OUT1", ".png", image);

    cv::Mat cpyImage = image.clone();
    cvtColor(cpyImage, cpyImage, CV_BGR2HSV);
    for(int i =2; i < cpyImage.rows * cpyImage.cols * 3; i+=3)
    {
        cpyImage.data[i] = cpyImage.data[i-1];
    }
    cvtColor(cpyImage, cpyImage, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", cpyImage );
    save_result(path, "_OUT3", ".png", cpyImage);

    cvtColor(image, image, CV_BGR2HSV);
    for(int i =2; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    for(int i = 1; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    cvtColor(image, image, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", image );
    save_result(path, "_OUT2", ".png", image);

    return 0;
}

cv::Mat test_canny( char* path, double factor, int dilationSize )
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return image;
    }
    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);

    Preprocess preprocess( MakeFilter::box_kernel(11), image);
    cv::Mat edges = preprocess.make_thick_kernel( image, dilationSize );
    cv::namedWindow( "Canny", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Canny", edges );
    cv::waitKey(0);

    return edges;
}

std::vector<IndexTransitionCluster> index_transition_part(cv::Mat const image, double eps, uint minPts, int compareDistance)
{
    cv::Mat imageCpy = image.clone();
    cv::Mat imageCpy2 = image.clone();
    cv::Mat blackImage;

    TYPE acceptanceLevel = 150;
    ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
    double lightThreshold = 0.03;
    double colorThreshold = 0.01;

    IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance, compareDistance);
    auto result = entryProcess.iterate_HV();

    ColorBalance cba( image, 5u, compareDistance );
    ColorStruct secondBalance = cba.balance( result );

    result.resize( 0 );
    //colorThreshold/=2;
    IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, secondBalance, compareDistance);//secondBalance);
    result = secondProcess.iterate_HV();

    Clustering clustering( result, Distance::distance_fast, eps, minPts);
    clustering.points_clustering(&Clustering::check_point_zone_linear);
    auto clusters = clustering.getRefVIndexTransitionCluster();

    #ifdef VERBOSE
    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
    blackImage = show_result(imageCpy, clusters);
    #endif

    return clusters;
}

cv::Mat test_gauss_directed(const char* path, double factor, int dilationSize )
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return image;
    }

    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
    cv::Mat cImage = image.clone();
    bilateralFilter( cImage, image, 30, 150, 150, cv::BORDER_REFLECT );

    // int sigma = 2;
    // cv::GaussianBlur( image, image, cv::Size(sigma*4+1, sigma*4+1), sigma);

    auto idTrCluster = index_transition_part( image, 3.0, 1, 3 );
    std::vector<IndexTransition> idTr( idTrCluster.begin(), idTrCluster.end() );

    Preprocess preprocess( MakeFilter::box_kernel(3), image);
    preprocess.make_thick_kernel(cImage, dilationSize);
    preprocess.rm_out_edge_detected( idTr );

    #ifdef VERBOSE
    show_result( image, std::vector<IndexTransitionCluster>(idTr.begin(), idTr.end()));
    #endif

    Filter filter(cImage, idTr, 20, 5, 1, 10);
    cv::Mat result = filter.filter_image();
/*
    ContourTransition contourTransition(image);
    contourTransition.bw_push_transition( idTr );
    cv::Mat matTrans = contourTransition.show_matDataTrans();
*/
    #ifdef VERBOSE
    cv::namedWindow( "matTrans", cv::WINDOW_AUTOSIZE );
    cv::imshow( "matTrans", matTrans );
    cv::waitKey(0);
    // cv::namedWindow( "thickKernel", cv::WINDOW_AUTOSIZE );
    // cv::imshow( "thickKernel", preprocess.get_thickKernel() );

    cv::namedWindow( "GaussFiltered", cv::WINDOW_AUTOSIZE );
    cv::imshow( "GaussFiltered", result );
    cv::waitKey(0);
    #endif

    return result;
}<commit_msg>bilateral_08<commit_after>#include "show_result.hpp"

void save_result(const char* source_path, char const postFix[], char const outputFormat[], cv::Mat& image)
{
    char* destination_path = (char*)calloc( strlen(source_path) + strlen(postFix) + strlen(outputFormat) + strlen("\0"), sizeof(char) );

    const char* lastSlash = strrchr ( source_path, '.' );
    int lastSlashPos = lastSlash - source_path;

    strncpy( destination_path, source_path, lastSlashPos );

    int len = strlen( destination_path );
    strcpy( destination_path + len, postFix );

    len += strlen( postFix );
    strcpy( destination_path + len, source_path + lastSlashPos );

    len = strlen( destination_path );
    strcpy( destination_path + len, outputFormat );

    cv::imwrite( destination_path, image);
}

void p_around(unsigned char* data, int before, int after)
{
    for(int i = -before; i < after; ++i )
    {
        if(i == 0)
        {
            std::cout << "MARKER";
        }
        std::cout << data[i];
    }
}

void draw_clusterNumber(cv::Mat& image, std::vector<IndexTransitionCluster> const & result)
{
    std::vector<IndexTransitionCluster> textPoint(result);
    std::stable_sort( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
        if(el1.get_clusterNumber() < el2.get_clusterNumber())
        {
            return true;
        }
        else
        {
            return false;
        }
    } );
    textPoint.erase( unique( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
        if(el1.get_clusterNumber() == el2.get_clusterNumber())
        {
            return true;
        }
        else
        {
            return false;
        }
    } ), textPoint.end() );
    std::for_each(textPoint.begin(), textPoint.end(), [&image](auto el){
        cv::putText(image, std::to_string(el.get_clusterNumber()), cv::Point(el.col, el.row ), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cv::Scalar(200,20,250));//, 1, 8, false);
        std::cout<<el.get_clusterNumber()<<" "<<el.row<<" "<<el.col<<"\n";
    });
    std::cout<< result.size()<< "\n";
    std::cout<< textPoint.size()<< "\n";
}

cv::Mat show_result(cv::Mat const img, std::vector<IndexTransitionCluster> const & result )
{
    cv::Mat image = img.clone();
    cv::namedWindow( "show_result", cv::WINDOW_AUTOSIZE );
    cv::imshow( "show_result", image );
    cv::waitKey(0);

    if(image.isContinuous())
    {
        for_each(result.begin(), result.end(), [&image](auto el){
            image.data[el.index( image )] = 255;
            image.data[el.index( image ) + 1] = 0;
            image.data[el.index( image ) + 2] = 255;
        });
        draw_clusterNumber(image, result);
        cv::imshow( "show_result", image );
    }
    else
    {
        std::cout<<"notcontionuous\n";
        return image;
    }
//    cv::waitKey(0);

    cv::Mat blackImage(image.rows, image.cols, CV_8UC3, cv::Scalar(0,0,0));
    for_each(result.begin(), result.end(), [&blackImage](auto el){
        blackImage.data[el.index( blackImage )] = 255;
        blackImage.data[el.index( blackImage ) + 1] = 0;
        blackImage.data[el.index( blackImage ) + 2] = 255;
    });
    draw_clusterNumber(blackImage, result);
    cv::imshow( "show_result", blackImage );
    cv::waitKey(0);
    return blackImage;
}

std::vector<IndexTransitionCluster> test_on_image(const char* path, double factor, double eps, uint minPts)
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return std::vector<IndexTransitionCluster>();
    }

    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
    cv::Mat imageCpy = image.clone();
    cv::Mat imageCpy2 = image.clone();
    cv::Mat blackImage;

    TYPE acceptanceLevel = 60;
    ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
    double lightThreshold = 0.2;
    double colorThreshold = 0.2;

    IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance);
    auto result = entryProcess.iterate_HV();
    std::cout << result.size() << '\n';
    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    save_result(path, "_noisy", ".png", blackImage);
    ColorBalance cba( image, 5u, 6 );
    ColorStruct secondBalance = cba.balance( result );

    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    save_result(path, "_detect1", ".png", blackImage);
    result.resize( 0 );

    lightThreshold = 0.2;
    colorThreshold = 0.2;
    IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, ColorStruct{ 0.82, 1.05, 1.14 });//secondBalance);
    result = secondProcess.iterate_HV();

    blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
    save_result(path, "_detect_balanced", ".png", blackImage);

    Clustering clustering( result, Distance::distance_fast, eps, minPts);
    clustering.points_clustering(&Clustering::check_point_zone_linear);
    auto clusters = clustering.getRefVIndexTransitionCluster();
    blackImage = show_result(imageCpy, clusters);
    save_result(path, "_detect_cluster", ".png", blackImage);

    return clusters;
}

int broad_HUE(char* path)
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return -1;
    }

    cvtColor(image, image, CV_BGR2HSV);
    for(int i =2; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    cvtColor(image, image, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", image );
    save_result(path, "_OUT1", ".png", image);

    cv::Mat cpyImage = image.clone();
    cvtColor(cpyImage, cpyImage, CV_BGR2HSV);
    for(int i =2; i < cpyImage.rows * cpyImage.cols * 3; i+=3)
    {
        cpyImage.data[i] = cpyImage.data[i-1];
    }
    cvtColor(cpyImage, cpyImage, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", cpyImage );
    save_result(path, "_OUT3", ".png", cpyImage);

    cvtColor(image, image, CV_BGR2HSV);
    for(int i =2; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    for(int i = 1; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    cvtColor(image, image, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", image );
    save_result(path, "_OUT2", ".png", image);

    return 0;
}

cv::Mat test_canny( char* path, double factor, int dilationSize )
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return image;
    }
    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);

    Preprocess preprocess( MakeFilter::box_kernel(11), image);
    cv::Mat edges = preprocess.make_thick_kernel( image, dilationSize );
    cv::namedWindow( "Canny", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Canny", edges );
    cv::waitKey(0);

    return edges;
}

std::vector<IndexTransitionCluster> index_transition_part(cv::Mat const image, double eps, uint minPts, int compareDistance)
{
    cv::Mat imageCpy = image.clone();
    cv::Mat imageCpy2 = image.clone();
    cv::Mat blackImage;

    TYPE acceptanceLevel = 150;
    ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
    double lightThreshold = 0.03;
    double colorThreshold = 0.01;

    IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance, compareDistance);
    auto result = entryProcess.iterate_HV();

    ColorBalance cba( image, 5u, compareDistance );
    ColorStruct secondBalance = cba.balance( result );

    result.resize( 0 );
    //colorThreshold/=2;
    IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, secondBalance, compareDistance);//secondBalance);
    result = secondProcess.iterate_HV();

    Clustering clustering( result, Distance::distance_fast, eps, minPts);
    clustering.points_clustering(&Clustering::check_point_zone_linear);
    auto clusters = clustering.getRefVIndexTransitionCluster();

    #ifdef VERBOSE
    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
    blackImage = show_result(imageCpy, clusters);
    #endif

    return clusters;
}

cv::Mat test_gauss_directed(const char* path, double factor, int dilationSize )
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return image;
    }

    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
    cv::Mat cImage = image.clone();
    bilateralFilter( cImage, image, 30, 150, 150, cv::BORDER_REFLECT );

    // int sigma = 2;
    // cv::GaussianBlur( image, image, cv::Size(sigma*4+1, sigma*4+1), sigma);

    auto idTrCluster = index_transition_part( image, 3.0, 1, 7 );
    std::vector<IndexTransition> idTr( idTrCluster.begin(), idTrCluster.end() );

    Preprocess preprocess( MakeFilter::box_kernel(3), image);
    preprocess.make_thick_kernel(cImage, dilationSize);
    preprocess.rm_out_edge_detected( idTr );

    #ifdef VERBOSE
    show_result( image, std::vector<IndexTransitionCluster>(idTr.begin(), idTr.end()));
    #endif

    Filter filter(cImage, idTr, 20, 5, 1, 10);
    cv::Mat result = filter.filter_image();
/*
    ContourTransition contourTransition(image);
    contourTransition.bw_push_transition( idTr );
    cv::Mat matTrans = contourTransition.show_matDataTrans();
*/
    #ifdef VERBOSE
    cv::namedWindow( "matTrans", cv::WINDOW_AUTOSIZE );
    cv::imshow( "matTrans", matTrans );
    cv::waitKey(0);
    // cv::namedWindow( "thickKernel", cv::WINDOW_AUTOSIZE );
    // cv::imshow( "thickKernel", preprocess.get_thickKernel() );

    cv::namedWindow( "GaussFiltered", cv::WINDOW_AUTOSIZE );
    cv::imshow( "GaussFiltered", result );
    cv::waitKey(0);
    #endif

    return result;
}<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.foundation headers.
#include "foundation/math/population.h"
#include "foundation/utility/test.h"

using namespace foundation;

TEST_SUITE(Foundation_Math_Population)
{
    TEST_CASE(EmptyPopulation)
    {
        Population<int> pop;

        EXPECT_EQ(0, pop.get_size());
        EXPECT_EQ(0, pop.get_min());
        EXPECT_EQ(0, pop.get_max());
        EXPECT_EQ(0.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
        EXPECT_EQ(0.0, pop.get_var());
    }

    TEST_CASE(IntegerPopulationWithSingleZeroValue)
    {
        Population<int> pop;
        pop.insert(0);

        EXPECT_EQ(1, pop.get_size());
        EXPECT_EQ(0, pop.get_min());
        EXPECT_EQ(0, pop.get_max());
        EXPECT_EQ(0.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
        EXPECT_EQ(0.0, pop.get_var());
    }

    TEST_CASE(FloatingPointPopulationWithSingleZeroValue)
    {
        Population<double> pop;
        pop.insert(0.0);

        EXPECT_EQ(1, pop.get_size());
        EXPECT_EQ(0.0, pop.get_min());
        EXPECT_EQ(0.0, pop.get_max());
        EXPECT_EQ(0.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
        EXPECT_EQ(0.0, pop.get_var());
    }

    TEST_CASE(NonEmptyIntegerPopulation)
    {
        Population<int> pop;
        pop.insert(2);
        pop.insert(4);
        pop.insert(4);
        pop.insert(4);
        pop.insert(5);
        pop.insert(5);
        pop.insert(7);
        pop.insert(9);

        EXPECT_EQ(8, pop.get_size());
        EXPECT_EQ(2, pop.get_min());
        EXPECT_EQ(9, pop.get_max());
        EXPECT_FEQ(5.0, pop.get_mean());
        EXPECT_FEQ(2.0, pop.get_dev());
        EXPECT_FEQ(0.4, pop.get_var());
    }

    TEST_CASE(MergeEmptyPopulationIntoEmptyPopulation)
    {
        Population<int> pop;

        Population<int> other_pop;
        pop.merge(other_pop);

        EXPECT_EQ(0, pop.get_size());
        EXPECT_EQ(0, pop.get_min());
        EXPECT_EQ(0, pop.get_max());
        EXPECT_EQ(0.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
    }

    TEST_CASE(MergeEmptyPopulationIntoNonEmptyPopulation)
    {
        Population<int> pop;
        pop.insert(2);
        pop.insert(4);
        pop.insert(4);
        pop.insert(4);
        pop.insert(5);
        pop.insert(5);
        pop.insert(7);
        pop.insert(9);

        Population<int> other_pop;
        pop.merge(other_pop);

        EXPECT_EQ(8, pop.get_size());
        EXPECT_EQ(2, pop.get_min());
        EXPECT_EQ(9, pop.get_max());
        EXPECT_EQ(5.0, pop.get_mean());
        EXPECT_EQ(2.0, pop.get_dev());
    }

    TEST_CASE(MergeNonEmptyPopulationIntoEmptyPopulation)
    {
        Population<int> other_pop;
        other_pop.insert(2);
        other_pop.insert(4);
        other_pop.insert(4);
        other_pop.insert(4);
        other_pop.insert(5);
        other_pop.insert(5);
        other_pop.insert(7);
        other_pop.insert(9);

        Population<int> pop;
        pop.merge(other_pop);

        EXPECT_EQ(8, pop.get_size());
        EXPECT_EQ(2, pop.get_min());
        EXPECT_EQ(9, pop.get_max());
        EXPECT_EQ(5.0, pop.get_mean());
        EXPECT_EQ(2.0, pop.get_dev());
    }

    TEST_CASE(MergeNonPopulationIntoNonEmptyPopulation)
    {
        Population<int> pop;
        pop.insert(2);
        pop.insert(4);
        pop.insert(4);
        pop.insert(4);
        pop.insert(5);
        pop.insert(5);
        pop.insert(7);
        pop.insert(9);

        Population<int> other_pop;
        other_pop.insert(1);
        other_pop.insert(11);

        pop.merge(other_pop);

        Population<int> expected;
        expected.insert(2);
        expected.insert(4);
        expected.insert(4);
        expected.insert(4);
        expected.insert(5);
        expected.insert(5);
        expected.insert(7);
        expected.insert(9);
        expected.insert(1);
        expected.insert(11);

        EXPECT_EQ(expected.get_size(), pop.get_size());
        EXPECT_EQ(expected.get_min(), pop.get_min());
        EXPECT_EQ(expected.get_max(), pop.get_max());
        EXPECT_FEQ(expected.get_mean(), pop.get_mean());
        EXPECT_FEQ(expected.get_dev(), pop.get_dev());
    }
}
<commit_msg>added a test case.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.foundation headers.
#include "foundation/math/population.h"
#include "foundation/utility/test.h"

using namespace foundation;

TEST_SUITE(Foundation_Math_Population)
{
    TEST_CASE(EmptyPopulation)
    {
        Population<int> pop;

        EXPECT_EQ(0, pop.get_size());
        EXPECT_EQ(0, pop.get_min());
        EXPECT_EQ(0, pop.get_max());
        EXPECT_EQ(0.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
        EXPECT_EQ(0.0, pop.get_var());
    }

    TEST_CASE(IntegerPopulationWithSingleZeroValue)
    {
        Population<int> pop;
        pop.insert(0);

        EXPECT_EQ(1, pop.get_size());
        EXPECT_EQ(0, pop.get_min());
        EXPECT_EQ(0, pop.get_max());
        EXPECT_EQ(0.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
        EXPECT_EQ(0.0, pop.get_var());
    }

    TEST_CASE(FloatingPointPopulationWithSingleZeroValue)
    {
        Population<double> pop;
        pop.insert(0.0);

        EXPECT_EQ(1, pop.get_size());
        EXPECT_EQ(0.0, pop.get_min());
        EXPECT_EQ(0.0, pop.get_max());
        EXPECT_EQ(0.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
        EXPECT_EQ(0.0, pop.get_var());
    }

    TEST_CASE(FloatingPointPopulationWithSingleNonZeroValue)
    {
        Population<double> pop;
        pop.insert(5.0);

        EXPECT_EQ(1, pop.get_size());
        EXPECT_EQ(5.0, pop.get_min());
        EXPECT_EQ(5.0, pop.get_max());
        EXPECT_EQ(5.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
        EXPECT_EQ(0.0, pop.get_var());
    }

    TEST_CASE(NonEmptyIntegerPopulation)
    {
        Population<int> pop;
        pop.insert(2);
        pop.insert(4);
        pop.insert(4);
        pop.insert(4);
        pop.insert(5);
        pop.insert(5);
        pop.insert(7);
        pop.insert(9);

        EXPECT_EQ(8, pop.get_size());
        EXPECT_EQ(2, pop.get_min());
        EXPECT_EQ(9, pop.get_max());
        EXPECT_FEQ(5.0, pop.get_mean());
        EXPECT_FEQ(2.0, pop.get_dev());
        EXPECT_FEQ(0.4, pop.get_var());
    }

    TEST_CASE(MergeEmptyPopulationIntoEmptyPopulation)
    {
        Population<int> pop;

        Population<int> other_pop;
        pop.merge(other_pop);

        EXPECT_EQ(0, pop.get_size());
        EXPECT_EQ(0, pop.get_min());
        EXPECT_EQ(0, pop.get_max());
        EXPECT_EQ(0.0, pop.get_mean());
        EXPECT_EQ(0.0, pop.get_dev());
    }

    TEST_CASE(MergeEmptyPopulationIntoNonEmptyPopulation)
    {
        Population<int> pop;
        pop.insert(2);
        pop.insert(4);
        pop.insert(4);
        pop.insert(4);
        pop.insert(5);
        pop.insert(5);
        pop.insert(7);
        pop.insert(9);

        Population<int> other_pop;
        pop.merge(other_pop);

        EXPECT_EQ(8, pop.get_size());
        EXPECT_EQ(2, pop.get_min());
        EXPECT_EQ(9, pop.get_max());
        EXPECT_EQ(5.0, pop.get_mean());
        EXPECT_EQ(2.0, pop.get_dev());
    }

    TEST_CASE(MergeNonEmptyPopulationIntoEmptyPopulation)
    {
        Population<int> other_pop;
        other_pop.insert(2);
        other_pop.insert(4);
        other_pop.insert(4);
        other_pop.insert(4);
        other_pop.insert(5);
        other_pop.insert(5);
        other_pop.insert(7);
        other_pop.insert(9);

        Population<int> pop;
        pop.merge(other_pop);

        EXPECT_EQ(8, pop.get_size());
        EXPECT_EQ(2, pop.get_min());
        EXPECT_EQ(9, pop.get_max());
        EXPECT_EQ(5.0, pop.get_mean());
        EXPECT_EQ(2.0, pop.get_dev());
    }

    TEST_CASE(MergeNonPopulationIntoNonEmptyPopulation)
    {
        Population<int> pop;
        pop.insert(2);
        pop.insert(4);
        pop.insert(4);
        pop.insert(4);
        pop.insert(5);
        pop.insert(5);
        pop.insert(7);
        pop.insert(9);

        Population<int> other_pop;
        other_pop.insert(1);
        other_pop.insert(11);

        pop.merge(other_pop);

        Population<int> expected;
        expected.insert(2);
        expected.insert(4);
        expected.insert(4);
        expected.insert(4);
        expected.insert(5);
        expected.insert(5);
        expected.insert(7);
        expected.insert(9);
        expected.insert(1);
        expected.insert(11);

        EXPECT_EQ(expected.get_size(), pop.get_size());
        EXPECT_EQ(expected.get_min(), pop.get_min());
        EXPECT_EQ(expected.get_max(), pop.get_max());
        EXPECT_FEQ(expected.get_mean(), pop.get_mean());
        EXPECT_FEQ(expected.get_dev(), pop.get_dev());
    }
}
<|endoftext|>


<commit_before>/*!
    @file
    @author     Albert Semenov
    @date       08/2008
    @module
*/
#include "DemoKeeper.h"

namespace demo
{

	enum Type
	{
		None,
		Start,
		End,
		Miss,
		Accept,
		Refuse
	};

	struct State
	{
		enum
		{
			None,
			Start,
			End,
			Miss,
			Accept,
			Refuse
		};

		State() : value(None) { }
		State(int _value) : value(_value) { }
		//State(State const& _other) : value(_other.value) { }
		//State & operator = (State const& _other) { value = _other.value; return *this; }
		friend bool operator == (State const & a, State const & b) { return a.value == b.value; }
		friend bool operator != (State const & a, State const & b) { return a.value != b.value; }

		int value;
	};

	template <typename T>
	void checkParce(MyGUI::EditPtr _edit, size_t _count)
	{
		const Ogre::UTFString & text = _edit->getOnlyText();
		size_t index = _edit->getTextCursor();

		T p;
		std::istringstream str(text);
		while (_count > 0) {
			str >> p;
			-- _count;
		}
		if (str.fail()) {
			_edit->setCaption("#FF0000" + text);
		}
		else {
			std::string tmp;
			str >> tmp;
			if (!str.fail() || tmp.find_first_not_of(" \t\r") != std::string::npos) {
				_edit->setCaption("#FF0000" + text);
			}
			else {
				_edit->setCaption(text);
			}
		}
		_edit->setTextCursor(index);
	}

	void notifyEditTextChange(MyGUI::WidgetPtr _sender)
	{
		MyGUI::EditPtr edit = _sender->castType<MyGUI::Edit>();
		checkParce<int>(edit, 4);
	}

    void DemoKeeper::createScene()
    {

		const MyGUI::IntSize & view = MyGUI::Gui::getInstance().getViewSize();
        const MyGUI::IntSize size(100, 100);

        base::BaseManager::getInstance().addResourceLocation("../../Media/TestApp");
        base::BaseManager::getInstance().setWallpaper("wallpaper4.jpg");

		State type;

		State type1 = 0;
		type1 = 101;
		State type2 = State::Miss;

		type1 = type2;

		type1 == type2;
		type1 == State::Miss;
		State::End == type2;
		State::End != type2;

		State test = State::Start;
		//int value = type1;

		MyGUI::EditPtr edit = MyGUI::Gui::getInstance().createWidget<MyGUI::Edit>("Edit", MyGUI::IntCoord(100, 100, 150, 26), MyGUI::Align::Default, "Overlapped");
		edit->eventEditTextChange = MyGUI::newDelegate(notifyEditTextChange);
		//button->setMaskPeek("mask.png");

		/*MyGUI::DDContainerPtr container = MyGUI::Gui::getInstance().createWidget<MyGUI::DDContainer>("Default", MyGUI::IntCoord(100, 100, 50, 50), MyGUI::Align::Default, "Overlapped");
		container->setNeedDragDrop(true);
		container->setNeedToolTip(true);
		container->eventStartDrop = MyGUI::newDelegate(this, &DemoKeeper::notifyStartDrop);
		container->eventRequestDrop = MyGUI::newDelegate(this, &DemoKeeper::notifyRequestDrop);
		container->eventEndDrop = MyGUI::newDelegate(this, &DemoKeeper::notifyEndDrop);
		container->eventDropState = MyGUI::newDelegate(this, &DemoKeeper::notifyDropState);
		container->requestDropWidgetInfo = MyGUI::newDelegate(this, &DemoKeeper::requestDropWidgetInfo);
		container->eventUpdateDropState = MyGUI::newDelegate(this, &DemoKeeper::notifyUpdateDropState);
		container->eventToolTip = MyGUI::newDelegate(this, &DemoKeeper::notifyToolTip);

		MyGUI::StaticImagePtr image = container->createWidget<MyGUI::StaticImage>("StaticImage", MyGUI::IntCoord(0, 0, 50, 50), MyGUI::Align::Default);
		image->setNeedMouseFocus(false);
		image->setItemResource("pic_CoreMessageIcon");
		image->setItemGroup("Icons");
		image->setItemName("Error");

		mDropDimension.set(0, 0, 50, 50);
		mDropImage = MyGUI::Gui::getInstance().createWidget<MyGUI::StaticImage>("StaticImage", MyGUI::IntCoord(), MyGUI::Align::Default, "DragAndDrop");
		mDropImage->hide();
		mDropImage->setItemResource("pic_CoreMessageIcon");
		mDropImage->setItemGroup("Icons");
		mDropImage->setItemName("Info");*/

    }

    void DemoKeeper::destroyScene()
    {
    }

	/*void DemoKeeper::notifyStartDrop(MyGUI::WidgetPtr _sender, const MyGUI::ItemDropInfo & _info, bool & _result)
	{
		_result = true;
	}

	void DemoKeeper::notifyRequestDrop(MyGUI::WidgetPtr _sender, const MyGUI::ItemDropInfo & _info, bool & _result)
	{
		_result = _info.reseiver != null;
	}

	void DemoKeeper::notifyEndDrop(MyGUI::WidgetPtr _sender, const MyGUI::ItemDropInfo & _info, bool _result)
	{
	}

	void DemoKeeper::notifyDropState(MyGUI::WidgetPtr _sender, MyGUI::DropState _state)
	{
	}

	void DemoKeeper::notifyUpdateDropState(MyGUI::WidgetPtr _sender, MyGUI::VectorDropWidgetInfo & _items, const MyGUI::DropWidgetState & _state)
	{
		for (MyGUI::VectorDropWidgetInfo::iterator iter=_items.begin(); iter!=_items.end(); ++iter) {
			iter->item->castType<MyGUI::StaticImage>()->setItemName(_state.accept ? "Warning" : "Quest");
		}
	}

	void DemoKeeper::requestDropWidgetInfo(MyGUI::WidgetPtr _sender, MyGUI::VectorDropWidgetInfo & _items)
	{
		_items.push_back(MyGUI::DropWidgetInfo(mDropImage, mDropDimension));
	}

	void DemoKeeper::notifyToolTip(MyGUI::WidgetPtr _sender, const MyGUI::ToolTipInfo & _info)
	{
		MyGUI::MYGUI_OUT("ToolTip : ", (_info.type == MyGUI::ToolTipInfo::Show ? "show" : "hide"));
	}*/

} // namespace demo

  <commit_msg>add file search<commit_after>/*!
    @file
    @author     Albert Semenov
    @date       08/2008
    @module
*/
#include "DemoKeeper.h"

namespace demo
{

	enum Type
	{
		None,
		Start,
		End,
		Miss,
		Accept,
		Refuse
	};

	struct State
	{
		enum
		{
			None,
			Start,
			End,
			Miss,
			Accept,
			Refuse
		};

		State() : value(None) { }
		State(int _value) : value(_value) { }
		//State(State const& _other) : value(_other.value) { }
		//State & operator = (State const& _other) { value = _other.value; return *this; }
		friend bool operator == (State const & a, State const & b) { return a.value == b.value; }
		friend bool operator != (State const & a, State const & b) { return a.value != b.value; }

		int value;
	};

	template <typename T>
	void checkParce(MyGUI::EditPtr _edit, size_t _count)
	{
		static const Ogre::UTFString colour = "#FF0000";
		const Ogre::UTFString & text = _edit->getOnlyText();
		size_t index = _edit->getTextCursor();

		T p;
		std::istringstream str(text);
		while (_count > 0) {
			str >> p;
			-- _count;
		}
		if (str.fail()) {
			_edit->setCaption(colour + text);
		}
		else {
			std::string tmp;
			str >> tmp;
			if (!str.fail() || tmp.find_first_not_of(" \t\r") != std::string::npos) {
				_edit->setCaption(colour + text);
			}
			else {
				_edit->setCaption(text);
			}
		}
		_edit->setTextCursor(index);
	}

	void checkParceFileName(MyGUI::EditPtr _edit)
	{
		static const Ogre::UTFString colour = "#FF0000";
		const Ogre::UTFString & text = _edit->getOnlyText();
		size_t index = _edit->getTextCursor();

		if (text.find_first_of("*?") == std::string::npos) {
			Ogre::FileInfoListPtr pFileInfo = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(
				Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, text);
			//     ,   ,
			if (pFileInfo->size() != 1) {
				_edit->setCaption(colour + text);
			}
			else {
				_edit->setCaption(text);
			}
			pFileInfo.setNull();
		}
		else {
			_edit->setCaption(colour + text);
		}
		_edit->setTextCursor(index);
	}

	void notifyEditTextChange(MyGUI::WidgetPtr _sender)
	{
		MyGUI::EditPtr edit = _sender->castType<MyGUI::Edit>();
		checkParceFileName(edit);
		//checkParce<int>(edit, 4);
	}

    void DemoKeeper::createScene()
    {

		const MyGUI::IntSize & view = MyGUI::Gui::getInstance().getViewSize();
        const MyGUI::IntSize size(100, 100);

        base::BaseManager::getInstance().addResourceLocation("../../Media/TestApp");
        base::BaseManager::getInstance().setWallpaper("wallpaper4.jpg");

		State type;

		State type1 = 0;
		type1 = 101;
		State type2 = State::Miss;

		type1 = type2;

		type1 == type2;
		type1 == State::Miss;
		State::End == type2;
		State::End != type2;

		State test = State::Start;
		//int value = type1;

		MyGUI::EditPtr edit = MyGUI::Gui::getInstance().createWidget<MyGUI::Edit>("Edit", MyGUI::IntCoord(100, 100, 150, 26), MyGUI::Align::Default, "Overlapped");
		edit->eventEditTextChange = MyGUI::newDelegate(notifyEditTextChange);
		//button->setMaskPeek("mask.png");

		/*MyGUI::DDContainerPtr container = MyGUI::Gui::getInstance().createWidget<MyGUI::DDContainer>("Default", MyGUI::IntCoord(100, 100, 50, 50), MyGUI::Align::Default, "Overlapped");
		container->setNeedDragDrop(true);
		container->setNeedToolTip(true);
		container->eventStartDrop = MyGUI::newDelegate(this, &DemoKeeper::notifyStartDrop);
		container->eventRequestDrop = MyGUI::newDelegate(this, &DemoKeeper::notifyRequestDrop);
		container->eventEndDrop = MyGUI::newDelegate(this, &DemoKeeper::notifyEndDrop);
		container->eventDropState = MyGUI::newDelegate(this, &DemoKeeper::notifyDropState);
		container->requestDropWidgetInfo = MyGUI::newDelegate(this, &DemoKeeper::requestDropWidgetInfo);
		container->eventUpdateDropState = MyGUI::newDelegate(this, &DemoKeeper::notifyUpdateDropState);
		container->eventToolTip = MyGUI::newDelegate(this, &DemoKeeper::notifyToolTip);

		MyGUI::StaticImagePtr image = container->createWidget<MyGUI::StaticImage>("StaticImage", MyGUI::IntCoord(0, 0, 50, 50), MyGUI::Align::Default);
		image->setNeedMouseFocus(false);
		image->setItemResource("pic_CoreMessageIcon");
		image->setItemGroup("Icons");
		image->setItemName("Error");

		mDropDimension.set(0, 0, 50, 50);
		mDropImage = MyGUI::Gui::getInstance().createWidget<MyGUI::StaticImage>("StaticImage", MyGUI::IntCoord(), MyGUI::Align::Default, "DragAndDrop");
		mDropImage->hide();
		mDropImage->setItemResource("pic_CoreMessageIcon");
		mDropImage->setItemGroup("Icons");
		mDropImage->setItemName("Info");*/

    }

    void DemoKeeper::destroyScene()
    {
    }

	/*void DemoKeeper::notifyStartDrop(MyGUI::WidgetPtr _sender, const MyGUI::ItemDropInfo & _info, bool & _result)
	{
		_result = true;
	}

	void DemoKeeper::notifyRequestDrop(MyGUI::WidgetPtr _sender, const MyGUI::ItemDropInfo & _info, bool & _result)
	{
		_result = _info.reseiver != null;
	}

	void DemoKeeper::notifyEndDrop(MyGUI::WidgetPtr _sender, const MyGUI::ItemDropInfo & _info, bool _result)
	{
	}

	void DemoKeeper::notifyDropState(MyGUI::WidgetPtr _sender, MyGUI::DropState _state)
	{
	}

	void DemoKeeper::notifyUpdateDropState(MyGUI::WidgetPtr _sender, MyGUI::VectorDropWidgetInfo & _items, const MyGUI::DropWidgetState & _state)
	{
		for (MyGUI::VectorDropWidgetInfo::iterator iter=_items.begin(); iter!=_items.end(); ++iter) {
			iter->item->castType<MyGUI::StaticImage>()->setItemName(_state.accept ? "Warning" : "Quest");
		}
	}

	void DemoKeeper::requestDropWidgetInfo(MyGUI::WidgetPtr _sender, MyGUI::VectorDropWidgetInfo & _items)
	{
		_items.push_back(MyGUI::DropWidgetInfo(mDropImage, mDropDimension));
	}

	void DemoKeeper::notifyToolTip(MyGUI::WidgetPtr _sender, const MyGUI::ToolTipInfo & _info)
	{
		MyGUI::MYGUI_OUT("ToolTip : ", (_info.type == MyGUI::ToolTipInfo::Show ? "show" : "hide"));
	}*/

} // namespace demo

  <|endoftext|>


<commit_before>#include "show_result.hpp"

void save_result(const char* source_path, char const postFix[], char const outputFormat[], cv::Mat& image)
{
    char* destination_path = (char*)calloc( strlen(source_path) + strlen(postFix) + strlen(outputFormat) + strlen("\0"), sizeof(char) );

    const char* lastSlash = strrchr ( source_path, '.' );
    int lastSlashPos = lastSlash - source_path;

    strncpy( destination_path, source_path, lastSlashPos );

    int len = strlen( destination_path );
    strcpy( destination_path + len, postFix );

    len += strlen( postFix );
    strcpy( destination_path + len, source_path + lastSlashPos );

    len = strlen( destination_path );
    strcpy( destination_path + len, outputFormat );

    cv::imwrite( destination_path, image);
}

void p_around(unsigned char* data, int before, int after)
{
    for(int i = -before; i < after; ++i )
    {
        if(i == 0)
        {
            std::cout << "MARKER";
        }
        std::cout << data[i];
    }
}

void draw_clusterNumber(cv::Mat& image, std::vector<IndexTransitionCluster> const & result)
{
    std::vector<IndexTransitionCluster> textPoint(result);
    std::stable_sort( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
        if(el1.get_clusterNumber() < el2.get_clusterNumber())
        {
            return true;
        }
        else
        {
            return false;
        }
    } );
    textPoint.erase( unique( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
        if(el1.get_clusterNumber() == el2.get_clusterNumber())
        {
            return true;
        }
        else
        {
            return false;
        }
    } ), textPoint.end() );
    std::for_each(textPoint.begin(), textPoint.end(), [&image](auto el){
        cv::putText(image, std::to_string(el.get_clusterNumber()), cv::Point(el.col, el.row ), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cv::Scalar(200,20,250));//, 1, 8, false);
        std::cout<<el.get_clusterNumber()<<" "<<el.row<<" "<<el.col<<"\n";
    });
    std::cout<< result.size()<< "\n";
    std::cout<< textPoint.size()<< "\n";
}

cv::Mat show_result(cv::Mat const img, std::vector<IndexTransitionCluster> const & result )
{
    cv::Mat image = img.clone();
    cv::namedWindow( "show_result", cv::WINDOW_AUTOSIZE );
    cv::imshow( "show_result", image );
    cv::waitKey(0);

    if(image.isContinuous())
    {
        for_each(result.begin(), result.end(), [&image](auto el){
            image.data[el.index( image )] = 255;
            image.data[el.index( image ) + 1] = 0;
            image.data[el.index( image ) + 2] = 255;
        });
        draw_clusterNumber(image, result);
        cv::imshow( "show_result", image );
    }
    else
    {
        std::cout<<"notcontionuous\n";
        return image;
    }
//    cv::waitKey(0);

    cv::Mat blackImage(image.rows, image.cols, CV_8UC3, cv::Scalar(0,0,0));
    for_each(result.begin(), result.end(), [&blackImage](auto el){
        blackImage.data[el.index( blackImage )] = 255;
        blackImage.data[el.index( blackImage ) + 1] = 0;
        blackImage.data[el.index( blackImage ) + 2] = 255;
    });
    draw_clusterNumber(blackImage, result);
    cv::imshow( "show_result", blackImage );
    cv::waitKey(0);
    return blackImage;
}

std::vector<IndexTransitionCluster> test_on_image(const char* path, double factor, double eps, uint minPts)
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return std::vector<IndexTransitionCluster>();
    }

    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
    cv::Mat imageCpy = image.clone();
    cv::Mat imageCpy2 = image.clone();
    cv::Mat blackImage;

    TYPE acceptanceLevel = 60;
    ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
    double lightThreshold = 0.2;
    double colorThreshold = 0.2;

    IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance);
    auto result = entryProcess.iterate_HV();
    std::cout << result.size() << '\n';
    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    save_result(path, "_noisy", ".png", blackImage);
    ColorBalance cba( image, 5u, 6 );
    ColorStruct secondBalance = cba.balance( result );

    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    save_result(path, "_detect1", ".png", blackImage);
    result.resize( 0 );

    lightThreshold = 0.2;
    colorThreshold = 0.2;
    IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, ColorStruct{ 0.82, 1.05, 1.14 });//secondBalance);
    result = secondProcess.iterate_HV();

    blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
    save_result(path, "_detect_balanced", ".png", blackImage);

    Clustering clustering( result, Distance::distance_fast, eps, minPts);
    clustering.points_clustering(&Clustering::check_point_zone_linear);
    auto clusters = clustering.getRefVIndexTransitionCluster();
    blackImage = show_result(imageCpy, clusters);
    save_result(path, "_detect_cluster", ".png", blackImage);

    return clusters;
}

int broad_HUE(char* path)
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return -1;
    }

    cvtColor(image, image, CV_BGR2HSV);
    for(int i =2; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    cvtColor(image, image, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", image );
    save_result(path, "_OUT1", ".png", image);

    cv::Mat cpyImage = image.clone();
    cvtColor(cpyImage, cpyImage, CV_BGR2HSV);
    for(int i =2; i < cpyImage.rows * cpyImage.cols * 3; i+=3)
    {
        cpyImage.data[i] = cpyImage.data[i-1];
    }
    cvtColor(cpyImage, cpyImage, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", cpyImage );
    save_result(path, "_OUT3", ".png", cpyImage);

    cvtColor(image, image, CV_BGR2HSV);
    for(int i =2; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    for(int i = 1; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    cvtColor(image, image, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", image );
    save_result(path, "_OUT2", ".png", image);

    return 0;
}

cv::Mat test_canny( char* path, double factor, int dilationSize )
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return image;
    }
    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);

    Preprocess preprocess( MakeFilter::box_kernel(11), image);
    cv::Mat edges = preprocess.make_thick_kernel( image, dilationSize );
    cv::namedWindow( "Canny", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Canny", edges );
    cv::waitKey(0);

    return edges;
}

std::vector<IndexTransitionCluster> index_transition_part(cv::Mat const image, double eps, uint minPts, int compareDistance)
{
    cv::Mat imageCpy = image.clone();
    cv::Mat imageCpy2 = image.clone();
    cv::Mat blackImage;

    TYPE acceptanceLevel = 150;
    ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
    double lightThreshold = 0.03;
    double colorThreshold = 0.01;

    IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance, compareDistance);
    auto result = entryProcess.iterate_HV();

    ColorBalance cba( image, 5u, compareDistance );
    ColorStruct secondBalance = cba.balance( result );

    result.resize( 0 );
    //colorThreshold/=2;
    IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, secondBalance, compareDistance);//secondBalance);
    result = secondProcess.iterate_HV();

    Clustering clustering( result, Distance::distance_fast, eps, minPts);
    clustering.points_clustering(&Clustering::check_point_zone_linear);
    auto clusters = clustering.getRefVIndexTransitionCluster();

    #ifdef VERBOSE
    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
    blackImage = show_result(imageCpy, clusters);
    #endif

    return clusters;
}

cv::Mat test_gauss_directed(const char* path, double factor, int dilationSize )
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return image;
    }

    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
    cv::Mat cImage = image.clone();
    bilateralFilter( cImage, image, 30, 150, 150, cv::BORDER_REFLECT );

    // int sigma = 2;
    // cv::GaussianBlur( image, image, cv::Size(sigma*4+1, sigma*4+1), sigma);

    auto idTrCluster = index_transition_part( image, 3.0, 1, 7 );
    std::vector<IndexTransition> idTr( idTrCluster.begin(), idTrCluster.end() );
/*
    Preprocess preprocess( MakeFilter::box_kernel(3), image);
    preprocess.make_thick_kernel(cImage, dilationSize);
    preprocess.rm_out_edge_detected( idTr );
*/

    #ifdef VERBOSE
    show_result( image, std::vector<IndexTransitionCluster>(idTr.begin(), idTr.end()));
    #endif

    Filter filter(cImage, idTr, 150, 20, 1, 10);
    cv::Mat result = filter.filter_image();
/*
    ContourTransition contourTransition(image);
    contourTransition.bw_push_transition( idTr );
    cv::Mat matTrans = contourTransition.show_matDataTrans();
*/
    #ifdef VERBOSE
    cv::namedWindow( "matTrans", cv::WINDOW_AUTOSIZE );
    cv::imshow( "matTrans", matTrans );
    cv::waitKey(0);
    // cv::namedWindow( "thickKernel", cv::WINDOW_AUTOSIZE );
    // cv::imshow( "thickKernel", preprocess.get_thickKernel() );

    cv::namedWindow( "GaussFiltered", cv::WINDOW_AUTOSIZE );
    cv::imshow( "GaussFiltered", result );
    cv::waitKey(0);
    #endif

    return result;
}<commit_msg>normal_bilateral_05<commit_after>#include "show_result.hpp"

void save_result(const char* source_path, char const postFix[], char const outputFormat[], cv::Mat& image)
{
    char* destination_path = (char*)calloc( strlen(source_path) + strlen(postFix) + strlen(outputFormat) + strlen("\0"), sizeof(char) );

    const char* lastSlash = strrchr ( source_path, '.' );
    int lastSlashPos = lastSlash - source_path;

    strncpy( destination_path, source_path, lastSlashPos );

    int len = strlen( destination_path );
    strcpy( destination_path + len, postFix );

    len += strlen( postFix );
    strcpy( destination_path + len, source_path + lastSlashPos );

    len = strlen( destination_path );
    strcpy( destination_path + len, outputFormat );

    cv::imwrite( destination_path, image);
}

void p_around(unsigned char* data, int before, int after)
{
    for(int i = -before; i < after; ++i )
    {
        if(i == 0)
        {
            std::cout << "MARKER";
        }
        std::cout << data[i];
    }
}

void draw_clusterNumber(cv::Mat& image, std::vector<IndexTransitionCluster> const & result)
{
    std::vector<IndexTransitionCluster> textPoint(result);
    std::stable_sort( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
        if(el1.get_clusterNumber() < el2.get_clusterNumber())
        {
            return true;
        }
        else
        {
            return false;
        }
    } );
    textPoint.erase( unique( textPoint.begin(), textPoint.end(), [](auto el1, auto el2){
        if(el1.get_clusterNumber() == el2.get_clusterNumber())
        {
            return true;
        }
        else
        {
            return false;
        }
    } ), textPoint.end() );
    std::for_each(textPoint.begin(), textPoint.end(), [&image](auto el){
        cv::putText(image, std::to_string(el.get_clusterNumber()), cv::Point(el.col, el.row ), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cv::Scalar(200,20,250));//, 1, 8, false);
        std::cout<<el.get_clusterNumber()<<" "<<el.row<<" "<<el.col<<"\n";
    });
    std::cout<< result.size()<< "\n";
    std::cout<< textPoint.size()<< "\n";
}

cv::Mat show_result(cv::Mat const img, std::vector<IndexTransitionCluster> const & result )
{
    cv::Mat image = img.clone();
    cv::namedWindow( "show_result", cv::WINDOW_AUTOSIZE );
    cv::imshow( "show_result", image );
    cv::waitKey(0);

    if(image.isContinuous())
    {
        for_each(result.begin(), result.end(), [&image](auto el){
            image.data[el.index( image )] = 255;
            image.data[el.index( image ) + 1] = 0;
            image.data[el.index( image ) + 2] = 255;
        });
        draw_clusterNumber(image, result);
        cv::imshow( "show_result", image );
    }
    else
    {
        std::cout<<"notcontionuous\n";
        return image;
    }
//    cv::waitKey(0);

    cv::Mat blackImage(image.rows, image.cols, CV_8UC3, cv::Scalar(0,0,0));
    for_each(result.begin(), result.end(), [&blackImage](auto el){
        blackImage.data[el.index( blackImage )] = 255;
        blackImage.data[el.index( blackImage ) + 1] = 0;
        blackImage.data[el.index( blackImage ) + 2] = 255;
    });
    draw_clusterNumber(blackImage, result);
    cv::imshow( "show_result", blackImage );
    cv::waitKey(0);
    return blackImage;
}

std::vector<IndexTransitionCluster> test_on_image(const char* path, double factor, double eps, uint minPts)
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return std::vector<IndexTransitionCluster>();
    }

    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
    cv::Mat imageCpy = image.clone();
    cv::Mat imageCpy2 = image.clone();
    cv::Mat blackImage;

    TYPE acceptanceLevel = 60;
    ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
    double lightThreshold = 0.2;
    double colorThreshold = 0.2;

    IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance);
    auto result = entryProcess.iterate_HV();
    std::cout << result.size() << '\n';
    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    save_result(path, "_noisy", ".png", blackImage);
    ColorBalance cba( image, 5u, 6 );
    ColorStruct secondBalance = cba.balance( result );

    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    save_result(path, "_detect1", ".png", blackImage);
    result.resize( 0 );

    lightThreshold = 0.2;
    colorThreshold = 0.2;
    IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, ColorStruct{ 0.82, 1.05, 1.14 });//secondBalance);
    result = secondProcess.iterate_HV();

    blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
    save_result(path, "_detect_balanced", ".png", blackImage);

    Clustering clustering( result, Distance::distance_fast, eps, minPts);
    clustering.points_clustering(&Clustering::check_point_zone_linear);
    auto clusters = clustering.getRefVIndexTransitionCluster();
    blackImage = show_result(imageCpy, clusters);
    save_result(path, "_detect_cluster", ".png", blackImage);

    return clusters;
}

int broad_HUE(char* path)
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return -1;
    }

    cvtColor(image, image, CV_BGR2HSV);
    for(int i =2; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    cvtColor(image, image, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", image );
    save_result(path, "_OUT1", ".png", image);

    cv::Mat cpyImage = image.clone();
    cvtColor(cpyImage, cpyImage, CV_BGR2HSV);
    for(int i =2; i < cpyImage.rows * cpyImage.cols * 3; i+=3)
    {
        cpyImage.data[i] = cpyImage.data[i-1];
    }
    cvtColor(cpyImage, cpyImage, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", cpyImage );
    save_result(path, "_OUT3", ".png", cpyImage);

    cvtColor(image, image, CV_BGR2HSV);
    for(int i =2; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    for(int i = 1; i < image.rows * image.cols * 3; i+=3)
    {
        image.data[i] = 255;
    }
    cvtColor(image, image, CV_HSV2BGR);
    cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Display window", image );
    save_result(path, "_OUT2", ".png", image);

    return 0;
}

cv::Mat test_canny( char* path, double factor, int dilationSize )
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return image;
    }
    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);

    Preprocess preprocess( MakeFilter::box_kernel(11), image);
    cv::Mat edges = preprocess.make_thick_kernel( image, dilationSize );
    cv::namedWindow( "Canny", cv::WINDOW_AUTOSIZE );
    cv::imshow( "Canny", edges );
    cv::waitKey(0);

    return edges;
}

std::vector<IndexTransitionCluster> index_transition_part(cv::Mat const image, double eps, uint minPts, int compareDistance)
{
    cv::Mat imageCpy = image.clone();
    cv::Mat imageCpy2 = image.clone();
    cv::Mat blackImage;

    TYPE acceptanceLevel = 150;
    ColorStruct entryBalance{ 1.0, 1.0, 1.0 };
    double lightThreshold = 0.03;
    double colorThreshold = 0.01;

    IterateProcess<TYPE> entryProcess(image, acceptanceLevel, lightThreshold, colorThreshold, entryBalance, compareDistance);
    auto result = entryProcess.iterate_HV();

    ColorBalance cba( image, 5u, compareDistance );
    ColorStruct secondBalance = cba.balance( result );

    result.resize( 0 );
    //colorThreshold/=2;
    IterateProcess<TYPE> secondProcess(imageCpy2, acceptanceLevel, lightThreshold, colorThreshold, secondBalance, compareDistance);//secondBalance);
    result = secondProcess.iterate_HV();

    Clustering clustering( result, Distance::distance_fast, eps, minPts);
    clustering.points_clustering(&Clustering::check_point_zone_linear);
    auto clusters = clustering.getRefVIndexTransitionCluster();

    #ifdef VERBOSE
    blackImage = show_result( image, std::vector<IndexTransitionCluster>( result.begin(), result.end() ) );
    blackImage = show_result(imageCpy2, std::vector<IndexTransitionCluster>( result.begin(), result.end() ));
    blackImage = show_result(imageCpy, clusters);
    #endif

    return clusters;
}

cv::Mat test_gauss_directed(const char* path, double factor, int dilationSize )
{
    cv::Mat image;
    image = cv::imread(path, CV_LOAD_IMAGE_COLOR);
    if(! image.data )
    {
        std::cout<<"\nwrong path\n";
        return image;
    }

    cv::resize(image, image, cv::Size(), factor, factor, cv::INTER_NEAREST);
    cv::Mat cImage = image.clone();
    bilateralFilter( cImage, image, 30, 150, 150, cv::BORDER_REFLECT );

    // int sigma = 2;
    // cv::GaussianBlur( image, image, cv::Size(sigma*4+1, sigma*4+1), sigma);

    auto idTrCluster = index_transition_part( image, 3.0, 1, 7 );
    std::vector<IndexTransition> idTr( idTrCluster.begin(), idTrCluster.end() );
/*
    Preprocess preprocess( MakeFilter::box_kernel(3), image);
    preprocess.make_thick_kernel(cImage, dilationSize);
    preprocess.rm_out_edge_detected( idTr );
*/

    #ifdef VERBOSE
    show_result( image, std::vector<IndexTransitionCluster>(idTr.begin(), idTr.end()));
    #endif

    Filter filter(cImage, idTr, 80, 15, 1, 10);
    cv::Mat result = filter.filter_image();
/*
    ContourTransition contourTransition(image);
    contourTransition.bw_push_transition( idTr );
    cv::Mat matTrans = contourTransition.show_matDataTrans();
*/
    #ifdef VERBOSE
    cv::namedWindow( "matTrans", cv::WINDOW_AUTOSIZE );
    cv::imshow( "matTrans", matTrans );
    cv::waitKey(0);
    // cv::namedWindow( "thickKernel", cv::WINDOW_AUTOSIZE );
    // cv::imshow( "thickKernel", preprocess.get_thickKernel() );

    cv::namedWindow( "GaussFiltered", cv::WINDOW_AUTOSIZE );
    cv::imshow( "GaussFiltered", result );
    cv::waitKey(0);
    #endif

    return result;
}<|endoftext|>


<commit_before>/**
 *
 *    Copyright (c) 2020-2021 Project CHIP Authors
 *    Copyright (c) 2018 Google LLC.
 *    Copyright (c) 2016-2017 Nest Labs, Inc.
 *    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.
 */
/**
 *    @file
 *      This file defines message helper functions in CHIP interaction model
 *
 */

#include "MessageDefHelper.h"
#include <algorithm>
#include <app/AppConfig.h>
#include <app/InteractionModelRevision.h>
#include <app/util/basic-types.h>
#include <inttypes.h>
#include <lib/support/logging/CHIPLogging.h>
#include <stdarg.h>
#include <stdio.h>

namespace chip {
namespace app {
#if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK && CHIP_DETAIL_LOGGING
// this is used to run in signle thread for IM message debug purpose
namespace {
uint32_t gPrettyPrintingDepthLevel = 0;
char gLineBuffer[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE];
size_t gCurLineBufferSize = 0;
} // namespace

void PrettyPrintIMBlankLine()
{
    if (gCurLineBufferSize)
    {
        // Don't need to explicitly NULL-terminate the string because
        // snprintf takes care of that.
        ChipLogDetail(DataManagement, "%s", gLineBuffer);
        gCurLineBufferSize = 0;
    }

    for (uint32_t i = 0; i < gPrettyPrintingDepthLevel; i++)
    {
        if (sizeof(gLineBuffer) > gCurLineBufferSize)
        {
            size_t sizeLeft = sizeof(gLineBuffer) - gCurLineBufferSize;
            size_t ret      = (size_t)(snprintf(gLineBuffer + gCurLineBufferSize, sizeLeft, "\t"));
            if (ret > 0)
            {
                gCurLineBufferSize += std::min(ret, sizeLeft);
            }
        }
    }
}

void PrettyPrintIM(bool aIsNewLine, const char * aFmt, ...)
{
    va_list args;
    va_start(args, aFmt);

    if (aIsNewLine)
    {
        PrettyPrintIMBlankLine();
    }

    if (sizeof(gLineBuffer) > gCurLineBufferSize)
    {
        size_t sizeLeft = sizeof(gLineBuffer) - gCurLineBufferSize;
        size_t ret      = (size_t)(vsnprintf(gLineBuffer + gCurLineBufferSize, sizeLeft, aFmt, args));
        if (ret > 0)
        {
            gCurLineBufferSize += std::min(ret, sizeLeft);
        }
    }

    va_end(args);
}
void IncreaseDepth()
{
    gPrettyPrintingDepthLevel++;
}

void DecreaseDepth()
{
    gPrettyPrintingDepthLevel--;
}
#endif

#if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK
CHIP_ERROR CheckIMPayload(TLV::TLVReader & aReader, int aDepth, const char * aLabel)
{
    if (aDepth == 0)
    {
        PRETTY_PRINT("%s = ", aLabel);
    }
    else
    {
        if (TLV::IsContextTag(aReader.GetTag()))
        {
            PRETTY_PRINT("0x%" PRIx32 " = ", TLV::TagNumFromTag(aReader.GetTag()));
        }
        else if (TLV::IsProfileTag(aReader.GetTag()))
        {
            PRETTY_PRINT("0x%" PRIx32 "::0x%" PRIx32 " = ", TLV::ProfileIdFromTag(aReader.GetTag()),
                         TLV::TagNumFromTag(aReader.GetTag()));
        }
        else
        {
            // Anonymous tag, don't print anything
        }
    }

    switch (aReader.GetType())
    {
    case TLV::kTLVType_Structure:
        PRETTY_PRINT("{");
        break;

    case TLV::kTLVType_Array:
        PRETTY_PRINT_SAMELINE("[");
        PRETTY_PRINT("\t\t");
        break;

    case TLV::kTLVType_SignedInteger: {
        int64_t value_s64;

        ReturnErrorOnFailure(aReader.Get(value_s64));

        PRETTY_PRINT_SAMELINE("%" PRId64 ", ", value_s64);
        break;
    }

    case TLV::kTLVType_UnsignedInteger: {
        uint64_t value_u64;

        ReturnErrorOnFailure(aReader.Get(value_u64));

        PRETTY_PRINT_SAMELINE("%" PRIu64 ", ", value_u64);
        break;
    }

    case TLV::kTLVType_FloatingPointNumber: {
        double value_fp;

        ReturnErrorOnFailure(aReader.Get(value_fp));

        PRETTY_PRINT_SAMELINE("%f, ", value_fp);
        break;
    }
    case TLV::kTLVType_Boolean: {
        bool value_b;

        ReturnErrorOnFailure(aReader.Get(value_b));

        PRETTY_PRINT_SAMELINE("%s, ", value_b ? "true" : "false");
        break;
    }

    case TLV::kTLVType_UTF8String: {
        char value_s[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE];

#if CHIP_DETAIL_LOGGING
        uint32_t readerLen = aReader.GetLength();
#endif // CHIP_DETAIL_LOGGING
        CHIP_ERROR err = aReader.GetString(value_s, sizeof(value_s));
        VerifyOrReturnError(err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL, err);

        if (err == CHIP_ERROR_BUFFER_TOO_SMALL)
        {
            PRETTY_PRINT_SAMELINE("... (char string too long: %" PRIu32 " chars) ...", readerLen);
        }
        else
        {
            PRETTY_PRINT_SAMELINE("\"%s\" (%" PRIu32 " chars), ", value_s, readerLen);
        }
        break;
    }

    case TLV::kTLVType_ByteString: {
        uint8_t value_b[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE];
        uint32_t len, readerLen;

        readerLen = aReader.GetLength();

        CHIP_ERROR err = aReader.GetBytes(value_b, sizeof(value_b));
        VerifyOrReturnError(err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL, err);

        PRETTY_PRINT_SAMELINE("[");
        PRETTY_PRINT("\t\t");

        if (readerLen < sizeof(value_b))
        {
            len = readerLen;
        }
        else
        {
            len = sizeof(value_b);
        }

        if (err == CHIP_ERROR_BUFFER_TOO_SMALL)
        {
            PRETTY_PRINT_SAMELINE("... (byte string too long) ...");
        }
        else
        {
            for (size_t i = 0; i < len; i++)
            {
                PRETTY_PRINT_SAMELINE("0x%x, ", value_b[i]);
            }
        }

        PRETTY_PRINT("] (%" PRIu32 " bytes)", readerLen);
        break;
    }

    case TLV::kTLVType_Null:
        PRETTY_PRINT_SAMELINE("NULL");
        break;

    default:
        PRETTY_PRINT_SAMELINE("--");
        break;
    }

    if (aReader.GetType() == TLV::kTLVType_Structure || aReader.GetType() == TLV::kTLVType_Array)
    {
        const char terminating_char = (aReader.GetType() == TLV::kTLVType_Structure) ? '}' : ']';
        TLV::TLVType type;

        IgnoreUnusedVariable(terminating_char);

        ReturnErrorOnFailure(aReader.EnterContainer(type));

        CHIP_ERROR err;
        while ((err = aReader.Next()) == CHIP_NO_ERROR)
        {
            PRETTY_PRINT_INCDEPTH();

            ReturnErrorOnFailure(CheckIMPayload(aReader, aDepth + 1, aLabel));

            PRETTY_PRINT_DECDEPTH();
        }

        PRETTY_PRINT("%c,", terminating_char);

        ReturnErrorOnFailure(aReader.ExitContainer(type));
    }

    return CHIP_NO_ERROR;
}

#endif // CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK

}; // namespace app
}; // namespace chip
<commit_msg>Make MessageDef byte string logging nicer. (#22707)<commit_after>/**
 *
 *    Copyright (c) 2020-2021 Project CHIP Authors
 *    Copyright (c) 2018 Google LLC.
 *    Copyright (c) 2016-2017 Nest Labs, Inc.
 *    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.
 */
/**
 *    @file
 *      This file defines message helper functions in CHIP interaction model
 *
 */

#include "MessageDefHelper.h"
#include <algorithm>
#include <app/AppConfig.h>
#include <app/InteractionModelRevision.h>
#include <app/util/basic-types.h>
#include <inttypes.h>
#include <lib/support/logging/CHIPLogging.h>
#include <stdarg.h>
#include <stdio.h>

namespace chip {
namespace app {
#if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK && CHIP_DETAIL_LOGGING
// this is used to run in signle thread for IM message debug purpose
namespace {
uint32_t gPrettyPrintingDepthLevel = 0;
char gLineBuffer[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE];
size_t gCurLineBufferSize = 0;
} // namespace

void PrettyPrintIMBlankLine()
{
    if (gCurLineBufferSize)
    {
        // Don't need to explicitly NULL-terminate the string because
        // snprintf takes care of that.
        ChipLogDetail(DataManagement, "%s", gLineBuffer);
        gCurLineBufferSize = 0;
    }

    for (uint32_t i = 0; i < gPrettyPrintingDepthLevel; i++)
    {
        if (sizeof(gLineBuffer) > gCurLineBufferSize)
        {
            size_t sizeLeft = sizeof(gLineBuffer) - gCurLineBufferSize;
            size_t ret      = (size_t)(snprintf(gLineBuffer + gCurLineBufferSize, sizeLeft, "\t"));
            if (ret > 0)
            {
                gCurLineBufferSize += std::min(ret, sizeLeft);
            }
        }
    }
}

void PrettyPrintIM(bool aIsNewLine, const char * aFmt, ...)
{
    va_list args;
    va_start(args, aFmt);

    if (aIsNewLine)
    {
        PrettyPrintIMBlankLine();
    }

    if (sizeof(gLineBuffer) > gCurLineBufferSize)
    {
        size_t sizeLeft = sizeof(gLineBuffer) - gCurLineBufferSize;
        size_t ret      = (size_t)(vsnprintf(gLineBuffer + gCurLineBufferSize, sizeLeft, aFmt, args));
        if (ret > 0)
        {
            gCurLineBufferSize += std::min(ret, sizeLeft);
        }
    }

    va_end(args);
}
void IncreaseDepth()
{
    gPrettyPrintingDepthLevel++;
}

void DecreaseDepth()
{
    gPrettyPrintingDepthLevel--;
}
#endif

#if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK
CHIP_ERROR CheckIMPayload(TLV::TLVReader & aReader, int aDepth, const char * aLabel)
{
    if (aDepth == 0)
    {
        PRETTY_PRINT("%s = ", aLabel);
    }
    else
    {
        if (TLV::IsContextTag(aReader.GetTag()))
        {
            PRETTY_PRINT("0x%" PRIx32 " = ", TLV::TagNumFromTag(aReader.GetTag()));
        }
        else if (TLV::IsProfileTag(aReader.GetTag()))
        {
            PRETTY_PRINT("0x%" PRIx32 "::0x%" PRIx32 " = ", TLV::ProfileIdFromTag(aReader.GetTag()),
                         TLV::TagNumFromTag(aReader.GetTag()));
        }
        else
        {
            // Anonymous tag, don't print anything
        }
    }

    switch (aReader.GetType())
    {
    case TLV::kTLVType_Structure:
        PRETTY_PRINT("{");
        break;

    case TLV::kTLVType_Array:
        PRETTY_PRINT_SAMELINE("[");
        PRETTY_PRINT("\t\t");
        break;

    case TLV::kTLVType_SignedInteger: {
        int64_t value_s64;

        ReturnErrorOnFailure(aReader.Get(value_s64));

        PRETTY_PRINT_SAMELINE("%" PRId64 ", ", value_s64);
        break;
    }

    case TLV::kTLVType_UnsignedInteger: {
        uint64_t value_u64;

        ReturnErrorOnFailure(aReader.Get(value_u64));

        PRETTY_PRINT_SAMELINE("%" PRIu64 ", ", value_u64);
        break;
    }

    case TLV::kTLVType_FloatingPointNumber: {
        double value_fp;

        ReturnErrorOnFailure(aReader.Get(value_fp));

        PRETTY_PRINT_SAMELINE("%f, ", value_fp);
        break;
    }
    case TLV::kTLVType_Boolean: {
        bool value_b;

        ReturnErrorOnFailure(aReader.Get(value_b));

        PRETTY_PRINT_SAMELINE("%s, ", value_b ? "true" : "false");
        break;
    }

    case TLV::kTLVType_UTF8String: {
        char value_s[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE];

#if CHIP_DETAIL_LOGGING
        uint32_t readerLen = aReader.GetLength();
#endif // CHIP_DETAIL_LOGGING
        CHIP_ERROR err = aReader.GetString(value_s, sizeof(value_s));
        VerifyOrReturnError(err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL, err);

        if (err == CHIP_ERROR_BUFFER_TOO_SMALL)
        {
            PRETTY_PRINT_SAMELINE("... (char string too long: %" PRIu32 " chars) ...", readerLen);
        }
        else
        {
            PRETTY_PRINT_SAMELINE("\"%s\" (%" PRIu32 " chars), ", value_s, readerLen);
        }
        break;
    }

    case TLV::kTLVType_ByteString: {
        uint8_t value_b[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE];
        uint32_t len, readerLen;

        readerLen = aReader.GetLength();

        CHIP_ERROR err = aReader.GetBytes(value_b, sizeof(value_b));
        VerifyOrReturnError(err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL, err);

        PRETTY_PRINT_SAMELINE("[");
        PRETTY_PRINT("\t\t");

        if (readerLen < sizeof(value_b))
        {
            len = readerLen;
        }
        else
        {
            len = sizeof(value_b);
        }

        if (err == CHIP_ERROR_BUFFER_TOO_SMALL)
        {
            PRETTY_PRINT_SAMELINE("... (byte string too long) ...");
        }
        else
        {
            for (size_t i = 0; i < len; i++)
            {
                PRETTY_PRINT_SAMELINE("0x%02x, ", value_b[i]);
            }
        }

        PRETTY_PRINT("] (%" PRIu32 " bytes)", readerLen);
        break;
    }

    case TLV::kTLVType_Null:
        PRETTY_PRINT_SAMELINE("NULL");
        break;

    default:
        PRETTY_PRINT_SAMELINE("--");
        break;
    }

    if (aReader.GetType() == TLV::kTLVType_Structure || aReader.GetType() == TLV::kTLVType_Array)
    {
        const char terminating_char = (aReader.GetType() == TLV::kTLVType_Structure) ? '}' : ']';
        TLV::TLVType type;

        IgnoreUnusedVariable(terminating_char);

        ReturnErrorOnFailure(aReader.EnterContainer(type));

        CHIP_ERROR err;
        while ((err = aReader.Next()) == CHIP_NO_ERROR)
        {
            PRETTY_PRINT_INCDEPTH();

            ReturnErrorOnFailure(CheckIMPayload(aReader, aDepth + 1, aLabel));

            PRETTY_PRINT_DECDEPTH();
        }

        PRETTY_PRINT("%c,", terminating_char);

        ReturnErrorOnFailure(aReader.ExitContainer(type));
    }

    return CHIP_NO_ERROR;
}

#endif // CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK

}; // namespace app
}; // namespace chip
<|endoftext|>