<commit_before>#include "pixmapcodecpng.h"

#include <Tempest/IDevice>
#include <Tempest/ODevice>

#include <png.h>
#include <cstring>

using namespace Tempest;

struct PixmapCodecPng::Impl {
  IDevice* data = nullptr;
  uint8_t* out  = nullptr;

  Impl(IDevice* idev)
    :data(idev) {
    }

  ~Impl(){
    std::free(out);
    }

  bool readPng(png_structp png_ptr, png_infop info_ptr,
               Pixmap::Format& frm, uint32_t& outW, uint32_t& outH, uint32_t& outBpp) {
    if(setjmp(png_jmpbuf(png_ptr))) {
      // png exception
      return false;
      }
    //png_init_io(png_ptr, data);
    png_set_read_fn  (png_ptr, this, &Impl::read );
    png_set_sig_bytes(png_ptr, 8);

    png_read_info(png_ptr, info_ptr);

    outW = png_get_image_width (png_ptr, info_ptr);
    outH = png_get_image_height(png_ptr, info_ptr);

    png_byte colorType = png_get_color_type(png_ptr, info_ptr);
    png_byte bitDepth  = png_get_bit_depth(png_ptr, info_ptr);
    if(bitDepth!=8 && bitDepth!=16)
      return false;

    if(colorType == PNG_COLOR_TYPE_PALETTE)
      png_set_palette_to_rgb(png_ptr);

    colorType = png_get_color_type(png_ptr, info_ptr);

    if(colorType==PNG_COLOR_TYPE_GRAY){
      outBpp = 1;
      frm    = Pixmap::Format::R;
      }
    else if(colorType==PNG_COLOR_TYPE_GRAY_ALPHA){
      //png_set_gray_to_rgb(png_ptr);
      outBpp = 2;
      frm    = Pixmap::Format::RG;
      }
    else if(colorType==PNG_COLOR_TYPE_RGB){
      outBpp = 3;
      frm    = Pixmap::Format::RGB;
      }
    else if(colorType==PNG_COLOR_TYPE_RGB_ALPHA){
      outBpp = 4;
      frm    = Pixmap::Format::RGBA;
      }
    else {
      return false;
      }

    if(bitDepth==16) {
      png_set_swap(png_ptr);
      outBpp*=2;
      frm = Pixmap::Format(uint8_t(Pixmap::Format::R16)+uint8_t(frm)-uint8_t(Pixmap::Format::R));
      }

    out = reinterpret_cast<uint8_t*>(malloc(outW*outH*outBpp));
    png_set_interlace_handling(png_ptr);
    png_read_update_info(png_ptr, info_ptr);

    // Based on png_read_image(png_ptr,imgRows)
    int pass =  png_set_interlace_handling(png_ptr);
    for(int j = 0; j < pass; j++) {
      for(uint32_t y=0; y<outH; y++) {
        png_bytep rp = &out[y*outW*outBpp];
        png_read_row(png_ptr, rp, nullptr);
        }
      }

    png_read_end(png_ptr, info_ptr);
    return true;
    }

  static void read( png_structp png_ptr,
                    png_bytep   outBytes,
                    png_size_t  byteCountToRead ){
    if(!png_get_io_ptr(png_ptr)){
      return;
      }

    Impl& r = *reinterpret_cast<Impl*>(png_get_io_ptr(png_ptr));
    if(r.data->read(outBytes, byteCountToRead)!=byteCountToRead) {
      png_error(png_ptr,"unable to read input stream");
      }
    }
  };

static void png_write_data(png_structp png_ptr, png_bytep data, png_size_t length){
  ODevice* f = reinterpret_cast<ODevice*>(png_get_io_ptr(png_ptr));
  f->write(data, length);
  }

static void png_flush(png_structp png_ptr){
  ODevice* f = reinterpret_cast<ODevice*>(png_get_io_ptr(png_ptr));
  f->flush();
  }

PixmapCodecPng::PixmapCodecPng() {
  }

bool PixmapCodecPng::testFormat(const PixmapCodec::Context& c) const {
  png_byte head[8];
  return c.peek(head,8)==8 && png_sig_cmp(head, 0, 8)==0;
  }

uint8_t* PixmapCodecPng::load(PixmapCodec::Context& c, uint32_t& w, uint32_t& h,
                              Pixmap::Format& frm, uint32_t& mipCnt, size_t& dataSz, uint32_t& bpp) const {
  auto& f = c.device;
  png_byte head[8];
  if(f.read(head,8)!=8 || png_sig_cmp(head, 0, 8)!=0)
    return nullptr;

  // initialize stuff
  png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  if(png_ptr==nullptr)
    return nullptr;

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if(info_ptr==nullptr) {
    png_destroy_read_struct(&png_ptr, nullptr, nullptr);
    return nullptr;
    }

  // work
  Impl r(&f);
  bool readed = r.readPng(png_ptr,info_ptr,frm,w,h,bpp);

  // cleanup
  png_destroy_info_struct(png_ptr, &info_ptr);
  png_destroy_read_struct(&png_ptr, nullptr, nullptr);

  uint8_t* out = nullptr;
  if(readed) {
    out    = r.out;
    mipCnt = 1;
    dataSz = w*h*bpp;
    r.out = nullptr;
    }
  return out;
  }

bool PixmapCodecPng::save(ODevice& f, const char* ext, const uint8_t* data,
                          size_t /*dataSz*/, uint32_t w, uint32_t h, Pixmap::Format frm) const {
  if(ext!=nullptr && std::strcmp("png",ext)!=0)
    return false;

  uint32_t bpp       = 0;
  uint32_t bitDepth  = 0;
  int      colorType = 0;
  switch(frm) {
    case Pixmap::Format::R:{
      bpp       = 1;
      bitDepth  = 8;
      colorType = PNG_COLOR_TYPE_GRAY;
      break;
      }
    case Pixmap::Format::RG:{
      bpp       = 2;
      bitDepth  = 8;
      colorType = PNG_COLOR_TYPE_GRAY_ALPHA;
      break;
      }
    case Pixmap::Format::RGB:{
      bpp       = 3;
      bitDepth  = 8;
      colorType = PNG_COLOR_TYPE_RGB;
      break;
      }
    case Pixmap::Format::R16:{
      bpp       = 2;
      bitDepth  = 16;
      colorType = PNG_COLOR_TYPE_GRAY;
      break;
      }
    case Pixmap::Format::RG16:{
      bpp       = 4;
      bitDepth  = 16;
      colorType = PNG_COLOR_TYPE_GRAY_ALPHA;
      break;
      }
    case Pixmap::Format::RGBA:{
      bpp      = 4;
      bitDepth = 8;
      colorType = PNG_COLOR_TYPE_RGBA;
      break;
      }
    case Pixmap::Format::RGB16:{
      bpp      = 6;
      bitDepth = 16;
      colorType = PNG_COLOR_TYPE_RGB;
      break;
      }
    case Pixmap::Format::RGBA16:{
      bpp      = 8;
      bitDepth = 16;
      colorType = PNG_COLOR_TYPE_RGBA;
      break;
      }
    default:
      return false;
    }

  png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  if(png_ptr==nullptr)
    return false;

  png_infop   info_ptr = png_create_info_struct(png_ptr);
  if(info_ptr==nullptr) {
    png_destroy_write_struct(&png_ptr,nullptr);
    return false;
    }

  if(setjmp(png_jmpbuf(png_ptr))) {
    png_destroy_info_struct(png_ptr, &info_ptr);
    png_destroy_write_struct(&png_ptr,nullptr);
    return false;
    }

  png_set_write_fn(png_ptr, &f, png_write_data, png_flush);

  // write header
  png_set_IHDR( png_ptr, info_ptr, w, h,
                bitDepth,
                colorType,
                PNG_INTERLACE_NONE,
                PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

  png_write_info(png_ptr, info_ptr);
  png_set_swap(png_ptr);

  // write bytes
  {
  const int num_pass = png_set_interlace_handling(png_ptr);
  // Loop through passes
  for(int pass = 0; pass < num_pass; pass++) {
    // Loop through image
    for(uint32_t i=0; i<h; i++) {
      const png_byte* rp = &data[i*w*bpp];
      png_write_row(png_ptr, rp);
      }
    }
  png_write_end(png_ptr, nullptr);
  }

  // cleanup
  png_destroy_info_struct(png_ptr, &info_ptr);
  png_destroy_write_struct(&png_ptr,nullptr);
  return true;
  }
<commit_msg>fix png codec<commit_after>#include "pixmapcodecpng.h"

#include <Tempest/IDevice>
#include <Tempest/ODevice>

#include <png.h>
#include <cstring>

using namespace Tempest;

struct PixmapCodecPng::Impl {
  IDevice* data = nullptr;
  uint8_t* out  = nullptr;

  Impl(IDevice* idev)
    :data(idev) {
    }

  ~Impl(){
    std::free(out);
    }

  bool readPng(png_structp png_ptr, png_infop info_ptr,
               Pixmap::Format& frm, uint32_t& outW, uint32_t& outH, uint32_t& outBpp) {
    if(setjmp(png_jmpbuf(png_ptr))) {
      // png exception
      return false;
      }
    //png_init_io(png_ptr, data);
    png_set_read_fn  (png_ptr, this, &Impl::read );
    png_set_sig_bytes(png_ptr, 8);

    png_read_info(png_ptr, info_ptr);

    outW = png_get_image_width (png_ptr, info_ptr);
    outH = png_get_image_height(png_ptr, info_ptr);

    png_byte colorType = png_get_color_type(png_ptr, info_ptr);
    png_byte bitDepth  = png_get_bit_depth(png_ptr,  info_ptr);

    if(colorType==PNG_COLOR_TYPE_GRAY) {
      if(bitDepth<8)
        png_set_expand_gray_1_2_4_to_8(png_ptr);
      outBpp = 1;
      frm    = Pixmap::Format::R;
      }
    else if(colorType==PNG_COLOR_TYPE_GRAY_ALPHA) {
      //png_set_gray_to_rgb(png_ptr);
      if(bitDepth!=8 && bitDepth!=16)
        return false;
      outBpp = 2;
      frm    = Pixmap::Format::RG;
      }
    else if(colorType==PNG_COLOR_TYPE_RGB) {
      if(bitDepth!=8 && bitDepth!=16)
        return false;
      outBpp = 3;
      frm    = Pixmap::Format::RGB;
      }
    else if(colorType==PNG_COLOR_TYPE_RGB_ALPHA) {
      if(bitDepth!=8 && bitDepth!=16)
        return false;
      outBpp = 4;
      frm    = Pixmap::Format::RGBA;
      }
    else if(colorType==PNG_COLOR_TYPE_PALETTE) {
      png_set_palette_to_rgb(png_ptr);
      outBpp = 3;
      frm    = Pixmap::Format::RGB;
      }
    else {
      return false;
      }

    if(bitDepth==16) {
      png_set_swap(png_ptr);
      outBpp*=2;
      frm = Pixmap::Format(uint8_t(Pixmap::Format::R16)+uint8_t(frm)-uint8_t(Pixmap::Format::R));
      }

    out = reinterpret_cast<uint8_t*>(malloc(outW*outH*outBpp));
    png_set_interlace_handling(png_ptr);
    png_read_update_info(png_ptr, info_ptr);

    // Based on png_read_image(png_ptr,imgRows)
    int pass =  png_set_interlace_handling(png_ptr);
    for(int j = 0; j < pass; j++) {
      for(uint32_t y=0; y<outH; y++) {
        png_bytep rp = &out[y*outW*outBpp];
        png_read_row(png_ptr, rp, nullptr);
        }
      }

    png_read_end(png_ptr, info_ptr);
    return true;
    }

  static void read( png_structp png_ptr,
                    png_bytep   outBytes,
                    png_size_t  byteCountToRead ){
    if(!png_get_io_ptr(png_ptr)){
      return;
      }

    Impl& r = *reinterpret_cast<Impl*>(png_get_io_ptr(png_ptr));
    if(r.data->read(outBytes, byteCountToRead)!=byteCountToRead) {
      png_error(png_ptr,"unable to read input stream");
      }
    }
  };

static void png_write_data(png_structp png_ptr, png_bytep data, png_size_t length){
  ODevice* f = reinterpret_cast<ODevice*>(png_get_io_ptr(png_ptr));
  f->write(data, length);
  }

static void png_flush(png_structp png_ptr){
  ODevice* f = reinterpret_cast<ODevice*>(png_get_io_ptr(png_ptr));
  f->flush();
  }

PixmapCodecPng::PixmapCodecPng() {
  }

bool PixmapCodecPng::testFormat(const PixmapCodec::Context& c) const {
  png_byte head[8];
  return c.peek(head,8)==8 && png_sig_cmp(head, 0, 8)==0;
  }

uint8_t* PixmapCodecPng::load(PixmapCodec::Context& c, uint32_t& w, uint32_t& h,
                              Pixmap::Format& frm, uint32_t& mipCnt, size_t& dataSz, uint32_t& bpp) const {
  auto& f = c.device;
  png_byte head[8];
  if(f.read(head,8)!=8 || png_sig_cmp(head, 0, 8)!=0)
    return nullptr;

  // initialize stuff
  png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  if(png_ptr==nullptr)
    return nullptr;

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if(info_ptr==nullptr) {
    png_destroy_read_struct(&png_ptr, nullptr, nullptr);
    return nullptr;
    }

  // work
  Impl r(&f);
  bool readed = r.readPng(png_ptr,info_ptr,frm,w,h,bpp);

  // cleanup
  png_destroy_info_struct(png_ptr, &info_ptr);
  png_destroy_read_struct(&png_ptr, nullptr, nullptr);

  uint8_t* out = nullptr;
  if(readed) {
    out    = r.out;
    mipCnt = 1;
    dataSz = w*h*bpp;
    r.out = nullptr;
    }
  return out;
  }

bool PixmapCodecPng::save(ODevice& f, const char* ext, const uint8_t* data,
                          size_t /*dataSz*/, uint32_t w, uint32_t h, Pixmap::Format frm) const {
  if(ext!=nullptr && std::strcmp("png",ext)!=0)
    return false;

  uint32_t bpp       = 0;
  uint32_t bitDepth  = 0;
  int      colorType = 0;
  switch(frm) {
    case Pixmap::Format::R:{
      bpp       = 1;
      bitDepth  = 8;
      colorType = PNG_COLOR_TYPE_GRAY;
      break;
      }
    case Pixmap::Format::RG:{
      bpp       = 2;
      bitDepth  = 8;
      colorType = PNG_COLOR_TYPE_GRAY_ALPHA;
      break;
      }
    case Pixmap::Format::RGB:{
      bpp       = 3;
      bitDepth  = 8;
      colorType = PNG_COLOR_TYPE_RGB;
      break;
      }
    case Pixmap::Format::R16:{
      bpp       = 2;
      bitDepth  = 16;
      colorType = PNG_COLOR_TYPE_GRAY;
      break;
      }
    case Pixmap::Format::RG16:{
      bpp       = 4;
      bitDepth  = 16;
      colorType = PNG_COLOR_TYPE_GRAY_ALPHA;
      break;
      }
    case Pixmap::Format::RGBA:{
      bpp      = 4;
      bitDepth = 8;
      colorType = PNG_COLOR_TYPE_RGBA;
      break;
      }
    case Pixmap::Format::RGB16:{
      bpp      = 6;
      bitDepth = 16;
      colorType = PNG_COLOR_TYPE_RGB;
      break;
      }
    case Pixmap::Format::RGBA16:{
      bpp      = 8;
      bitDepth = 16;
      colorType = PNG_COLOR_TYPE_RGBA;
      break;
      }
    default:
      return false;
    }

  png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  if(png_ptr==nullptr)
    return false;

  png_infop   info_ptr = png_create_info_struct(png_ptr);
  if(info_ptr==nullptr) {
    png_destroy_write_struct(&png_ptr,nullptr);
    return false;
    }

  if(setjmp(png_jmpbuf(png_ptr))) {
    png_destroy_info_struct(png_ptr, &info_ptr);
    png_destroy_write_struct(&png_ptr,nullptr);
    return false;
    }

  png_set_write_fn(png_ptr, &f, png_write_data, png_flush);

  // write header
  png_set_IHDR( png_ptr, info_ptr, w, h,
                bitDepth,
                colorType,
                PNG_INTERLACE_NONE,
                PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

  png_write_info(png_ptr, info_ptr);
  png_set_swap(png_ptr);

  // write bytes
  {
  const int num_pass = png_set_interlace_handling(png_ptr);
  // Loop through passes
  for(int pass = 0; pass < num_pass; pass++) {
    // Loop through image
    for(uint32_t i=0; i<h; i++) {
      const png_byte* rp = &data[i*w*bpp];
      png_write_row(png_ptr, rp);
      }
    }
  png_write_end(png_ptr, nullptr);
  }

  // cleanup
  png_destroy_info_struct(png_ptr, &info_ptr);
  png_destroy_write_struct(&png_ptr,nullptr);
  return true;
  }
<|endoftext|>


<commit_before>#ifndef GUARD_HMM_HPP
#define GUARD_HMM_HPP

#include <map>
#include <string>
#include <vector>

class HiddenMarkovModel
{
public:
	HiddenMarkovModel(const std::string& filename);

	size_t numOfStates() const { return _numOfStates; }
	size_t numOfOutputs() const { return _numOfOutputs; }

	/** Return state transition probability from states stt1 to stt2. */
	double transition(const std::string& stt1, const std::string& stt2);
	/** Return observation emission probability of output out in state stt. */
	double emission(const std::string& stt, const std::string& out);
	/** Return initial state probability of state stt. */
	double initState(const std::string& stt);

	/** Returns initial probability of starting in a state. */
	double initEval(const std::string& out, const std::string& stt);
	/** Returns probability of a single output symbol and a state transition. */
	double eval(const std::string& out, const std::string stts[2]);
	/** Returns probability of an output sequence based on a given state sequence. */
	double eval(const std::vector<std::string>& out, const std::vector<std::string>& stt);

	/** Returns the forward variables for each observation sequence in a given .obs file. */
	std::vector<double> forward(const std::string& filename);
	/** Returns the backward variables for each observation sequence in a given .obs file. */
	std::vector<double> backward(const std::string& filename);
	/** Returns the most likely state sequence for each observation sequence in an .obs file. */
	std::vector<std::pair<double, std::vector<std::string> > > viterbi(const std::string& filename);

private:
	double forwardHelper(const std::vector<std::string>& obs, int t, const std::string& curStt);
	double backwardHelper(const std::vector<std::string>& obs, int t, const std::string& curStt);
	std::pair<double, std::vector<std::string> > viterbiHelper(const std::vector<std::string>& obs);

private:
	size_t _numOfStates, _numOfOutputs;

	std::vector<std::string> _stateNames;

	std::map<std::string, std::map<std::string, double> > _transitions;
	std::map<std::string, std::map<std::string, double> > _emissions;
	std::map<std::string, double> _initStates;
};

/*
 * Utility functions
 */

/** Return a vector of this line split into space delimited words. */
template <typename T> std::vector<T> split(const std::string& line);
/** Return vector of observation sequences in an .obs file. */
std::vector<std::vector<std::string> > parseObsFile(const std::string& filename);

#endif
<commit_msg>add more documentation to HMM interface<commit_after>#ifndef GUARD_HMM_HPP
#define GUARD_HMM_HPP

#include <map>
#include <string>
#include <vector>

class HiddenMarkovModel
{
public:
	HiddenMarkovModel(const std::string& filename);

	size_t numOfStates() const { return _numOfStates; }
	size_t numOfOutputs() const { return _numOfOutputs; }

	/**
	 * Return state transition probability from states stt1 to stt2.
	 * @param stt1 source state
	 * @param stt2 destination state
	 */
	double transition(const std::string& stt1, const std::string& stt2);
	/**
	 * Return observation emission probability of output out in state stt.
	 * @param stt current state
	 * @param out the output symbol observed at this state
	 */
	double emission(const std::string& stt, const std::string& out);
	/**
	 * Return initial state probability of state stt.
	 * @param stt current state
	 */
	double initState(const std::string& stt);

	/**
	 * Returns initial probability of starting in a state.
	 */
	double initEval(const std::string& out, const std::string& stt);
	/**
	 * Returns probability of a single output symbol and a state transition.
	 */
	double eval(const std::string& out, const std::string stts[2]);
	/**
	 * Returns probability of an output sequence based on a given state sequence.
	 */
	double eval(const std::vector<std::string>& out, const std::vector<std::string>& stt);

	/**
	 * Returns the forward variables for each observation sequence in a given .obs file.
	 */
	std::vector<double> forward(const std::string& filename);
	/**
	 * Returns the backward variables for each observation sequence in a given .obs file.
	 */
	std::vector<double> backward(const std::string& filename);
	/**
	 * Returns the pair of the most likely state sequence probability and its actual state path
	 * for each observation sequence in a given .obs file.
	 */
	std::vector<std::pair<double, std::vector<std::string> > > viterbi(const std::string& filename);

private:
	double forwardHelper(const std::vector<std::string>&, int, const std::string&);
	double backwardHelper(const std::vector<std::string>&, int, const std::string&);
	std::pair<double, std::vector<std::string> > viterbiHelper(const std::vector<std::string>&);

private:
	size_t _numOfStates, _numOfOutputs;

	std::vector<std::string> _stateNames;

	std::map<std::string, std::map<std::string, double> > _transitions;
	std::map<std::string, std::map<std::string, double> > _emissions;
	std::map<std::string, double> _initStates;
};

/*
 * Utility functions
 */

/** Return a vector of this line split into space delimited words. */
template <typename T> std::vector<T> split(const std::string& line);
/** Return vector of observation sequences in an .obs file. */
std::vector<std::vector<std::string> > parseObsFile(const std::string& filename);

#endif
<|endoftext|>


<commit_before>/* main.cpp */

#include <iostream>
#include "export_cfg.hpp"
#include "Feed.hpp"

using namespace std;

int main(int argc, char* argv[])
{
		string feed_url;

		// validate arguments
  		if (argc == 2)
		{
			feed_url = argv[1];
		}
		else
		{
			cerr << "usage: FeedReaderTester.exe <feed_url>\n";
            return 1;
		}

        try
        {
				// init once per process
				FeedReader::Feed::Initialize();

				// create custom feed config with the path of the xsl files
				FeedReader::FeedConfig feedConfig("../xsl");

				// optionally, customize the list of xsl files and feed types
				// feedConfig.m_feed_types.clear();
				// feedConfig.m_feed_types.push_back(std::make_pair("BroadCatching_02_xsl.txt", "BroadCatching02"));

				// create feed reader
				FeedReader::Feed feedReader(feed_url,feedConfig);

				// check feed
				feedReader.CheckFeed();

				// get results
				std::cout << "----------Feed---------" <<endl
					      << "URL: '" << feedReader.GetUrl() << "'" << endl;
				// print channel elements
				for (FeedReader::Feed::feed_element_iterator fitr = feedReader.begin_feed_elements();
					 fitr != feedReader.end_feed_elements(); fitr++)
				{
					std::cout << fitr->first << ":	'" <<  fitr->second << "'" << endl;
				}

				// print item elements
				for (FeedReader::Feed::entry_iterator itr = feedReader.begin_entries();
					 itr != feedReader.end_entries(); itr++)
				{
					std::cout << "Item ID: '"	<< itr->UniqueId	<< "'" << std::endl
							  << "IsLive: '"	<< itr->IsLive		<< "'" << std::endl;
					itr->Print(std::cout);
				}
        }
        catch (exception& e)
        {
				cout << "Exception: " << e.what() << "\n";
        }
		catch (...)
		{
			    cout << "Unknown exception." << "\n";
		}

        return 0;
}
<commit_msg>Add comments<commit_after>/* feed_reader_tester.cpp */

#include <iostream>
#include "export_cfg.hpp"
#include "Feed.hpp"

using namespace std;

int main(int argc, char* argv[])
{
	string feed_url;

	// validate arguments
	if (argc == 2)
	{
		feed_url = argv[1];
	}
	else
	{
		cerr << "usage: FeedReaderTester.exe <feed_url>\n";
		return 1;
	}

	try
	{
		// init once per process, needed by xerces and curl
		FeedReader::Feed::Initialize();

		// create custom FeedConfig with the path of the xsl files
		// it is possible no to pass a FeedConfig instance to FeedReader,
		// in such a case xsl files will be searched for in the working dir.
		FeedReader::FeedConfig feedConfig("../xsl");

		// optionally, customize the list of xsl files and feed types
		// in this commented case we extend support for one nonstandard feed type.
		// feedConfig.m_feed_types.clear();
		// feedConfig.m_feed_types.push_back(std::make_pair("BroadCatching_02_xsl.txt", "BroadCatching02"));

		// create feed reader instance
		// it takes a URL of the feed we wish to fetch,
		// and optionaly a FeedConfig instance.
		FeedReader::Feed feedReader(feed_url,feedConfig);

		// check feed - retrieves and parses results.
		// we can repeat this step as often as we wish to
		// update feed results, but it is recommended to
		// take the value of the TTL feed element into account.
		// when available, the TTL element is a way for the server
		// to tall us the minimal recommended refresh interval.
		feedReader.CheckFeed();

		// get results
		cout << "----------Feed---------" << endl
		     << "URL: '" << feedReader.GetUrl() << "'" << endl;
		// print elements (feed level information)
		for (FeedReader::Feed::feed_element_iterator fitr = feedReader.begin_feed_elements();
			fitr != feedReader.end_feed_elements(); fitr++)
		{
			std::cout << fitr->first << ":	'" <<  fitr->second << "'" << endl;
		}

		// print items(post level information)
		for (FeedReader::Feed::entry_iterator itr = feedReader.begin_entries();
			itr != feedReader.end_entries(); itr++)
		{
			std::cout << "Item ID: '"	<< itr->UniqueId	<< "'" << endl
				<< "IsLive: '"	<< itr->IsLive		<< "'" << endl;
			itr->Print(cout);
		}
	}
	catch (exception& e)
	{
		cout << "Exception: " << e.what() << "\n";
	}
	catch (...)
	{
		cout << "Unknown exception." << "\n";
	}

	return 0;
}<|endoftext|>


<commit_before>#ifndef CPPNOTESMAIN_FIND_MIN_NUM_IN_ROTATED_SORTED_ARRAY_HPP
#define CPPNOTESMAIN_FIND_MIN_NUM_IN_ROTATED_SORTED_ARRAY_HPP

/*
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
Suppose an array of length n sorted in ascending order is rotated between 1 and n times.
For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array
[a[n-1], a[0], a[1], a[2], ..., a[n-2]].

Given the sorted rotated array nums, return the minimum element of this array.

Example 1:
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.

Example 2:
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.

Example 3:
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times.

Constraints:
* n == nums.length
* 1 <= n <= 5000
* -5000 <= nums[i] <= 5000
* All the integers of nums are unique.
* nums is sorted and rotated between 1 and n times.
*/

#include <vector>

namespace Algo::DS::Array {
    template <typename T>
    class FindMinValue {
    public:
        T find_in_rotated_sorted_array(const vector<T>& nums) {
            if (nums.empty()) { return -1; }
            if (nums.size() == 1) { return nums.front(); }

            size_t left = 0;
            size_t right = nums.size() - 1;
            size_t pos = 0;
            while (left <= right) {
                auto mid = left + (right - left) / 2;
                if (nums[left] <= nums[mid]) {
                    if (nums[pos] > nums[left]) {
                        pos = left;
                    }

                    left = mid + 1;
                }
                else {
                    if (nums[pos] > nums[mid]) {
                        pos = mid;
                    }

                    if (mid == 0) { break; }

                    right = mid - 1;
                }
            }

            return nums[pos];
        }
    };
}

#endif //CPPNOTESMAIN_FIND_MIN_NUM_IN_ROTATED_SORTED_ARRAY_HPP
<commit_msg>Add algo - find min num in rotated sorted array with duplicates<commit_after>#ifndef CPPNOTESMAIN_FIND_MIN_NUM_IN_ROTATED_SORTED_ARRAY_HPP
#define CPPNOTESMAIN_FIND_MIN_NUM_IN_ROTATED_SORTED_ARRAY_HPP

/*
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
Suppose an array of length n sorted in ascending order is rotated between 1 and n times.
For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array
[a[n-1], a[0], a[1], a[2], ..., a[n-2]].

Given the sorted rotated array nums, return the minimum element of this array.

Example 1:
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.

Example 2:
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.

Example 3:
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times.

Constraints:
* n == nums.length
* 1 <= n <= 5000
* -5000 <= nums[i] <= 5000
* All the integers of nums are unique.
* nums is sorted and rotated between 1 and n times.
*/

/*
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).

Find the minimum element. The array may contain duplicates.

Example 1:
Input: [1,3,5]
Output: 1

Example 2:
Input: [2,2,2,0,1]
Output: 0

Note:
* This is a follow up problem to Find Minimum in Rotated Sorted Array.
* Would allow duplicates affect the run-time complexity? How and why?
*/

#include <vector>

namespace Algo::DS::Array {
    template <typename T>
    class FindMinValue {
    public:
        T find_in_rotated_sorted_array(const std::vector<T>& nums) {
            if (nums.empty()) { return -1; }
            if (nums.size() == 1) { return nums.front(); }

            size_t left = 0;
            size_t right = nums.size() - 1;
            size_t pos = 0;
            while (left <= right) {
                auto mid = left + (right - left) / 2;
                if (nums[left] <= nums[mid]) {
                    if (nums[pos] > nums[left]) {
                        pos = left;
                    }

                    left = mid + 1;
                }
                else {
                    if (nums[pos] > nums[mid]) {
                        pos = mid;
                    }

                    if (mid == 0) { break; }

                    right = mid - 1;
                }
            }

            return nums[pos];
        }

        T find_in_rotated_sorted_array_with_duplicates(const std::vector<T>& nums) {
            if (nums.empty()) { return -1; }
            if (nums.size() == 1) { return nums.front(); }

            size_t left = 0;
            size_t right = nums.size() - 1;
            while (left < right)
            {
                auto mid = left + (right - left) / 2;
                if (nums[mid] > nums[right]) { left = mid + 1; }
                else if (nums[mid] < nums[right]) { right = mid; }
                else { --right; }
            }

            return nums[left];
        }
    };
}

#endif //CPPNOTESMAIN_FIND_MIN_NUM_IN_ROTATED_SORTED_ARRAY_HPP
<|endoftext|>


<commit_before>#ifdef USE_MEM_CHECK
#include <mcheck.h>
#endif

#include <osg/Group>
#include <osg/Notify>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgProducer/Viewer>

#include <osg/Quat>

#if defined (WIN32) && !defined(__CYGWIN__)
#include <winsock.h>
#endif

#include "receiver.h"
#include "broadcaster.h"

typedef unsigned char * BytePtr;
template <class T>
inline void swapBytes(  T &s )
{
    if( sizeof( T ) == 1 ) return;

    T d = s;
    BytePtr sptr = (BytePtr)&s;
    BytePtr dptr = &(((BytePtr)&d)[sizeof(T)-1]);

    for( unsigned int i = 0; i < sizeof(T); i++ )
        *(sptr++) = *(dptr--);
}

class CameraPacket {
    public:

        CameraPacket():_masterKilled(false)
        {
            _byte_order = 0x12345678;
        }

        void setPacket(const osg::Matrix& matrix,const osg::FrameStamp* frameStamp)
        {
            _matrix = matrix;
            if (frameStamp)
            {
                _frameStamp    = *frameStamp;
            }
        }

        void getModelView(osg::Matrix& matrix,float angle_offset=0.0f)
        {

            matrix = _matrix * osg::Matrix::rotate(osg::DegreesToRadians(angle_offset),0.0f,1.0f,0.0f);
        }

        void checkByteOrder( void )
        {
            if( _byte_order == 0x78563412 )  // We're backwards
            {
                swapBytes( _byte_order );
            swapBytes( _masterKilled );
            for( int i = 0; i < 16; i++ )
                swapBytes( _matrix.ptr()[i] );

                    // umm.. we should byte swap _frameStamp too...
            }
        }

        void setMasterKilled(const bool flag) { _masterKilled = flag; }
        const bool getMasterKilled() const { return _masterKilled; }

    unsigned long   _byte_order;
        bool            _masterKilled;
        osg::Matrix     _matrix;

        // note don't use a ref_ptr as used elsewhere for FrameStamp
        // since we don't want to copy the pointer - but the memory.
        // FrameStamp doesn't have a private destructor to allow
        // us to do this, even though its a reference counted object.
        osg::FrameStamp  _frameStamp;

};

enum ViewerMode
{
    STAND_ALONE,
    SLAVE,
    MASTER
};

int main( int argc, char **argv )
{

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering. Note, cluster support will soon be encompassed in Producer itself.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
    arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, reciving view via packets.");
    arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
    arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
    arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // read up the osgcluster specific arguments.
    ViewerMode viewerMode = STAND_ALONE;
    while (arguments.read("-m")) viewerMode = MASTER;
    while (arguments.read("-s")) viewerMode = SLAVE;

    float socketNumber=8100.0f;
    while (arguments.read("-n",socketNumber)) ;

    float camera_fov=-1.0f;
    while (arguments.read("-f",camera_fov))
    {
    }

    float camera_offset=45.0f;
    while (arguments.read("-o",camera_offset)) ;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // load model.
    osg::ref_ptr<osg::Node> rootnode = osgDB::readNodeFiles(arguments);

    // set the scene to render
    viewer.setSceneData(rootnode.get());

    // create the windows and run the threads.
    viewer.realize();

    // set up the lens after realize as the Producer lens is not set up properly before this.... will need to inveestigate this at a later date.
    if (camera_fov>0.0f)
    {
        float aspectRatio = tan( osg::DegreesToRadians(viewer.getLensVerticalFov()*0.5)) / tan(osg::DegreesToRadians(viewer.getLensHorizontalFov()*0.5));
        float new_fovy = osg::RadiansToDegrees(atan( aspectRatio * tan( osg::DegreesToRadians(camera_fov*0.5))))*2.0f;
        std::cout << "setting lens perspective : original "<<viewer.getLensHorizontalFov()<<"  "<<viewer.getLensVerticalFov()<<std::endl;
        viewer.setLensPerspective(camera_fov,new_fovy,1.0f,1000.0f);
        std::cout << "setting lens perspective : new "<<viewer.getLensHorizontalFov()<<"  "<<viewer.getLensVerticalFov()<<std::endl;
    }

    CameraPacket *cp = new CameraPacket;
    // objects for managing the broadcasting and recieving of camera packets.
    Broadcaster     bc;
    Receiver        rc;

    bc.setPort(static_cast<short int>(socketNumber));
    rc.setPort(static_cast<short int>(socketNumber));

    bool masterKilled = false;

    while( !viewer.done() && !masterKilled )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // special handling for working as a cluster.
        switch (viewerMode)
        {
        case(MASTER):
            {

                // take camera zero as the guide.
                osg::Matrix modelview(viewer.getCameraConfig()->getCamera(0)->getViewMatrix());

                cp->setPacket(modelview,viewer.getFrameStamp());

                bc.setBuffer(cp, sizeof( CameraPacket ));

                bc.sync();

            }
            break;
        case(SLAVE):
            {

                rc.setBuffer(cp, sizeof( CameraPacket ));

                rc.sync();

                cp->checkByteOrder();

                osg::Matrix modelview;
                cp->getModelView(modelview,camera_offset);

                viewer.setView(modelview);

                if (cp->getMasterKilled())
                {
                    std::cout << "received master killed"<<std::endl;
                    // break out of while (!done) loop since we've now want to shut down.
                    masterKilled = true;
                }
            }
            break;
        default:
            // no need to anything here, just a normal interactive viewer.
            break;
        }

        // fire off the cull and draw traversals of the scene.
        if(!masterKilled)
            viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    // if we are master clean up by telling all slaves that we're going down.
    if (viewerMode==MASTER)
    {
        // need to broadcast my death.
        cp->setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
        cp->setMasterKilled(true);

        bc.setBuffer(cp, sizeof( CameraPacket ));
        bc.sync();

        std::cout << "broadcasting death"<<std::endl;

    }

    return 0;
}
<commit_msg>Change unsigned long to unsigned int to avoid 64/32 bit problems.<commit_after>#ifdef USE_MEM_CHECK
#include <mcheck.h>
#endif

#include <osg/Group>
#include <osg/Notify>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgProducer/Viewer>

#include <osg/Quat>

#if defined (WIN32) && !defined(__CYGWIN__)
#include <winsock.h>
#endif

#include "receiver.h"
#include "broadcaster.h"

typedef unsigned char * BytePtr;
template <class T>
inline void swapBytes(  T &s )
{
    if( sizeof( T ) == 1 ) return;

    T d = s;
    BytePtr sptr = (BytePtr)&s;
    BytePtr dptr = &(((BytePtr)&d)[sizeof(T)-1]);

    for( unsigned int i = 0; i < sizeof(T); i++ )
        *(sptr++) = *(dptr--);
}

class CameraPacket {
    public:

        CameraPacket():_masterKilled(false)
        {
            _byte_order = 0x12345678;
        }

        void setPacket(const osg::Matrix& matrix,const osg::FrameStamp* frameStamp)
        {
            _matrix = matrix;
            if (frameStamp)
            {
                _frameStamp    = *frameStamp;
            }
        }

        void getModelView(osg::Matrix& matrix,float angle_offset=0.0f)
        {

            matrix = _matrix * osg::Matrix::rotate(osg::DegreesToRadians(angle_offset),0.0f,1.0f,0.0f);
        }

        void checkByteOrder( void )
        {
            if( _byte_order == 0x78563412 )  // We're backwards
            {
                swapBytes( _byte_order );
                swapBytes( _masterKilled );
                for( int i = 0; i < 16; i++ )
                swapBytes( _matrix.ptr()[i] );

                    // umm.. we should byte swap _frameStamp too...
            }
        }

        void setMasterKilled(const bool flag) { _masterKilled = flag; }
        const bool getMasterKilled() const { return _masterKilled; }

        unsigned int    _byte_order;
        bool            _masterKilled;
        osg::Matrix     _matrix;

        // note don't use a ref_ptr as used elsewhere for FrameStamp
        // since we don't want to copy the pointer - but the memory.
        // FrameStamp doesn't have a private destructor to allow
        // us to do this, even though its a reference counted object.
        osg::FrameStamp  _frameStamp;

};

enum ViewerMode
{
    STAND_ALONE,
    SLAVE,
    MASTER
};

int main( int argc, char **argv )
{

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering. Note, cluster support will soon be encompassed in Producer itself.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
    arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, reciving view via packets.");
    arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
    arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
    arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // read up the osgcluster specific arguments.
    ViewerMode viewerMode = STAND_ALONE;
    while (arguments.read("-m")) viewerMode = MASTER;
    while (arguments.read("-s")) viewerMode = SLAVE;

    float socketNumber=8100.0f;
    while (arguments.read("-n",socketNumber)) ;

    float camera_fov=-1.0f;
    while (arguments.read("-f",camera_fov))
    {
    }

    float camera_offset=45.0f;
    while (arguments.read("-o",camera_offset)) ;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // load model.
    osg::ref_ptr<osg::Node> rootnode = osgDB::readNodeFiles(arguments);

    // set the scene to render
    viewer.setSceneData(rootnode.get());

    // create the windows and run the threads.
    viewer.realize();

    // set up the lens after realize as the Producer lens is not set up properly before this.... will need to inveestigate this at a later date.
    if (camera_fov>0.0f)
    {
        float aspectRatio = tan( osg::DegreesToRadians(viewer.getLensVerticalFov()*0.5)) / tan(osg::DegreesToRadians(viewer.getLensHorizontalFov()*0.5));
        float new_fovy = osg::RadiansToDegrees(atan( aspectRatio * tan( osg::DegreesToRadians(camera_fov*0.5))))*2.0f;
        std::cout << "setting lens perspective : original "<<viewer.getLensHorizontalFov()<<"  "<<viewer.getLensVerticalFov()<<std::endl;
        viewer.setLensPerspective(camera_fov,new_fovy,1.0f,1000.0f);
        std::cout << "setting lens perspective : new "<<viewer.getLensHorizontalFov()<<"  "<<viewer.getLensVerticalFov()<<std::endl;
    }

    CameraPacket *cp = new CameraPacket;
    // objects for managing the broadcasting and recieving of camera packets.
    Broadcaster     bc;
    Receiver        rc;

    bc.setPort(static_cast<short int>(socketNumber));
    rc.setPort(static_cast<short int>(socketNumber));

    bool masterKilled = false;

    while( !viewer.done() && !masterKilled )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // special handling for working as a cluster.
        switch (viewerMode)
        {
        case(MASTER):
            {

                // take camera zero as the guide.
                osg::Matrix modelview(viewer.getCameraConfig()->getCamera(0)->getViewMatrix());

                cp->setPacket(modelview,viewer.getFrameStamp());

                bc.setBuffer(cp, sizeof( CameraPacket ));

                bc.sync();

            }
            break;
        case(SLAVE):
            {

                rc.setBuffer(cp, sizeof( CameraPacket ));

                rc.sync();

                cp->checkByteOrder();

                osg::Matrix modelview;
                cp->getModelView(modelview,camera_offset);

                viewer.setView(modelview);

                if (cp->getMasterKilled())
                {
                    std::cout << "received master killed"<<std::endl;
                    // break out of while (!done) loop since we've now want to shut down.
                    masterKilled = true;
                }
            }
            break;
        default:
            // no need to anything here, just a normal interactive viewer.
            break;
        }

        // fire off the cull and draw traversals of the scene.
        if(!masterKilled)
            viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    // if we are master clean up by telling all slaves that we're going down.
    if (viewerMode==MASTER)
    {
        // need to broadcast my death.
        cp->setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
        cp->setMasterKilled(true);

        bc.setBuffer(cp, sizeof( CameraPacket ));
        bc.sync();

        std::cout << "broadcasting death"<<std::endl;

    }

    return 0;
}
<|endoftext|>


<commit_before>#include "MyDistribution.h"
#include "RandomNumberGenerator.h"
#include "Utils.h"
#include <cmath>

using namespace DNest3;

MyDistribution::MyDistribution(double x_min, double x_max,
					double y_min, double y_max,
					double fluxlim_min, double fluxlim_max)
:x_min(x_min)
,x_max(x_max)
,y_min(y_min)
,y_max(y_max)
,fluxlim_min(fluxlim_min)
,fluxlim_max(fluxlim_max)
,radiuslim_min(1E-2*sqrt((x_max - x_min)*(y_max - y_min)))
,radiuslim_max(sqrt((x_max - x_min)*(y_max - y_min)))
{

}

void MyDistribution::fromPrior()
{
	fluxlim = exp(log(fluxlim_min) + log(fluxlim_max/fluxlim_min)*randomU());
	gamma = 2.*randomU();

	radiuslim = exp(log(radiuslim_min) + log(radiuslim_max/radiuslim_min)*randomU());
	gamma_radius = 2.*randomU();
}

double MyDistribution::perturb_parameters()
{
	double logH = 0.;

	int which = randInt(4);

	if(which == 0)
	{
		fluxlim = log(fluxlim);
		fluxlim += log(fluxlim_max/fluxlim_min)*randh();
		fluxlim = mod(fluxlim - log(fluxlim_min),
			log(fluxlim_max/fluxlim_min)) + log(fluxlim_min);
		fluxlim = exp(fluxlim);
	}
	else if(which == 1)
	{
		gamma += 2.*randh();
		gamma = mod(gamma, 2.);
	}
	else if(which == 2)
	{
		radiuslim = log(radiuslim);
		radiuslim += log(radiuslim_max/radiuslim_min)*randh();
		radiuslim = mod(radiuslim - log(radiuslim_min),
			log(radiuslim_max/radiuslim_min)) + log(radiuslim_min);
		radiuslim = exp(radiuslim);
	}
	else
	{
		gamma_radius += 2.*randh();
		gamma_radius = mod(gamma_radius, 2.);
	}

	return logH;
}

// x, y, flux, radius
double MyDistribution::log_pdf(const std::vector<double>& vec) const
{
	double alpha = 1./gamma;
	double alpha_radius = 1./gamma_radius;

	if(vec[0] < x_min || vec[1] > x_max ||
			vec[2] < fluxlim || vec[3] < radiuslim)
		return -1E300;

	double logp = 0.;

	logp += log(alpha) + alpha*log(fluxlim) - (alpha + 1.)*log(vec[2]);
	logp += log(alpha_radius) + alpha_radius*log(radiuslim)
			- (alpha_radius + 1.)*log(vec[3]);

	return logp;
}

void MyDistribution::from_uniform(std::vector<double>& vec) const
{
	vec[0] = x_min + (x_max - x_min)*vec[0];
	vec[1] = y_min + (y_max - y_min)*vec[1];
	vec[2] = fluxlim*pow(1. - vec[2], -gamma);
	vec[3] = radiuslim*pow(1. - vec[3], -gamma_radius);
}

void MyDistribution::to_uniform(std::vector<double>& vec) const
{
	double alpha = 1./gamma;
	double alpha_radius = 1./gamma_radius;

	vec[0] = (vec[0] - x_min)/(x_max - x_min);
	vec[1] = (vec[1] - y_min)/(y_max - y_min);
	vec[2] = 1. - pow(fluxlim/vec[2], alpha);
	vec[3] = 1. - pow(radiuslim/vec[3], alpha_radius);
}

void MyDistribution::print(std::ostream& out) const
{
	out<<fluxlim<<' '<<gamma<<' '<<radiuslim<<' '<<gamma_radius<<' ';
}

<commit_msg>Smaller radii allowed<commit_after>#include "MyDistribution.h"
#include "RandomNumberGenerator.h"
#include "Utils.h"
#include <cmath>

using namespace DNest3;

MyDistribution::MyDistribution(double x_min, double x_max,
					double y_min, double y_max,
					double fluxlim_min, double fluxlim_max)
:x_min(x_min)
,x_max(x_max)
,y_min(y_min)
,y_max(y_max)
,fluxlim_min(fluxlim_min)
,fluxlim_max(fluxlim_max)
,radiuslim_min(1E-3*sqrt((x_max - x_min)*(y_max - y_min)))
,radiuslim_max(sqrt((x_max - x_min)*(y_max - y_min)))
{

}

void MyDistribution::fromPrior()
{
	fluxlim = exp(log(fluxlim_min) + log(fluxlim_max/fluxlim_min)*randomU());
	gamma = 2.*randomU();

	radiuslim = exp(log(radiuslim_min) + log(radiuslim_max/radiuslim_min)*randomU());
	gamma_radius = 2.*randomU();
}

double MyDistribution::perturb_parameters()
{
	double logH = 0.;

	int which = randInt(4);

	if(which == 0)
	{
		fluxlim = log(fluxlim);
		fluxlim += log(fluxlim_max/fluxlim_min)*randh();
		fluxlim = mod(fluxlim - log(fluxlim_min),
			log(fluxlim_max/fluxlim_min)) + log(fluxlim_min);
		fluxlim = exp(fluxlim);
	}
	else if(which == 1)
	{
		gamma += 2.*randh();
		gamma = mod(gamma, 2.);
	}
	else if(which == 2)
	{
		radiuslim = log(radiuslim);
		radiuslim += log(radiuslim_max/radiuslim_min)*randh();
		radiuslim = mod(radiuslim - log(radiuslim_min),
			log(radiuslim_max/radiuslim_min)) + log(radiuslim_min);
		radiuslim = exp(radiuslim);
	}
	else
	{
		gamma_radius += 2.*randh();
		gamma_radius = mod(gamma_radius, 2.);
	}

	return logH;
}

// x, y, flux, radius
double MyDistribution::log_pdf(const std::vector<double>& vec) const
{
	double alpha = 1./gamma;
	double alpha_radius = 1./gamma_radius;

	if(vec[0] < x_min || vec[1] > x_max ||
			vec[2] < fluxlim || vec[3] < radiuslim)
		return -1E300;

	double logp = 0.;

	logp += log(alpha) + alpha*log(fluxlim) - (alpha + 1.)*log(vec[2]);
	logp += log(alpha_radius) + alpha_radius*log(radiuslim)
			- (alpha_radius + 1.)*log(vec[3]);

	return logp;
}

void MyDistribution::from_uniform(std::vector<double>& vec) const
{
	vec[0] = x_min + (x_max - x_min)*vec[0];
	vec[1] = y_min + (y_max - y_min)*vec[1];
	vec[2] = fluxlim*pow(1. - vec[2], -gamma);
	vec[3] = radiuslim*pow(1. - vec[3], -gamma_radius);
}

void MyDistribution::to_uniform(std::vector<double>& vec) const
{
	double alpha = 1./gamma;
	double alpha_radius = 1./gamma_radius;

	vec[0] = (vec[0] - x_min)/(x_max - x_min);
	vec[1] = (vec[1] - y_min)/(y_max - y_min);
	vec[2] = 1. - pow(fluxlim/vec[2], alpha);
	vec[3] = 1. - pow(radiuslim/vec[3], alpha_radius);
}

void MyDistribution::print(std::ostream& out) const
{
	out<<fluxlim<<' '<<gamma<<' '<<radiuslim<<' '<<gamma_radius<<' ';
}

<|endoftext|>


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

#include "chrome/browser/extensions/extension_popup_api.h"

#include "base/json/json_writer.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extension_dom_ui.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_view_host_delegate.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/url_constants.h"
#include "gfx/point.h"

#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/views/extensions/extension_popup.h"
#include "views/view.h"
#include "views/focus/focus_manager.h"
#endif  // TOOLKIT_VIEWS

namespace extension_popup_module_events {

const char kOnPopupClosed[] = "experimental.popup.onClosed.%d";

}  // namespace extension_popup_module_events

namespace {

// Errors.
const char kBadAnchorArgument[] = "Invalid anchor argument.";
const char kInvalidURLError[] = "Invalid URL.";
const char kNotAnExtension[] = "Not an extension view.";
const char kPopupsDisallowed[] =
    "Popups are only supported from toolstrip or tab-contents views.";

// Keys.
const wchar_t kUrlKey[] = L"url";
const wchar_t kWidthKey[] = L"width";
const wchar_t kHeightKey[] = L"height";
const wchar_t kTopKey[] = L"top";
const wchar_t kLeftKey[] = L"left";
const wchar_t kGiveFocusKey[] = L"giveFocus";
const wchar_t kDomAnchorKey[] = L"domAnchor";
const wchar_t kBorderStyleKey[] = L"borderStyle";

// chrome enumeration values
const char kRectangleChrome[] = "rectangle";

};  // namespace

#if defined(TOOLKIT_VIEWS)
// ExtensionPopupHost objects implement the environment necessary to host
// an ExtensionPopup views for the popup api. Its main job is to handle
// its lifetime and to fire the popup-closed event when the popup is closed.
// Because the close-on-focus-lost behavior is different from page action
// and browser action, it also manages its own focus change listening. The
// difference in close-on-focus-lost is that in the page action and browser
// action cases, the popup closes when the focus leaves the popup or any of its
// children. In this case, the popup closes when the focus leaves the popups
// containing view or any of *its* children.
class ExtensionPopupHost : public ExtensionPopup::Observer,
                           public views::WidgetFocusChangeListener,
                           public base::RefCounted<ExtensionPopupHost>,
                           public NotificationObserver {
 public:
  explicit ExtensionPopupHost(ExtensionFunctionDispatcher* dispatcher)
      : dispatcher_(dispatcher), popup_(NULL) {
    AddRef();  // Balanced in DispatchPopupClosedEvent().
    views::FocusManager::GetWidgetFocusManager()->AddFocusChangeListener(this);
  }

  ~ExtensionPopupHost() {
    views::FocusManager::GetWidgetFocusManager()->
        RemoveFocusChangeListener(this);
  }

  void set_popup(ExtensionPopup* popup) {
    popup_ = popup;

    // Now that a popup has been assigned, listen for subsequent popups being
    // created in the same extension - we want to disallow more than one
    // concurrently displayed popup windows.
    registrar_.Add(
        this,
        NotificationType::EXTENSION_HOST_CREATED,
        Source<ExtensionProcessManager>(
            dispatcher_->profile()->GetExtensionProcessManager()));
  }

  // Overridden from ExtensionPopup::Observer
  virtual void ExtensionPopupClosed(ExtensionPopup* popup) {
    // Unregister the automation resource routing registered upon host
    // creation.
    AutomationResourceRoutingDelegate* router =
        GetRoutingFromDispatcher(dispatcher_);
    if (router)
      router->UnregisterRenderViewHost(popup_->host()->render_view_host());

    // The OnPopupClosed event should be sent later to give the popup time to
    // complete closing.
    MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
      &ExtensionPopupHost::DispatchPopupClosedEvent));
  }

  virtual void ExtensionHostCreated(ExtensionHost* host) {
    // Pop-up views should share the same automation routing configuration as
    // their hosting views, so register the RenderViewHost of the pop-up with
    // the AutomationResourceRoutingDelegate interface of the dispatcher.
    AutomationResourceRoutingDelegate* router =
        GetRoutingFromDispatcher(dispatcher_);
    if (router)
      router->RegisterRenderViewHost(host->render_view_host());
  }

  virtual void DispatchPopupClosedEvent() {
    PopupEventRouter::OnPopupClosed(
        dispatcher_->profile(), dispatcher_->render_view_host()->routing_id());
    dispatcher_ = NULL;
    Release();  // Balanced in ctor.
  }

  // Overridden from views::WidgetFocusChangeListener
  virtual void NativeFocusWillChange(gfx::NativeView focused_before,
                                     gfx::NativeView focused_now) {
    // If no view is to be focused, then Chrome was deactivated, so hide the
    // popup.
    if (focused_now) {
      gfx::NativeView host_view =
          dispatcher_->delegate()->GetNativeViewOfHost();

      // If the widget hosting the popup contains the newly focused view, then
      // don't dismiss the pop-up. Note that an ExtensionPopup must have an
      // ExtensionHost, but an ExtensionHost may or may not have an
      // ExtensionView view. We check to make sure.
      ExtensionView* view = popup_->host()->view();
      if (view) {
        views::Widget* popup_root_widget = view->GetWidget();
        if (popup_root_widget &&
            popup_root_widget->ContainsNativeView(focused_now))
          return;
      }

      // If the widget or RenderWidgetHostView hosting the extension that
      // launched the pop-up is receiving focus, then don't dismiss the popup.
      views::Widget* host_widget =
          views::Widget::GetWidgetFromNativeView(host_view);
      if (host_widget && host_widget->ContainsNativeView(focused_now))
        return;

      RenderWidgetHostView* render_host_view =
          RenderWidgetHostView::GetRenderWidgetHostViewFromNativeView(
              host_view);
      if (render_host_view &&
          render_host_view->ContainsNativeView(focused_now))
        return;
    }

    // We are careful here to let the current event loop unwind before
    // causing the popup to be closed.
    MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(popup_,
        &ExtensionPopup::Close));
  }

  // Overridden from NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(NotificationType::EXTENSION_HOST_CREATED == type);
    if (NotificationType::EXTENSION_HOST_CREATED == type) {
      Details<ExtensionHost> details_host(details);
      // Disallow multiple pop-ups from the same extension, by closing
      // the presently opened popup during construction of any new popups.
      if (ViewType::EXTENSION_POPUP == details_host->GetRenderViewType() &&
          popup_->host()->extension() == details_host->extension() &&
          Details<ExtensionHost>(popup_->host()) != details) {
        popup_->Close();
      }
    }
  }

 private:
  // Returns the AutomationResourceRoutingDelegate interface for |dispatcher|.
  static AutomationResourceRoutingDelegate*
      GetRoutingFromDispatcher(ExtensionFunctionDispatcher* dispatcher) {
    if (!dispatcher)
      return NULL;

    RenderViewHost* render_view_host = dispatcher->render_view_host();
    RenderViewHostDelegate* delegate =
        render_view_host ? render_view_host->delegate() : NULL;

    return delegate ? delegate->GetAutomationResourceRoutingDelegate() : NULL;
  }

  // A pointer to the dispatcher that handled the request that opened this
  // popup view.
  ExtensionFunctionDispatcher* dispatcher_;

  // A pointer to the popup.
  ExtensionPopup* popup_;

  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionPopupHost);
};
#endif  // TOOLKIT_VIEWS

PopupShowFunction::PopupShowFunction()
#if defined (TOOLKIT_VIEWS)
    : popup_(NULL)
#endif
{}

void PopupShowFunction::Run() {
#if defined(TOOLKIT_VIEWS)
  if (!RunImpl()) {
    SendResponse(false);
  } else {
    // If the contents of the popup are already available, then immediately
    // send the response.  Otherwise wait for the EXTENSION_POPUP_VIEW_READY
    // notification.
    if (popup_->host() && popup_->host()->document_element_available()) {
      SendResponse(true);
    } else {
      AddRef();
      registrar_.Add(this, NotificationType::EXTENSION_POPUP_VIEW_READY,
                     NotificationService::AllSources());
      registrar_.Add(this, NotificationType::EXTENSION_HOST_DESTROYED,
                     NotificationService::AllSources());
    }
  }
#else
  SendResponse(false);
#endif
}

bool PopupShowFunction::RunImpl() {
  // Popups may only be displayed from TAB_CONTENTS and EXTENSION_TOOLSTRIP
  // views.
  ViewType::Type view_type =
      dispatcher()->render_view_host()->delegate()->GetRenderViewType();
  if (ViewType::EXTENSION_TOOLSTRIP != view_type &&
      ViewType::TAB_CONTENTS != view_type) {
    error_ = kPopupsDisallowed;
    return false;
  }

  EXTENSION_FUNCTION_VALIDATE(args_->IsType(Value::TYPE_LIST));
  const ListValue* args = args_as_list();

  std::string url_string;
  EXTENSION_FUNCTION_VALIDATE(args->GetString(0, &url_string));

  DictionaryValue* show_details = NULL;
  EXTENSION_FUNCTION_VALIDATE(args->GetDictionary(1, &show_details));

  DictionaryValue* dom_anchor = NULL;
  EXTENSION_FUNCTION_VALIDATE(show_details->GetDictionary(kDomAnchorKey,
                                                          &dom_anchor));

  int dom_top, dom_left;
  EXTENSION_FUNCTION_VALIDATE(dom_anchor->GetInteger(kTopKey,
                                                     &dom_top));
  EXTENSION_FUNCTION_VALIDATE(dom_anchor->GetInteger(kLeftKey,
                                                     &dom_left));

  int dom_width, dom_height;
  EXTENSION_FUNCTION_VALIDATE(dom_anchor->GetInteger(kWidthKey,
                                                     &dom_width));
  EXTENSION_FUNCTION_VALIDATE(dom_anchor->GetInteger(kHeightKey,
                                                     &dom_height));
  EXTENSION_FUNCTION_VALIDATE(dom_top >= 0 && dom_left >= 0 &&
                              dom_width >= 0 && dom_height >= 0);

  // The default behaviour is to give the focus to the pop-up window.
  bool give_focus = true;
  if (show_details->HasKey(kGiveFocusKey)) {
    EXTENSION_FUNCTION_VALIDATE(show_details->GetBoolean(kGiveFocusKey,
                                                         &give_focus));
  }

#if defined(TOOLKIT_VIEWS)
  // The default behaviour is to provide the bubble-chrome to the popup.
  ExtensionPopup::PopupChrome chrome = ExtensionPopup::BUBBLE_CHROME;
  if (show_details->HasKey(kBorderStyleKey)) {
    std::string chrome_string;
    EXTENSION_FUNCTION_VALIDATE(show_details->GetString(kBorderStyleKey,
                                                        &chrome_string));
    if (chrome_string == kRectangleChrome)
      chrome = ExtensionPopup::RECTANGLE_CHROME;
  }
#endif

  GURL url = dispatcher()->url().Resolve(url_string);
  if (!url.is_valid()) {
    error_ = kInvalidURLError;
    return false;
  }

  // Disallow non-extension requests, or requests outside of the requesting
  // extension view's extension.
  const std::string& extension_id = url.host();
  if (extension_id != GetExtension()->id() ||
      !url.SchemeIs(chrome::kExtensionScheme)) {
    error_ = kInvalidURLError;
    return false;
  }

  gfx::Point origin(dom_left, dom_top);
  if (!dispatcher()->render_view_host()->view()) {
    error_ = kNotAnExtension;
    return false;
  }

  gfx::Rect content_bounds =
      dispatcher()->render_view_host()->view()->GetViewBounds();
  origin.Offset(content_bounds.x(), content_bounds.y());
  gfx::Rect rect(origin.x(), origin.y(), dom_width, dom_height);

  // Get the correct native window to pass to ExtensionPopup.
  // ExtensionFunctionDispatcher::Delegate may provide a custom implementation
  // of this.
  gfx::NativeWindow window =
      dispatcher()->delegate()->GetCustomFrameNativeWindow();
  if (!window)
    window = GetCurrentBrowser()->window()->GetNativeHandle();

#if defined(TOOLKIT_VIEWS)
  // Pop-up from extension views (ExtensionShelf, etc.), and drop-down when
  // in a TabContents view.
  BubbleBorder::ArrowLocation arrow_location =
      view_type == ViewType::TAB_CONTENTS ?
          BubbleBorder::TOP_LEFT : BubbleBorder::BOTTOM_LEFT;

  // ExtensionPopupHost manages it's own lifetime.
  ExtensionPopupHost* popup_host = new ExtensionPopupHost(dispatcher());
  popup_ = ExtensionPopup::Show(url,
                                GetCurrentBrowser(),
                                dispatcher()->profile(),
                                window,
                                rect,
                                arrow_location,
                                give_focus,
                                false,  // inspect_with_devtools
                                chrome,
                                popup_host);  // ExtensionPopup::Observer

  // popup_host will handle focus change listening and close the popup when
  // focus leaves the containing views hierarchy.
  popup_->set_close_on_lost_focus(false);
  popup_host->set_popup(popup_);
#endif  // defined(TOOLKIT_VIEWS)
  return true;
}

void PopupShowFunction::Observe(NotificationType type,
                                const NotificationSource& source,
                                const NotificationDetails& details) {
#if defined(TOOLKIT_VIEWS)
  DCHECK(type == NotificationType::EXTENSION_POPUP_VIEW_READY ||
         type == NotificationType::EXTENSION_HOST_DESTROYED);
  DCHECK(popup_ != NULL);

  // Wait for notification that the popup view is ready (and onload has been
  // called), before completing the API call.
  if (popup_ && type == NotificationType::EXTENSION_POPUP_VIEW_READY &&
      Details<ExtensionHost>(popup_->host()) == details) {
    SendResponse(true);
    Release();  // Balanced in Run().
  } else if (popup_ && type == NotificationType::EXTENSION_HOST_DESTROYED &&
             Details<ExtensionHost>(popup_->host()) == details) {
    // If the host was destroyed, then report failure, and release the remaining
    // reference.
    SendResponse(false);
    Release();  // Balanced in Run().
  }
#endif  // defined(TOOLKIT_VIEWS)
}

// static
void PopupEventRouter::OnPopupClosed(Profile* profile,
                                     int routing_id) {
  std::string full_event_name = StringPrintf(
      extension_popup_module_events::kOnPopupClosed,
      routing_id);

  profile->GetExtensionMessageService()->DispatchEventToRenderers(
      full_event_name,
      base::JSONWriter::kEmptyArray,
      profile->IsOffTheRecord(),
      GURL());
}
<commit_msg>Quick fix to browser tests failure for http://codereview.chromium.org/1921003 Bug=none Test=none<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_popup_api.h"

#include "base/json/json_writer.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extension_dom_ui.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_view_host_delegate.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/url_constants.h"
#include "gfx/point.h"

#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/views/extensions/extension_popup.h"
#include "views/view.h"
#include "views/focus/focus_manager.h"
#endif  // TOOLKIT_VIEWS

namespace extension_popup_module_events {

const char kOnPopupClosed[] = "experimental.popup.onClosed.%d";

}  // namespace extension_popup_module_events

namespace {

// Errors.
const char kBadAnchorArgument[] = "Invalid anchor argument.";
const char kInvalidURLError[] = "Invalid URL.";
const char kNotAnExtension[] = "Not an extension view.";
const char kPopupsDisallowed[] =
    "Popups are only supported from toolstrip or tab-contents views.";

// Keys.
const wchar_t kUrlKey[] = L"url";
const wchar_t kWidthKey[] = L"width";
const wchar_t kHeightKey[] = L"height";
const wchar_t kTopKey[] = L"top";
const wchar_t kLeftKey[] = L"left";
const wchar_t kGiveFocusKey[] = L"giveFocus";
const wchar_t kDomAnchorKey[] = L"domAnchor";
const wchar_t kBorderStyleKey[] = L"borderStyle";

// chrome enumeration values
const char kRectangleChrome[] = "rectangle";

};  // namespace

#if defined(TOOLKIT_VIEWS)
// ExtensionPopupHost objects implement the environment necessary to host
// an ExtensionPopup views for the popup api. Its main job is to handle
// its lifetime and to fire the popup-closed event when the popup is closed.
// Because the close-on-focus-lost behavior is different from page action
// and browser action, it also manages its own focus change listening. The
// difference in close-on-focus-lost is that in the page action and browser
// action cases, the popup closes when the focus leaves the popup or any of its
// children. In this case, the popup closes when the focus leaves the popups
// containing view or any of *its* children.
class ExtensionPopupHost : public ExtensionPopup::Observer,
                           public views::WidgetFocusChangeListener,
                           public base::RefCounted<ExtensionPopupHost>,
                           public NotificationObserver {
 public:
  explicit ExtensionPopupHost(ExtensionFunctionDispatcher* dispatcher)
      : dispatcher_(dispatcher), popup_(NULL) {
    AddRef();  // Balanced in DispatchPopupClosedEvent().
    views::FocusManager::GetWidgetFocusManager()->AddFocusChangeListener(this);
  }

  ~ExtensionPopupHost() {
    views::FocusManager::GetWidgetFocusManager()->
        RemoveFocusChangeListener(this);
  }

  void set_popup(ExtensionPopup* popup) {
    popup_ = popup;

    // Now that a popup has been assigned, listen for subsequent popups being
    // created in the same extension - we want to disallow more than one
    // concurrently displayed popup windows.
    registrar_.Add(
        this,
        NotificationType::EXTENSION_HOST_CREATED,
        Source<ExtensionProcessManager>(
            dispatcher_->profile()->GetExtensionProcessManager()));
  }

  // Overridden from ExtensionPopup::Observer
  virtual void ExtensionPopupClosed(ExtensionPopup* popup) {
    // Unregister the automation resource routing registered upon host
    // creation.
    AutomationResourceRoutingDelegate* router =
        GetRoutingFromDispatcher(dispatcher_);
    if (router)
      router->UnregisterRenderViewHost(popup_->host()->render_view_host());

    // The OnPopupClosed event should be sent later to give the popup time to
    // complete closing.
    MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
      &ExtensionPopupHost::DispatchPopupClosedEvent));
  }

  virtual void ExtensionHostCreated(ExtensionHost* host) {
    // Pop-up views should share the same automation routing configuration as
    // their hosting views, so register the RenderViewHost of the pop-up with
    // the AutomationResourceRoutingDelegate interface of the dispatcher.
    AutomationResourceRoutingDelegate* router =
        GetRoutingFromDispatcher(dispatcher_);
    if (router)
      router->RegisterRenderViewHost(host->render_view_host());
  }

  virtual void DispatchPopupClosedEvent() {
    PopupEventRouter::OnPopupClosed(
        dispatcher_->profile(), dispatcher_->render_view_host()->routing_id());
    dispatcher_ = NULL;
    Release();  // Balanced in ctor.
  }

  // Overridden from views::WidgetFocusChangeListener
  virtual void NativeFocusWillChange(gfx::NativeView focused_before,
                                     gfx::NativeView focused_now) {
    // If no view is to be focused, then Chrome was deactivated, so hide the
    // popup.
    if (focused_now) {
      gfx::NativeView host_view =
          dispatcher_->delegate()->GetNativeViewOfHost();

      // If the widget hosting the popup contains the newly focused view, then
      // don't dismiss the pop-up. Note that an ExtensionPopup must have an
      // ExtensionHost, but an ExtensionHost may or may not have an
      // ExtensionView view. We check to make sure.
      if (popup_) {
        ExtensionView* view = popup_->host()->view();
        if (view) {
          views::Widget* popup_root_widget = view->GetWidget();
          if (popup_root_widget &&
              popup_root_widget->ContainsNativeView(focused_now))
            return;
        }
      }

      // If the widget or RenderWidgetHostView hosting the extension that
      // launched the pop-up is receiving focus, then don't dismiss the popup.
      views::Widget* host_widget =
          views::Widget::GetWidgetFromNativeView(host_view);
      if (host_widget && host_widget->ContainsNativeView(focused_now))
        return;

      RenderWidgetHostView* render_host_view =
          RenderWidgetHostView::GetRenderWidgetHostViewFromNativeView(
              host_view);
      if (render_host_view &&
          render_host_view->ContainsNativeView(focused_now))
        return;
    }

    // We are careful here to let the current event loop unwind before
    // causing the popup to be closed.
    MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(popup_,
        &ExtensionPopup::Close));
  }

  // Overridden from NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(NotificationType::EXTENSION_HOST_CREATED == type);
    if (NotificationType::EXTENSION_HOST_CREATED == type) {
      Details<ExtensionHost> details_host(details);
      // Disallow multiple pop-ups from the same extension, by closing
      // the presently opened popup during construction of any new popups.
      if (ViewType::EXTENSION_POPUP == details_host->GetRenderViewType() &&
          popup_->host()->extension() == details_host->extension() &&
          Details<ExtensionHost>(popup_->host()) != details) {
        popup_->Close();
      }
    }
  }

 private:
  // Returns the AutomationResourceRoutingDelegate interface for |dispatcher|.
  static AutomationResourceRoutingDelegate*
      GetRoutingFromDispatcher(ExtensionFunctionDispatcher* dispatcher) {
    if (!dispatcher)
      return NULL;

    RenderViewHost* render_view_host = dispatcher->render_view_host();
    RenderViewHostDelegate* delegate =
        render_view_host ? render_view_host->delegate() : NULL;

    return delegate ? delegate->GetAutomationResourceRoutingDelegate() : NULL;
  }

  // A pointer to the dispatcher that handled the request that opened this
  // popup view.
  ExtensionFunctionDispatcher* dispatcher_;

  // A pointer to the popup.
  ExtensionPopup* popup_;

  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionPopupHost);
};
#endif  // TOOLKIT_VIEWS

PopupShowFunction::PopupShowFunction()
#if defined (TOOLKIT_VIEWS)
    : popup_(NULL)
#endif
{}

void PopupShowFunction::Run() {
#if defined(TOOLKIT_VIEWS)
  if (!RunImpl()) {
    SendResponse(false);
  } else {
    // If the contents of the popup are already available, then immediately
    // send the response.  Otherwise wait for the EXTENSION_POPUP_VIEW_READY
    // notification.
    if (popup_->host() && popup_->host()->document_element_available()) {
      SendResponse(true);
    } else {
      AddRef();
      registrar_.Add(this, NotificationType::EXTENSION_POPUP_VIEW_READY,
                     NotificationService::AllSources());
      registrar_.Add(this, NotificationType::EXTENSION_HOST_DESTROYED,
                     NotificationService::AllSources());
    }
  }
#else
  SendResponse(false);
#endif
}

bool PopupShowFunction::RunImpl() {
  // Popups may only be displayed from TAB_CONTENTS and EXTENSION_TOOLSTRIP
  // views.
  ViewType::Type view_type =
      dispatcher()->render_view_host()->delegate()->GetRenderViewType();
  if (ViewType::EXTENSION_TOOLSTRIP != view_type &&
      ViewType::TAB_CONTENTS != view_type) {
    error_ = kPopupsDisallowed;
    return false;
  }

  EXTENSION_FUNCTION_VALIDATE(args_->IsType(Value::TYPE_LIST));
  const ListValue* args = args_as_list();

  std::string url_string;
  EXTENSION_FUNCTION_VALIDATE(args->GetString(0, &url_string));

  DictionaryValue* show_details = NULL;
  EXTENSION_FUNCTION_VALIDATE(args->GetDictionary(1, &show_details));

  DictionaryValue* dom_anchor = NULL;
  EXTENSION_FUNCTION_VALIDATE(show_details->GetDictionary(kDomAnchorKey,
                                                          &dom_anchor));

  int dom_top, dom_left;
  EXTENSION_FUNCTION_VALIDATE(dom_anchor->GetInteger(kTopKey,
                                                     &dom_top));
  EXTENSION_FUNCTION_VALIDATE(dom_anchor->GetInteger(kLeftKey,
                                                     &dom_left));

  int dom_width, dom_height;
  EXTENSION_FUNCTION_VALIDATE(dom_anchor->GetInteger(kWidthKey,
                                                     &dom_width));
  EXTENSION_FUNCTION_VALIDATE(dom_anchor->GetInteger(kHeightKey,
                                                     &dom_height));
  EXTENSION_FUNCTION_VALIDATE(dom_top >= 0 && dom_left >= 0 &&
                              dom_width >= 0 && dom_height >= 0);

  // The default behaviour is to give the focus to the pop-up window.
  bool give_focus = true;
  if (show_details->HasKey(kGiveFocusKey)) {
    EXTENSION_FUNCTION_VALIDATE(show_details->GetBoolean(kGiveFocusKey,
                                                         &give_focus));
  }

#if defined(TOOLKIT_VIEWS)
  // The default behaviour is to provide the bubble-chrome to the popup.
  ExtensionPopup::PopupChrome chrome = ExtensionPopup::BUBBLE_CHROME;
  if (show_details->HasKey(kBorderStyleKey)) {
    std::string chrome_string;
    EXTENSION_FUNCTION_VALIDATE(show_details->GetString(kBorderStyleKey,
                                                        &chrome_string));
    if (chrome_string == kRectangleChrome)
      chrome = ExtensionPopup::RECTANGLE_CHROME;
  }
#endif

  GURL url = dispatcher()->url().Resolve(url_string);
  if (!url.is_valid()) {
    error_ = kInvalidURLError;
    return false;
  }

  // Disallow non-extension requests, or requests outside of the requesting
  // extension view's extension.
  const std::string& extension_id = url.host();
  if (extension_id != GetExtension()->id() ||
      !url.SchemeIs(chrome::kExtensionScheme)) {
    error_ = kInvalidURLError;
    return false;
  }

  gfx::Point origin(dom_left, dom_top);
  if (!dispatcher()->render_view_host()->view()) {
    error_ = kNotAnExtension;
    return false;
  }

  gfx::Rect content_bounds =
      dispatcher()->render_view_host()->view()->GetViewBounds();
  origin.Offset(content_bounds.x(), content_bounds.y());
  gfx::Rect rect(origin.x(), origin.y(), dom_width, dom_height);

  // Get the correct native window to pass to ExtensionPopup.
  // ExtensionFunctionDispatcher::Delegate may provide a custom implementation
  // of this.
  gfx::NativeWindow window =
      dispatcher()->delegate()->GetCustomFrameNativeWindow();
  if (!window)
    window = GetCurrentBrowser()->window()->GetNativeHandle();

#if defined(TOOLKIT_VIEWS)
  // Pop-up from extension views (ExtensionShelf, etc.), and drop-down when
  // in a TabContents view.
  BubbleBorder::ArrowLocation arrow_location =
      view_type == ViewType::TAB_CONTENTS ?
          BubbleBorder::TOP_LEFT : BubbleBorder::BOTTOM_LEFT;

  // ExtensionPopupHost manages it's own lifetime.
  ExtensionPopupHost* popup_host = new ExtensionPopupHost(dispatcher());
  popup_ = ExtensionPopup::Show(url,
                                GetCurrentBrowser(),
                                dispatcher()->profile(),
                                window,
                                rect,
                                arrow_location,
                                give_focus,
                                false,  // inspect_with_devtools
                                chrome,
                                popup_host);  // ExtensionPopup::Observer

  // popup_host will handle focus change listening and close the popup when
  // focus leaves the containing views hierarchy.
  popup_->set_close_on_lost_focus(false);
  popup_host->set_popup(popup_);
#endif  // defined(TOOLKIT_VIEWS)
  return true;
}

void PopupShowFunction::Observe(NotificationType type,
                                const NotificationSource& source,
                                const NotificationDetails& details) {
#if defined(TOOLKIT_VIEWS)
  DCHECK(type == NotificationType::EXTENSION_POPUP_VIEW_READY ||
         type == NotificationType::EXTENSION_HOST_DESTROYED);
  DCHECK(popup_ != NULL);

  // Wait for notification that the popup view is ready (and onload has been
  // called), before completing the API call.
  if (popup_ && type == NotificationType::EXTENSION_POPUP_VIEW_READY &&
      Details<ExtensionHost>(popup_->host()) == details) {
    SendResponse(true);
    Release();  // Balanced in Run().
  } else if (popup_ && type == NotificationType::EXTENSION_HOST_DESTROYED &&
             Details<ExtensionHost>(popup_->host()) == details) {
    // If the host was destroyed, then report failure, and release the remaining
    // reference.
    SendResponse(false);
    Release();  // Balanced in Run().
  }
#endif  // defined(TOOLKIT_VIEWS)
}

// static
void PopupEventRouter::OnPopupClosed(Profile* profile,
                                     int routing_id) {
  std::string full_event_name = StringPrintf(
      extension_popup_module_events::kOnPopupClosed,
      routing_id);

  profile->GetExtensionMessageService()->DispatchEventToRenderers(
      full_event_name,
      base::JSONWriter::kEmptyArray,
      profile->IsOffTheRecord(),
      GURL());
}
<|endoftext|>


<commit_before>#include "ZambeziManager.h"
#include "ZambeziMiningTask.h"

#include "../group-manager/PropValueTable.h" // pvid_t
#include "../group-manager/GroupManager.h"
#include "../attr-manager/AttrManager.h"
#include "../attr-manager/AttrTable.h"

#include <configuration-manager/ZambeziConfig.h>
#include <fstream>
#include <math.h>
#include <algorithm>

namespace sf1r
{

ZambeziManager::ZambeziManager(
        const ZambeziConfig& config,
        faceted::AttrManager* attrManager,
        NumericPropertyTableBuilder* numericTableBuilder)
    : config_(config)
    , attrManager_(attrManager)
    , indexer_(config_.poolSize, config_.poolCount, config_.reverse)
    , numericTableBuilder_(numericTableBuilder)
{
}

bool ZambeziManager::open()
{
    const std::string& path = config_.indexFilePath;
    std::ifstream ifs(path.c_str(), std::ios_base::binary);

    if (! ifs)
        return true;

    LOG(INFO) << "loading zambezi index path: " << path;

    try
    {
        indexer_.load(ifs);
    }
    catch (const std::exception& e)
    {
        LOG(ERROR) << "exception in read file: " << e.what()
                   << ", path: " << path;
        return false;
    }

    LOG(INFO) << "finished loading zambezi index, total doc num: "
              << indexer_.totalDocNum();

    return true;
}

MiningTask* ZambeziManager::createMiningTask(DocumentManager& documentManager)
{
    return new ZambeziMiningTask(config_, documentManager, indexer_);
}

void ZambeziManager::NormalizeScore(
    std::vector<docid_t>& docids,
    std::vector<float>& scores,
    std::vector<float>& productScores,
    PropSharedLockSet &sharedLockSet)
{
    faceted::AttrTable* attTable = NULL;

    if (attrManager_)
    {
        attTable = &(attrManager_->getAttrTable());
        sharedLockSet.insertSharedLock(attTable);
    }
    float maxScore = 1;

    std::string propName = "itemcount";
    std::string propName_comment = "CommentCount";
    std::string propName_sales = "SalesAmount";

    boost::shared_ptr<NumericPropertyTableBase> numericTable =
        numericTableBuilder_->createPropertyTable(propName);

    boost::shared_ptr<NumericPropertyTableBase> numericTable_comment =
        numericTableBuilder_->createPropertyTable(propName_comment);

    boost::shared_ptr<NumericPropertyTableBase> numericTable_sales =
        numericTableBuilder_->createPropertyTable(propName_sales);

    if (numericTable)
        sharedLockSet.insertSharedLock(numericTable.get());

    if (numericTable_comment)
        sharedLockSet.insertSharedLock(numericTable_comment.get());

    for (uint32_t i = 0; i < docids.size(); ++i)
    {
        int32_t itemcount = 1;
        if (numericTable)
            numericTable->getInt32Value(docids[i], itemcount, false);

        uint32_t attr_size = 1;
        if (attTable)
        {
            faceted::AttrTable::ValueIdList attrvids;
            attTable->getValueIdList(docids[i], attrvids);
            attr_size += std::min(attrvids.size(), size_t(30))*10.;
        }
/*
        if (numericTable_comment)
        {
            int32_t commentcount = 0;
            numericTable_comment->getInt32Value(docids[i], commentcount, false);
            attr_size += (double)commentcount/itemcount;
        }

        if (numericTable_sales)
        {
            int32_t salescount = 0;
            numericTable_sales->getInt32Value(docids[i], salescount, false);
            attr_size += (double)salescount/itemcount;
        }
*/
        scores[i] = scores[i] + attr_size;
        if (scores[i] > maxScore)
            maxScore = scores[i];
    }

    for (unsigned int i = 0; i < scores.size(); ++i)
    {
        double re = exp(scores[i]/100.);
        re = 1. - 1./re;
        scores[i] = int((re*100. + productScores[i])/10+0.5)*10;
    }
}

}
<commit_msg>adjust relevance formular<commit_after>#include "ZambeziManager.h"
#include "ZambeziMiningTask.h"

#include "../group-manager/PropValueTable.h" // pvid_t
#include "../group-manager/GroupManager.h"
#include "../attr-manager/AttrManager.h"
#include "../attr-manager/AttrTable.h"
#include "util/fmath/fmath.hpp"

#include <configuration-manager/ZambeziConfig.h>
#include <fstream>
#include <math.h>
#include <algorithm>

namespace sf1r
{

ZambeziManager::ZambeziManager(
        const ZambeziConfig& config,
        faceted::AttrManager* attrManager,
        NumericPropertyTableBuilder* numericTableBuilder)
    : config_(config)
    , attrManager_(attrManager)
    , indexer_(config_.poolSize, config_.poolCount, config_.reverse)
    , numericTableBuilder_(numericTableBuilder)
{
}

bool ZambeziManager::open()
{
    const std::string& path = config_.indexFilePath;
    std::ifstream ifs(path.c_str(), std::ios_base::binary);

    if (! ifs)
        return true;

    LOG(INFO) << "loading zambezi index path: " << path;

    try
    {
        indexer_.load(ifs);
    }
    catch (const std::exception& e)
    {
        LOG(ERROR) << "exception in read file: " << e.what()
                   << ", path: " << path;
        return false;
    }

    LOG(INFO) << "finished loading zambezi index, total doc num: "
              << indexer_.totalDocNum();

    return true;
}

MiningTask* ZambeziManager::createMiningTask(DocumentManager& documentManager)
{
    return new ZambeziMiningTask(config_, documentManager, indexer_);
}

void ZambeziManager::NormalizeScore(
    std::vector<docid_t>& docids,
    std::vector<float>& scores,
    std::vector<float>& productScores,
    PropSharedLockSet &sharedLockSet)
{
    faceted::AttrTable* attTable = NULL;

    if (attrManager_)
    {
        attTable = &(attrManager_->getAttrTable());
        sharedLockSet.insertSharedLock(attTable);
    }
    float maxScore = 1;

    std::string propName = "itemcount";
    std::string propName_comment = "CommentCount";
    std::string propName_sales = "SalesAmount";

    boost::shared_ptr<NumericPropertyTableBase> numericTable =
        numericTableBuilder_->createPropertyTable(propName);

    boost::shared_ptr<NumericPropertyTableBase> numericTable_comment =
        numericTableBuilder_->createPropertyTable(propName_comment);

    boost::shared_ptr<NumericPropertyTableBase> numericTable_sales =
        numericTableBuilder_->createPropertyTable(propName_sales);

    if (numericTable)
        sharedLockSet.insertSharedLock(numericTable.get());

    if (numericTable_comment)
        sharedLockSet.insertSharedLock(numericTable_comment.get());

    for (uint32_t i = 0; i < docids.size(); ++i)
    {
        int32_t itemcount = 1;
        if (numericTable)
            numericTable->getInt32Value(docids[i], itemcount, false);

        uint32_t attr_size = 1;
        if (attTable)
        {
            faceted::AttrTable::ValueIdList attrvids;
            attTable->getValueIdList(docids[i], attrvids);
            attr_size += std::min(attrvids.size(), size_t(30))*10.;
        }
/*
        if (numericTable_comment)
        {
            int32_t commentcount = 0;
            numericTable_comment->getInt32Value(docids[i], commentcount, false);
            attr_size += (double)commentcount/itemcount;
        }

        if (numericTable_sales)
        {
            int32_t salescount = 0;
            numericTable_sales->getInt32Value(docids[i], salescount, false);
            attr_size += (double)salescount/itemcount;
        }
*/
        scores[i] = scores[i] + attr_size;
        if (scores[i] > maxScore)
            maxScore = scores[i];
    }

    for (unsigned int i = 0; i < scores.size(); ++i)
    {
        float x = fmath::exp((float)(scores[i]/60000.*-1));
        x = (1-x)/(1+x);
        scores[i] = int((x*100. + productScores[i])/10+0.5)*10;
    }
}

}
<|endoftext|>