text:
//=============================================================================
//
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//
//=============================================================================

#include <remus/worker/detail/MessageRouter.h>

#include <remus/common/SleepFor.h>
#include <remus/proto/Message.h>
#include <remus/proto/Response.h>
#include <remus/worker/detail/JobQueue.h>

#include <remus/proto/zmq.hpp>

#include <remus/testing/Testing.h>

REMUS_THIRDPARTY_PRE_INCLUDE
#include <boost/uuid/uuid.hpp>
REMUS_THIRDPARTY_POST_INCLUDE

using namespace remus::worker::detail;

namespace {

//------------------------------------------------------------------------------
void verify_basic_comms(zmq::context_t& context)
{
  zmq::socketInfo<zmq::proto::inproc> queue_channel(
                                                remus::testing::UniqueString());
  JobQueue jq(context,queue_channel); //bind the jobqueue to the worker channel

  //we need to pause for some time to all the JobQueue
  //to properly bind to the socket before we connect
  while(!jq.isReady())
    { remus::common::SleepForMillisec(10); }

  //create the socket to send info to the job queue
  zmq::socket_t jobSocket(context,ZMQ_PAIR);
  jobSocket.connect(queue_channel.endpoint().c_str());

  zmq::SocketIdentity sid;

  boost::uuids::uuid jobId = remus::testing::UUIDGenerator();
  remus::worker::Job fakeJob(jobId,
                             remus::proto::JobSubmission());

  {
  remus::proto::Response r =
      remus::proto::send_NonBlockingResponse(remus::MAKE_MESH,
                                             remus::worker::to_string(fakeJob),
                                             &jobSocket,
                                             sid);
  REMUS_ASSERT( (r.isValid()) );
  }

  while(jq.size()<1){}
  REMUS_ASSERT( (jq.size()>0) );
  REMUS_ASSERT( (jq.size()==1) );

  //now add multiple more jobs to the queue
  remus::proto::JobRequirements reqs(
          remus::common::ContentFormat::User,
          remus::common::MeshIOType( (remus::meshtypes::Mesh2D()),
                                     (remus::meshtypes::Mesh2D()) ),
          std::string(),
          std::string()
          );
  remus::proto::JobSubmission sub(reqs);

  remus::worker::Job fakeJob2(remus::testing::UUIDGenerator(), sub);
  remus::worker::Job fakeJob3(remus::testing::UUIDGenerator(), sub);

  {
  remus::proto::Response r =
      remus::proto::send_NonBlockingResponse(remus::MAKE_MESH,
                                             remus::worker::to_string(fakeJob2),
                                             &jobSocket,
                                             sid);
  REMUS_ASSERT( (r.isValid()) );
  }

  {
  remus::proto::Response r =
      remus::proto::send_NonBlockingResponse(remus::MAKE_MESH,
                                            remus::worker::to_string(fakeJob3),
                                            &jobSocket,
                                            sid);
  REMUS_ASSERT( (r.isValid()) );
  }

  //now send a terminate job command for the first job
  //and verify that the correct job was terminated by pulling
  //all the jobs off the stack
  {
  remus::worker::Job terminateJob(jobId,
                                  remus::proto::JobSubmission());
  remus::proto::Response r =
      remus::proto::send_NonBlockingResponse(remus::TERMINATE_JOB,
                                             remus::worker::to_string(terminateJob),
                                             &jobSocket,
                                             sid);
  REMUS_ASSERT( (r.isValid()) );
  }

  //gotta wait for all three messages to come in
  remus::common::SleepForMillisec(2000);

  REMUS_ASSERT( (jq.isATerminatedJob( fakeJob ) ==true ))
  REMUS_ASSERT( (jq.isATerminatedJob( fakeJob2 ) ==false ))
  REMUS_ASSERT( (jq.isATerminatedJob( fakeJob3) ==false ))

  while(jq.size()>0)
    {
    remus::worker::Job j = jq.take();
    REMUS_ASSERT( (j.valid() == true) )
    }
}

//------------------------------------------------------------------------------
void verify_term(zmq::context_t& context)
{
  zmq::socketInfo<zmq::proto::inproc> queue_channel(
                                                remus::testing::UniqueString());
  JobQueue jq(context,queue_channel); //bind the jobqueue to the worker channel

  //we need to pause for some time to all the JobQueue
  //to properly bind to the socket before we connect
  while(!jq.isReady())
    { remus::common::SleepForMillisec(10); }

  //create the socket to send info to the job queue
  zmq::socket_t jobSocket(context,ZMQ_PAIR);
  jobSocket.connect(queue_channel.endpoint().c_str());

  REMUS_ASSERT( (jq.size() == 0) );

  //now send it a terminate message over the worker channel
  remus::worker::Job terminateJob;
  remus::proto::Response r=
      remus::proto::send_NonBlockingResponse(remus::TERMINATE_WORKER,
                                             remus::worker::to_string(terminateJob),
                                             &jobSocket,
                                             (zmq::SocketIdentity()));
  REMUS_ASSERT( (r.isValid()) );

  //cheap block while we wait for the router thread to get the message
  while(jq.size()<1){}

  REMUS_ASSERT( (jq.size() == 1) )
  remus::worker::Job invalid_job = jq.take();
  REMUS_ASSERT( (!invalid_job.valid()) )
  REMUS_ASSERT( (invalid_job.validityReason() ==
                 remus::worker::Job::TERMINATE_WORKER) )

}

}

int UnitTestWorkerJobQueue(int, char *[])
{
  zmq::context_t context(1);

  verify_basic_comms(context);
  verify_term(context);

  return 0;
}

ext: cxx

max_stars_repo_name: robertmaynard/Remus

max_issues_repo_name: robertmaynard/Remus

max_forks_repo_name: Kitware/Remus


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_DSL_FUNCTIONS_SCHEDULE_HPP_INCLUDED
#define BOOST_SIMD_DSL_FUNCTIONS_SCHEDULE_HPP_INCLUDED

#include <boost/simd/include/functor.hpp>

namespace boost { namespace simd
{
  namespace tag
  {
    struct schedule_;
    struct schedule_assign_;
  }
  namespace ext
  {
    template<class Site, class... Ts>
    BOOST_FORCEINLINE generic_dispatcher<tag::schedule_, Site> dispatching_schedule_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
    {
      return generic_dispatcher<tag::schedule_, Site>();
    }
    template<class... Args>
    struct impl_schedule_;

    template<class Site, class... Ts>
    BOOST_FORCEINLINE generic_dispatcher<tag::schedule_assign_, Site> dispatching_schedule_assign_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
    {
      return generic_dispatcher<tag::schedule_assign_, Site>();
    }
    template<class... Args>
    struct impl_schedule_assign_;
  }
  namespace tag
  {
    struct schedule_ : ext::abstract_<schedule_>
    {
      typedef ext::abstract_<schedule_> parent;

      template<class... Args>
      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
      BOOST_AUTO_DECLTYPE_BODY( dispatching_schedule_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
    };

    struct schedule_assign_ : ext::abstract_<schedule_assign_>
    {
      typedef ext::abstract_<schedule_assign_> parent;

      template<class... Args>
      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
      BOOST_AUTO_DECLTYPE_BODY( dispatching_schedule_assign_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
    };
  }

  // Tree + function + top mark
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL(tag::schedule_, schedule, (A0&)(A1 const&), 2)
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL(tag::schedule_, schedule, (A0 const&)(A1 const&), 2)

  // Special case assign node
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL(tag::schedule_assign_, schedule_assign, (A0&)(A1&)(A2 const&), 3)
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL(tag::schedule_assign_, schedule_assign, (A0 const&)(A1&)(A2 const&), 3)
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL(tag::schedule_assign_, schedule_assign, (A0 const&)(A1 const&)(A2 const&), 3)
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL(tag::schedule_assign_, schedule_assign, (A0&)(A1 const&)(A2 const&), 3)
} }

#endif

ext: hpp


text:
#include <stdio.h>
#include <inttypes.h>
#include <iostream>

#include <boost/shared_ptr.hpp>
#include <lcm/lcm-cpp.hpp>

#include "lcmtypes/bot_core.hpp"
#include <lcmtypes/microstrain.hpp>
#include <ConciseArgs>

#include <Eigen/Dense>
#include <Eigen/StdVector>

using namespace std;
using namespace Eigen;

class Pass{
  public:
    Pass(boost::shared_ptr<lcm::LCM> &lcm_, bool verbose_,
         std::string ins_channel_);

    ~Pass(){
    }
  private:
    boost::shared_ptr<lcm::LCM> lcm_;
    bool verbose_;
    std::string ins_channel_;

    void insHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  microstrain::ins_t* msg);
    microstrain::ins_t lidar_msgout_;
};

Pass::Pass(boost::shared_ptr<lcm::LCM> &lcm_, bool verbose_,
         std::string ins_channel_):
    lcm_(lcm_), verbose_(verbose_),
    ins_channel_(ins_channel_){
  lcm_->subscribe( ins_channel_ ,&Pass::insHandler,this);
  cout << "Finished setting up\n";
}

void Pass::insHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  microstrain::ins_t* msg){
  Eigen::Quaterniond meas_rot(msg->quat[0],msg->quat[1],msg->quat[2],msg->quat[3]);
  Eigen::Matrix3d meas_rotation(meas_rot);

  // rotate coordinate frame so that look vector is +X, and up is +Z
  Eigen::Matrix3d M;
  M <<  -1, 0,  0,
         0, 1,  0,
         0, 0, -1;

  // which is equivalent to:
  /*
  double rpy[] = {M_PI, 0,M_PI};
  double q[4],rot[9];
  roll_pitch_yaw_to_quat (rpy,q);
  quat_to_matrix(q,rot);
  M << rot[0], rot[1], rot[2],
       rot[3], rot[4], rot[5],
       rot[6], rot[7], rot[8];

  cout << rot[0] << " " << rot[1] << " "<< rot[2] << "\n";
  cout << rot[3] << " "<< rot[4] << " "<< rot[5] << "\n";
  cout << rot[6] << " "<< rot[7] << " "<< rot[8] << "\n";
  */

  meas_rotation= M * meas_rotation;
  Eigen::Quaterniond rotation = Eigen::Quaterniond( meas_rotation * M.transpose() );

  bot_core::pose_t pose_msg;
  pose_msg.utime = msg->utime;
  pose_msg.pos[0] =0;
  pose_msg.pos[1] =0;
  pose_msg.pos[2] =1.6;
  pose_msg.orientation[0] = rotation.w();
  pose_msg.orientation[1] = rotation.x();
  pose_msg.orientation[2] = rotation.y();
  pose_msg.orientation[3] = rotation.z();
  lcm_->publish("POSE_BODY", &pose_msg);
}

int main( int argc, char** argv ){
  ConciseArgs parser(argc, argv, "lidar-passthrough");
  bool verbose=false;
  string ins_channel="MICROSTRAIN_INS";
  parser.add(verbose, "v", "verbose", "Verbosity");
  parser.add(ins_channel, "l", "ins_channel", "Incoming INS channel");
  parser.parse();
  cout << verbose << " is verbose\n";
  cout << ins_channel << " is ins_channel\n";

  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if(!lcm->good()){
    std::cerr <<"ERROR: lcm is not good()" <<std::endl;
  }

  Pass app(lcm,verbose,ins_channel);
  cout << "Ready to convert from imu to pose" << endl << "============================" << endl;
  while(0 == lcm->handle());
  return 0;
}

ext: cpp

max_stars_repo_name: liangfok/oh-distro

max_issues_repo_name: liangfok/oh-distro

max_forks_repo_name: liangfok/oh-distro


text:
#include "BoostPythonCoreScanner.h"
#include <stdlib.h>
#include <sstream>
#include <boost/python/make_function.hpp>

template<class a>
py::object call_python(py::object& fn, a& arg1) {
	py::object ret;
	PyGILState_STATE state = PyGILState_Ensure();
	try {
		ret = fn(arg1);
	} catch(const py::error_already_set&) {
		PyObject *e, *v, *t;
		PyErr_Fetch(&e, &v, &t);
		PyObject* e_obj = PyObject_Repr(e);
		PyObject* v_obj = PyObject_Repr(v);
		std::string e_str = PyUnicode_AsUTF8(e_obj);
		std::string v_str = PyUnicode_AsUTF8(v_obj);
		cout << "Error occured: " <<  e_str << "\n";
		cout << v_str << "\n";
		PyErr_Restore(e, v, t);
		throw;
	}
	PyGILState_Release(state);
	return ret;
}

// BOOST_PYTHON_MODULE(zebra_scanner)
PYBIND11_MODULE(zebra_scanner, m)
{
	using namespace py;

	class_<CoreScanner>(m, "CoreScanner")
		.def(py::init<>())
		.def("open", &CoreScanner::Open)
		.def("close", &CoreScanner::Close)
		.def("on_scanner_added", &CoreScanner::OnScannerAddedDecorator)
		.def("on_scanner_removed", &CoreScanner::OnScannerRemovedDecorator)
		.def("fetch_scanners", &CoreScanner::FetchScanners);

	class_<Scanner>(m, "Scanner")
		.def("on_barcode", &Scanner::OnBarcodeDecorator)
		.def("pull_trigger", &Scanner::PullTrigger)
		.def("release_trigger", &Scanner::ReleaseTrigger)
		.def("fetch_attributes", static_cast<void (Scanner::*)()>(&Scanner::FetchAttributes))
		.def("fetch_attributes", static_cast<void (Scanner::*)(std::string)>(&Scanner::FetchAttributes))
		.def_readonly("attributes", &Scanner::attributes)
		.def_readonly("type", &Scanner::type)
		.def_readonly("scannerID", &Scanner::scannerID)
		.def_readonly("serialnumber", &Scanner::serialnumber)
		.def_readonly("GUID", &Scanner::GUID)
		.def_readonly("PID", &Scanner::PID)
		.def_readonly("VID", &Scanner::VID)
		.def_readonly("modelnumber", &Scanner::modelnumber)
		.def_readonly("DoM", &Scanner::DoM)
		.def_readonly("firmware", &Scanner::firmware);

	class_<Attribute>(m, "Attribute")
		.def("get_value", &Attribute::GetValue)
		.def("set_value", &Attribute::SetValue)
		.def("store_value", &Attribute::StoreValue)
		.def_readonly("id", &Attribute::id)
		.def_readonly("permission", &Attribute::permission)
		.def_readonly("datatype", &Attribute::datatype)
		.def_readonly("value", &Attribute::value);

	// used to be class_<Barcode, std::auto_ptr<Barcode> >(m, "Barcode")
	class_<Barcode>(m, "Barcode")
		.def_readonly("code", &Barcode::code)
		.def_readonly("type", &Barcode::type);
}

Scanner::Scanner() {
}

void Scanner::OnBarcodeDecorator(py::object& obj) {
	on_barcode.push_back(obj);
}

void Scanner::OnBarcode(py::object& obj) {
	for(std::vector<py::object>::iterator i=on_barcode.begin();i!=on_barcode.end();++i) {
	    call_python(*i, obj);
	}
}

void Scanner::PullTrigger()
{
    StatusID status;
    std::string inXml = "<inArgs><scannerID>" + scannerID + "</scannerID></inArgs>";
    std::string outXml;
    ::ExecCommand(CMD_DEVICE_PULL_TRIGGER, inXml, outXml, &status);
}

void Scanner::ReleaseTrigger()
{
    StatusID status;
    std::string inXml = "<inArgs><scannerID>" + scannerID + "</scannerID></inArgs>";
    std::string outXml;
    ::ExecCommand(CMD_DEVICE_RELEASE_TRIGGER, inXml, outXml, &status);
}

py::dict Scanner::get_dict() {
	py::dict d;
	d["type"] = type;
	d["scannerID"] = scannerID;
	d["serialnumber"] = serialnumber;
	d["GUID"] = GUID;
	d["PID"] = PID;
	d["VID"] = VID;
	d["modelnumber"] = modelnumber;
	d["DoM"] = DoM;
	d["firwmare"] = firmware;
	return d;
}

CoreScanner* CORE_SCANNER_SINGLETON;
#include <csignal>

void signal_handler_close(int num) {
	if(CORE_SCANNER_SINGLETON && CORE_SCANNER_SINGLETON->is_open) {
		CORE_SCANNER_SINGLETON->Close();
	}

	if(num == SIGINT || num == SIGTERM) {
		std::exit(128+num);
	}
}

CoreScanner::CoreScanner()
	: is_open(false)
{
	CORE_SCANNER_SINGLETON = this;
	PyEval_InitThreads();
	std::signal(SIGINT, signal_handler_close);
	std::signal(SIGTERM, signal_handler_close);
	Open();
}

CoreScanner::~CoreScanner()
{
	if(is_open)
		Close();
}

void CoreScanner::Open()
{
    StatusID status;
    ::Open(this, SCANNER_TYPE_ALL, &status);

    // std::string inXml = "<inArgs><cmdArgs><arg-int>7</arg-int><arg-int>1,2,4,8,16,32,128</arg-int></cmdArgs></inArgs>";

    std::string inXml = "<inArgs><cmdArgs><arg-int>6</arg-int><arg-int>1,2,4,8,16,32</arg-int></cmdArgs></inArgs>";
    std::string outXml;
    ::ExecCommand(CMD_REGISTER_FOR_EVENTS, inXml, outXml, &status);
	FetchScanners();
	is_open = true;
}

#include <algorithm>
#include <cctype>
#include <locale>

static inline void ltrim(std::string &s) {
	s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
		return !std::isspace(ch);
	}));
}

static inline void rtrim(std::string &s) {
	s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
		return !std::isspace(ch);
	}).base(), s.end());
}

static inline void trim(std::string &s) {
	ltrim(s);
	rtrim(s);
}

void CoreScanner::ParseScannerXML(pugi::xml_node& scanner) {
	std::string id = scanner.child_value("scannerID");
	Scanner s;
	s.active = true;
	s.type = scanner.attribute("type").value();
	s.scannerID = id;
	s.serialnumber = scanner.child_value("serialnumber");
	s.GUID = scanner.child_value("GUID");
	s.PID = scanner.child_value("PID");
	s.VID = scanner.child_value("VID");
	s.modelnumber = scanner.child_value("modelnumber");
	s.firmware = scanner.child_value("firmware");
	trim(s.serialnumber);
	trim(s.modelnumber);
	trim(s.firmware);
	s.DoM = scanner.child_value("DoM");
	PyGILState_STATE state = PyGILState_Ensure();
	py::object o = py::cast(s);
	_scanners[id] = o;
	// o.attr("__dict__").attr("update")(s.get_dict());
	PyGILState_Release(state);

	// wait for some kind of response from the scanner
	// so that we know we can access the scanner
	// in our on_scanner_added callback
	s.FetchAttributes("0");
	OnScannerAdded(o);
}

void Scanner::FetchAttributes() {
    std::string inXml = "<inArgs><scannerID>"+scannerID+"</scannerID></inArgs>";
    StatusID sId;
    std::string outXml;

    ::ExecCommand(CMD_RSM_ATTR_GETALL, inXml, outXml, &sId);

	pugi::xml_document outargs;
	outargs.load_buffer_inplace(&outXml[0], outXml.size());
	std::string attribute_list;
	bool first = true;
	for(pugi::xml_node attr = outargs.child("outArgs").child("arg-xml").child("response").child("attrib_list").child("attribute");
			attr;
			attr = attr.next_sibling("attribute")) {
		if(!first)
			attribute_list += ',';
		attribute_list += attr.child_value();
		first = false;
	}
	FetchAttributes(attribute_list);
}

void Scanner::FetchAttributes(std::string attribute_list) {
	std::string inXml = "<inArgs><scannerID>" + scannerID +
						"</scannerID><cmdArgs><arg-xml><attrib_list>" +
						attribute_list + "</attrib_list></arg-xml></cmdArgs></inArgs>";

    StatusID sId;
	std::string outXmlA;
	::ExecCommand(CMD_RSM_ATTR_GET, inXml, outXmlA, &sId);
	pugi::xml_document outargs;
	outargs.load_buffer_inplace(&outXmlA[0], outXmlA.size());
	std::string False("False");
	for(pugi::xml_node attr = outargs.child("outArgs").child("arg-xml").child("response").child("attrib_list").child("attribute");
			attr;
			attr = attr.next_sibling("attribute")) {
		Attribute a(this);
		a.id = std::stoi(attr.child_value("id"));
		a.datatype = attr.child_value("datatype")[0];
		a.permission = std::stoi(attr.child_value("permission"));
		// Information about data types is taken from zebra-scanner-4.4.1-8/Native/CsClient/src/CsDecodeIncomming.cpp
		if (a.datatype=='F') { // Flag? A boolean
			if(False.compare(attr.child_value("value")) == 0) {
				a.value = py::cast(false);
			} else {
				a.value = py::cast(true);
			}
		}
		else if (a.datatype=='B' || a.datatype=='W' || a.datatype=='D') { //uint8_t/uint16_t/uint32_t
			a.value = py::cast(std::stoul(attr.child_value("value")));
		}
		else if (a.datatype=='I' || a.datatype=='L') { // int16_t/int32_t
			a.value = py::cast(std::stol(attr.child_value("value")));
		}
		else { // String or single character
			a.value = py::cast(attr.child_value("value"));
		}
		attributes[py::cast(a.id)] = a;
	}
}

int Attribute::SetValue(py::object v) {
	return ExecuteSetOrStoreAttribute(CMD_RSM_ATTR_SET, v);
}

int Attribute::StoreValue(py::object v) {
	return ExecuteSetOrStoreAttribute(CMD_RSM_ATTR_STORE, v);
}

int Attribute::ExecuteSetOrStoreAttribute(CmdOpcode command, py::object v)
{
	std::string value_as_string;
	CastValueToString(v, value_as_string);
    std::string inXml = "<inArgs><scannerID>" + scanner->scannerID + "</scannerID><cmdArgs><arg-xml><attrib_list><attribute>" +
		"<id>" + std::to_string(id) + "</id>" +
		"<datatype>" + datatype + "</datatype>" +
		"<value>" + value_as_string + "</value>" +
		"</attribute></attrib_list></arg-xml></cmdArgs></inArgs>";
    std::string outXml;
    StatusID status;
    ::ExecCommand(command, inXml, outXml, &status);
	if (status == STATUS_OK) {
		value = v; // Update local copy of the new value
	}
	return status;
}

void Attribute::CastValueToString(py::object v, std::string &value_as_string) {
	// Information about data types is taken from zebra-scanner-4.4.1-8/Native/CsClient/src/CsDecodeIncomming.cpp
	switch (datatype) {
		case 'F': // Boolean (F for flag?)
			value_as_string = v.cast<bool>() ? "True" : "False";
			break;

		case 'B': // uint8_t
		case 'W': // uint16_t
		case 'D': // uint32_t
			value_as_string = std::to_string(v.cast<uint32_t>());
			break;

		case 'I': // int16_t
		case 'L': // int32_t
			value_as_string = std::to_string(v.cast<int32_t>());
			break;

		default: // A string
			value_as_string = v.cast<std::string>();
			break;
	}
}

void CoreScanner::OnScannerAddedDecorator(py::object& obj) {
	on_added.push_back(CoreScanner::scanner_callback(obj));
	for(std::map<std::string, py::object>::iterator i = _scanners.begin(); i != _scanners.end(); ++i) {
		py::object& o = i->second;
		Scanner& s = o.cast<Scanner&>();
		if(s.active)
			call_python(obj, o);
	}
}

void CoreScanner::OnScannerRemovedDecorator(py::object& obj) {
	on_removed.push_back(CoreScanner::scanner_callback(obj));
}

void CoreScanner::OnScannerAdded(py::object& o) {
	for(std::vector<CoreScanner::scanner_callback>::iterator i=on_added.begin();i!=on_added.end();++i) {
		call_python(*i, o);
	}
}

void CoreScanner::OnScannerRemoved(py::object& o) {
	for(std::vector<CoreScanner::scanner_callback>::iterator i=on_removed.begin();i!=on_removed.end();++i) {
		call_python(*i, o);
	}
}

void CoreScanner::FetchScanners()
{
    unsigned short count;
    vector<unsigned int> list;
    string outXml;
    StatusID eStatus;
    ::GetScanners(&count, &list, outXml, &eStatus);
    if ( eStatus != STATUS_OK )
    {
		return;
    }
	pugi::xml_document scanners;
	scanners.load_buffer_inplace(&outXml[0], outXml.size());
	for(pugi::xml_node scanner = scanners.child("scanners").child("scanner"); scanner; scanner = scanner.next_sibling("scanner")) {
		ParseScannerXML(scanner);
	}
}

void CoreScanner::Close()
{
	for(std::map<std::string, py::object>::iterator i = _scanners.begin(); i != _scanners.end(); ++i) {
		py::object& o = i->second;
		Scanner& s = o.cast<Scanner&>();
		if(s.active)
			OnScannerRemoved(o);
	}
    StatusID status;
    ::Close(0, &status);
	is_open = false;
}

/// TODO: implement python callbacks
void CoreScanner::OnBinaryDataEvent(short eventType, int dataLength, short dataFormat, unsigned char* sfBinaryData, std::string& pScannerData)
{
}

void CoreScanner::OnImageEvent( short eventType, int size, short imageFormat, char* sfimageData, int dataLength, std::string& pScannerData )
{
}

void CoreScanner::OnVideoEvent( short eventType, int size, char* sfvideoData, int dataLength, std::string& pScannerData )
{
}

void CoreScanner::OnPNPEvent( short eventType, std::string ppnpData )
{
    if (eventType == SCANNER_ATTACHED || eventType == SCANNER_DETACHED) {
		pugi::xml_document outargs;
		outargs.load_buffer_inplace(&ppnpData[0], ppnpData.size());
		for(pugi::xml_node scanner = outargs.child("outargs").child("arg-xml").child("scanners").child("scanner");
				scanner;
				scanner = scanner.next_sibling("scanner")) {
			if (eventType == SCANNER_ATTACHED) {
				FetchScanners();
			} else {
				py::object& o = _scanners[scanner.child_value("scannerID")];
				Scanner& s = o.cast<Scanner&>();
				if(s.active) {
					s.active = false;
					OnScannerRemoved(o);
				}
			}
		}
    }
}

void CoreScanner::OnCommandResponseEvent( short status, std::string& prspData )
{
}

void CoreScanner::OnScannerNotification( short notificationType, std::string& pScannerData )
{
}

void CoreScanner::OnIOEvent( short type, unsigned char data )
{
}

void CoreScanner::OnScanRMDEvent( short eventType, std::string& prmdData )
{
}

void CoreScanner::OnDisconnect()
{
}

void CoreScanner::OnBarcodeEvent(short int eventType, std::string & pscanData)
{
	pugi::xml_document outargs;
	outargs.load_buffer_inplace(&pscanData[0], pscanData.size());
	pugi::xml_node args = outargs.child("outArgs");
	std::string scannerID = args.child_value("scannerID");
	std::map<std::string, py::object>::iterator si = _scanners.find(scannerID);
	if(si == _scanners.end()) {
		FetchScanners();
		return;
	}
	Scanner& s = si->second.cast<Scanner&>();
	if(!s.active) {
		FetchScanners();
		return;
	}

	for(pugi::xml_node scanData = args.child("arg-xml").child("scandata");
			scanData;
			scanData = scanData.next_sibling("scandata")) {

		std::string data = scanData.child_value("datalabel");
		std::string result;
		for(std::string::iterator i=data.begin(); i!=data.end(); ++i) {
			std::stringstream ss;
			char c1 = *(i++) - 48;
			if(c1 > 9) c1 -= 39;
			char c2 = *(i++) - 48;
			if(c2 > 9) c2 -= 39;
			char d = 16*c1+c2;;
			result.append(1, d);
		}
		Barcode b;
		b.code = result;
		b.type = std::stoi(scanData.child_value("datatype"));
		py::object o = py::cast(b);
		s.OnBarcode(o);
	}
}

max_stars_repo_name: Netimage/zebra-scanner

max_issues_repo_name: Netimage/zebra-scanner

max_forks_repo_name: Netimage/zebra-scanner


text:
// Author: Michael Kaufmann <kau@zurich.ibm.com>
//
// Copyright (c) 2018, IBM Corporation, All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.

#include <climits>
#include <fstream>
#include <map>
#include <random>
#include <set>
#include <thread>
#include <unordered_map>

#include "app/app.h"
#include "common.h"
#include "event/engine.h"

#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;

App::App(AppId id, std::string name, std::string driverUrl)
{
    this->state(TaskState::unknown);
    this->_metrics.submitted(Time::now());

    this->id(id);
    this->name(name);
    this->driverUrl(driverUrl);
    this->load();
}

App::~App()
{
}

std::unique_lock<Mutex> __attribute__((warn_unused_result)) App::guard(int id)
{
    logCInfo(LC_LOCK | LC_APP) << "About to acquire app " << this->id() << " guard " << id;
    auto lock = std::unique_lock<Mutex>(this->_mutex, std::defer_lock);
    while (!lock.try_lock_for(10s)) {
        logWarn << "Unable to acquire guard " << id << " for application " << this->id()
                << " within the last 10s";
    }
    logCInfo(LC_LOCK | LC_APP) << "Acquired app " << this->id() << " guard " << id;
    return lock;
}

void App::lock(int id)
{
    logCDebug(LC_LOCK | LC_APP) << "About to acquire app " << this->id() << " lock " << id;
    while (!this->_mutex.try_lock_for(10s)) {
        logWarn << "Unable to acquire lock " << id << " for application " << this->id()
                << " within the last 10s";
    }
    logCDebug(LC_LOCK | LC_APP) << "Acquired app " << this->id() << " lock " << id;
}

void App::unlock(int id)
{
    this->_mutex.unlock();
    logCDebug(LC_LOCK | LC_APP) << "Released app " << this->id() << " lock " << id;
}

void App::addStages(std::map<Stage *, std::list<StageId>> stages)
{
    try {
        // 1. Add stages
        for (auto &entry : stages) {
            Stage *stage = entry.first;
            stage->scheduler(this->scheduler());
            // Map the raw key into out continuous key space
            stage->key(this->stageKeyMapper().add(stage->key()));

            this->_stages.emplace(stage->nid(), stage);
            //        logInfo(0) << "Added stage " << stage->id() << " (key=" << stage->key() << ")";
        }

        // 2. Connect stages
        for (auto &entry : stages) {
            Stage *            dst          = entry.first;
            auto &             dependencies = entry.second;
            std::ostringstream os;
            os << "{";
            for (StageId snid : dependencies) {
                Stage *src = this->_stages.at(snid);

                auto it = this->_io.emplace(std::piecewise_construct,
                                            std::forward_as_tuple(std::make_pair(src, dst)),
                                            std::forward_as_tuple(src, dst, 1));

                src->next(&it.first->second);
                dst->prev(&it.first->second);

                os << src->id() << ", ";
            }

            if (os.str().length() > 1)
                os.seekp(-2, std::ios_base::end) << "} -> ";
            else
                os << "} -> ";

            logInfo(0) << os.str() << dst->id();
        }

        // 3. Compute level of each stage (distance to output)
        for (auto &entry : stages) {
            Stage *stage = entry.first;
            if (stage->next().empty())
                stage->level(0);
        }

        // 4. Add stages to schedule
        for (auto &entry : stages) {
            Stage *stage = entry.first;
            this->_schedule.addStage(stage);
            logInfo(0) << "Added stage " << stage->id() << " (key=" << stage->key()
                       << ", level=" << stage->level() << ", type=" << stage->type() << ")";
        }
    } catch (std::out_of_range const &e) {
        std::ostringstream os;
        for (auto &entry : stages) {
            Stage *stage = entry.first;
            if (stage)
                os << stage->id() << " (";
            else
                os << "NULL"
                   << " (";

            for (StageId dep : entry.second) {
                os << dep << " ";
            }

            os << ")";
        }

        logError << "Failed to add stages " << os.str() << " : " << e.what();
    }
}

Stage *App::stage(StageId id)
{
    auto s = this->_stages.find(id);
    if (s != this->_stages.end())
        return s->second;
    else
        return NULL;
}

void App::load()
{
    try {
        std::string   skeysFileName = config->perfdbdir() + "/" + this->name() + "-skeys.json";
        std::ifstream skeysFile(skeysFileName, std::ios::in);

        if (skeysFile.is_open()) {
            ptree skeys;
            read_json(skeysFile, skeys);
            skeysFile.close();
            this->_stageKeyMapper.load(skeys);

            logInfo(0) << "Loaded " << this->_stageKeyMapper.size() << " stage key mappings from "
                       << skeysFileName;
        }
    } catch (std::exception const &e) {
        logError << "Error while loading other stuff: " << e.what();
        return;
    }
}

void App::store()
{
    try {
        std::string   skeysFileName = config->perfdbdir() + "/" + this->name() + "-skeys.json";
        std::ofstream skeysFile(skeysFileName, std::ios::out | std::ios::trunc);
        ptree         skeys = this->_stageKeyMapper.store();
        write_json(skeysFile, skeys);
        skeysFile.close();

        logInfo(0) << "Stored " << this->_stageKeyMapper.size() << " stage key mappings to " << skeysFileName;
    } catch (std::exception const &e) {
        logError << "Error while storing stage key mappings: " << e.what();
        return;
    }
}

void App::state(TaskState state)
{
    this->_state = state;

    switch (this->state()) {
    case TaskState::unknown:
        break;
    case TaskState::unready:
        break;
    case TaskState::ready:
        break;
    case TaskState::scheduled:
        break;
    case TaskState::running:
        this->_metrics.started(Time::now());
        break;
    case TaskState::finished:
        this->_metrics.finished(Time::now());
        this->_metrics.runtime(this->_metrics.finished() - this->_metrics.started());
        this->store();
        break;
    }
}

std::ostream &operator<<(std::ostream &os, const App &obj)
{
    os << obj.id() << " (" << obj.name() << ")";
    return os;
}

ext: cc

max_stars_repo_name: zrlkau/hcs

max_issues_repo_name: zrlkau/hcs

max_forks_repo_name: zrlkau/hcs


text:
// (C) Copyright Toon Knapen    2001.
// (C) Copyright David Abrahams 2003.
// (C) Copyright Roland Richter 2003.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PERMUTATION_ITERATOR_HPP
#define BOOST_PERMUTATION_ITERATOR_HPP

#include <iterator>

#include <boost/iterator/iterator_adaptor.hpp>

namespace boost {
namespace iterators {

template< class ElementIterator
        , class IndexIterator>
class permutation_iterator
  : public iterator_adaptor<
             permutation_iterator<ElementIterator, IndexIterator>
           , IndexIterator, typename std::iterator_traits<ElementIterator>::value_type
           , use_default, typename std::iterator_traits<ElementIterator>::reference>
{
  typedef iterator_adaptor<
            permutation_iterator<ElementIterator, IndexIterator>
          , IndexIterator, typename std::iterator_traits<ElementIterator>::value_type
          , use_default, typename std::iterator_traits<ElementIterator>::reference> super_t;

  friend class iterator_core_access;

public:
  permutation_iterator() : m_elt_iter() {}

  explicit permutation_iterator(ElementIterator x, IndexIterator y)
      : super_t(y), m_elt_iter(x) {}

  template<class OtherElementIterator, class OtherIndexIterator>
  permutation_iterator(
      permutation_iterator<OtherElementIterator, OtherIndexIterator> const& r
      , typename enable_if_convertible<OtherElementIterator, ElementIterator>::type* = 0
      , typename enable_if_convertible<OtherIndexIterator, IndexIterator>::type* = 0
      )
    : super_t(r.base()), m_elt_iter(r.m_elt_iter)
  {}

private:
    typename super_t::reference dereference() const
        { return *(m_elt_iter + *this->base()); }

#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
    template <class,class> friend class permutation_iterator;
#else
 public:
#endif
    ElementIterator m_elt_iter;
};

template <class ElementIterator, class IndexIterator>
inline permutation_iterator<ElementIterator, IndexIterator>
make_permutation_iterator( ElementIterator e, IndexIterator i )
{
    return permutation_iterator<ElementIterator, IndexIterator>( e, i );
}

} // namespace iterators

using iterators::permutation_iterator;
using iterators::make_permutation_iterator;

} // namespace boost

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
#include "config.h"

#include <iostream>

#include <boost/filesystem.hpp>
#include <rapidxml.hpp>
#include <rapidxml_utils.hpp>

struct Config::Impl {
    int id;
    std::string name;
    int units;
    float width, height;
    std::map<std::string, assets::tileset> _tilesets;
    std::map<std::string, std::pair<std::string, std::string>> _layouts;
};

Config::Config() : pImpl(std::make_unique<Impl>()) {}

Config::Config(const Config& other) : pImpl(std::make_unique<Impl>(*other.pImpl)) {
    pImpl->_tilesets = other.pImpl->_tilesets;
}

Config::~Config() {}

Config Config::load(const std::string& filepath) {
    rapidxml::file<> xmlFile(filepath.c_str());
    rapidxml::xml_document<> doc;
    try {
        Config config;
        auto basepath = boost::filesystem::path(filepath).parent_path();

        doc.parse<0>(xmlFile.data());
        auto root = doc.first_node();

        // Parse some metadata
        config.pImpl->id = atoi(root->first_attribute("id")->value());
        config.pImpl->name = root->first_attribute("name")->value();

        auto size_node = root->first_node("size");
        config.pImpl->units = atof(size_node->first_attribute("units")->value());
        config.pImpl->width = atof(size_node->first_attribute("width")->value());
        config.pImpl->height = atof(size_node->first_attribute("height")->value());

        // Parse tilesets
        auto tilesets = root->first_node("tilesets");
        auto tileset_node = tilesets->first_node("tileset");
        while (tileset_node) {
            auto filename = (basepath / tileset_node->value()).normalize().generic_string();
            auto [_, inserted] = config.pImpl->_tilesets.try_emplace(tileset_node->first_attribute("id")->value(), assets::tileset::load(filename));
            tileset_node = tileset_node->next_sibling("tileset");
        }

        // Parser layouts
        auto layouts = root->first_node("layouts");
        auto layout_node = layouts->first_node("layout");
        while (layout_node) {
            auto filename = (basepath / layout_node->value()).normalize().generic_string();
            auto tileset = layout_node->first_attribute("tileset")->value();
            auto [_, inserted] = config.pImpl->_layouts.try_emplace(layout_node->first_attribute("id")->value(), std::make_pair(tileset, filename));
            layout_node = layout_node->next_sibling("layout");
        }

        return config;
    }
    catch(rapidxml::parse_error & e) {
        std::cerr << "Parse error: " << e.what() << std::endl << "At: " << e.where<char>() << std::endl;
        throw std::runtime_error("Invalid file"); // TODO
    }
    catch(std::exception& e) {
        // TODO:
        throw e;
    }
}

int Config::id() const {
    return pImpl->id;
}

const std::string& Config::name() const {
    return pImpl->name;
}

int Config::units() const {
    return pImpl->units;
}

float Config::width() const {
    return pImpl->width;
}

float Config::height() const {
    return pImpl->height;
}

const std::map<std::string, assets::tileset>& Config::tilesets() const {
    return pImpl->_tilesets;
}

const std::map<std::string, std::pair<std::string, std::string>>& Config::layouts() const {
    return pImpl->_layouts;
}


text:
#define BOOST_TEST_MODULE Test

#include "keyboard_optimizer/deserializer.hpp"
#include "keyboard_optimizer/library_interface.hpp"
#include <boost/test/included/unit_test.hpp>
#include <iostream>
#include <sstream>

using namespace KeyboardOptimizer;

BOOST_AUTO_TEST_CASE(deserialize_test) {
  auto str = "[Keyboard]      \n"
             "acc = [0, 0    ]\n"
             "1   = [0, 1    ]\n"
             "2   = [0, 2    ]\n"
             "4   = [0, 4    ]\n"
             "3   = [0, 3    ]\n"
             "5   = [0, 5    ]\n"
             "[Modifiers]\n"
             "0 = []     \n"
             "2 = ['5']  \n"
             "1 = ['1']  \n";
  auto ss = std::stringstream(str);
  auto t = toml::parse(ss);
  auto v = toml::value{};
  {
    auto const &k = toml::find(t, "Keyboard");
    v = k;
  }
  auto const &m = toml::find(t, "Modifiers");
  auto kt = DeserializeKeyboard(v);
  auto mt = DeserializeModifiers(m, kt);
  auto &&aaa = std::setw(std::cout.width());
  auto str2 = std::string("Keyboard");
  auto yyy = toml::value{{str2, std::move(v)}};
  std::cout << yyy << std::endl;
  std::cout << std::endl;
  std::cout << m << std::endl;
}

BOOST_AUTO_TEST_CASE(tmp_test) {
  auto str = "[Constraints]                       \n"
             "0 = [\"abcdefghijklmnopqrstuvwxyz',.\\n:\"]\n"
             "1 = [\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\\";\"]  \n"
             "2 = []                          \n"
             "                                           \n"
             "Bonds=['aA','bB', 'cC', 'dD', 'eE', 'fF', 'gG', "
             "'hH', 'iI', 'jJ', 'kK', 'lL', 'mM', 'nN', 'oO', 'pP', 'qQ', "
             "'rR', 'sS', 'tT', 'uU', 'vV', 'wW', 'xX', 'yY', 'zZ']";
  auto ss = std::stringstream(str);
  auto t = toml::parse(ss);
  auto &&aaa = toml::find(t, "Constraints");
  std::cout << aaa << std::endl;
  auto x = std::unordered_map<int, std::string const &>{};
  auto aaaa = std::string("aaa");
  x.emplace(1, aaaa);
  aaaa = "bbb";
  std::cout << x.at(1);
}


text:
#ifndef LIVEODR_UTILS_HPP
#define LIVEODR_UTILS_HPP

#include <dlib/geometry/rectangle.h>
#include <opencv2/core/types.hpp>

namespace liveodr::utils {
  /* Source: https://stackoverflow.com/a/34873134/1935009 */
  static cv::Rect dlib_to_opencv_rect(dlib::rectangle r) {
    return cv::Rect(cv::Point2i(r.left(), r.top()), cv::Point2i(r.right() + 1, r.bottom() + 1));
  }

  static dlib::rectangle opencv_to_dlib_rect(cv::Rect r) {
    return dlib::rectangle((long)r.tl().x, (long)r.tl().y, (long)r.br().x - 1, (long)r.br().y - 1);
  }
}

#endif /* ifndef LIVEODR_UTILS_HPP */

max_stars_repo_name: YashasSamaga/liveodr

max_issues_repo_name: YashasSamaga/liveodr

max_forks_repo_name: YashasSamaga/liveodr


text:
#include "source_diff.h"
#include "config.h"
#include "terminal.h"
#include "filesystem.h"
#include "info.h"
#include <boost/version.hpp>

Source::DiffView::Renderer::Renderer() : Gsv::GutterRenderer() {
  set_padding(4, 0);
}

void Source::DiffView::Renderer::draw_vfunc(const Cairo::RefPtr<Cairo::Context> &cr, const Gdk::Rectangle &background_area,
                                            const Gdk::Rectangle &cell_area, Gtk::TextIter &start, Gtk::TextIter &end,
                                            Gsv::GutterRendererState p6) {
  if(start.has_tag(tag_added) || end.has_tag(tag_added)) {
    cr->set_source_rgba(0.0, 1.0, 0.0, 0.5);
    cr->rectangle(cell_area.get_x(), cell_area.get_y(), 4, cell_area.get_height());
    cr->fill();
  }
  else if(start.has_tag(tag_modified) || end.has_tag(tag_modified)) {
    cr->set_source_rgba(0.9, 0.9, 0.0, 0.75);
    cr->rectangle(cell_area.get_x(), cell_area.get_y(), 4, cell_area.get_height());
    cr->fill();
  }
  if(start.has_tag(tag_removed_below) || end.has_tag(tag_removed_below)) {
    cr->set_source_rgba(0.75, 0.0, 0.0, 0.5);
    cr->rectangle(cell_area.get_x()-4, cell_area.get_y()+cell_area.get_height()-2, 8, 2);
    cr->fill();
  }
  if(start.has_tag(tag_removed_above) || end.has_tag(tag_removed_above)) {
    cr->set_source_rgba(0.75, 0.0, 0.0, 0.5);
    cr->rectangle(cell_area.get_x()-4, cell_area.get_y(), 8, 2);
    cr->fill();
  }
}

Source::DiffView::DiffView(const boost::filesystem::path &file_path) : Gsv::View(), file_path(file_path), renderer(new Renderer()) {
  boost::system::error_code ec;
  canonical_file_path=boost::filesystem::canonical(file_path, ec);
  if(ec)
    canonical_file_path=file_path;

  renderer->tag_added=get_buffer()->create_tag("git_added");
  renderer->tag_modified=get_buffer()->create_tag("git_modified");
  renderer->tag_removed=get_buffer()->create_tag("git_removed");
  renderer->tag_removed_below=get_buffer()->create_tag();
  renderer->tag_removed_above=get_buffer()->create_tag();

  last_write_time=boost::filesystem::last_write_time(file_path, ec);
  if(ec)
    last_write_time=static_cast<std::time_t>(-1);

  signal_focus_in_event().connect([this](GdkEventFocus *event) {
    check_last_write_time();
    return false;
  });

  configure();
}

Source::DiffView::~DiffView() {
  dispatcher.disconnect();
  if(repository) {
    get_gutter(Gtk::TextWindowType::TEXT_WINDOW_LEFT)->remove(renderer.get());
    buffer_insert_connection.disconnect();
    buffer_erase_connection.disconnect();
    monitor_changed_connection.disconnect();
    delayed_buffer_changed_connection.disconnect();
    delayed_monitor_changed_connection.disconnect();

    parse_stop=true;
    if(parse_thread.joinable())
      parse_thread.join();
  }
}

void Source::DiffView::check_last_write_time() {
  if(has_focus()) {
    boost::system::error_code ec;
    auto last_write_time=boost::filesystem::last_write_time(file_path, ec);
    if(!ec && this->last_write_time!=static_cast<std::time_t>(-1) && last_write_time!=this->last_write_time)
      Info::get().print("Caution: " + file_path.filename().string() + " was changed outside of juCi++");
  }
}

void Source::DiffView::configure() {
  if(Config::get().source.show_git_diff) {
    if(repository)
      return;
  }
  else if(repository) {
    get_gutter(Gtk::TextWindowType::TEXT_WINDOW_LEFT)->remove(renderer.get());
    buffer_insert_connection.disconnect();
    buffer_erase_connection.disconnect();
    monitor_changed_connection.disconnect();
    delayed_buffer_changed_connection.disconnect();
    delayed_monitor_changed_connection.disconnect();

    parse_stop=true;
    if(parse_thread.joinable())
      parse_thread.join();
    repository=nullptr;
    diff=nullptr;

    return;
  }
  else
    return;

  try {
    repository=Git::get_repository(this->file_path.parent_path());
  }
  catch(const std::exception &) {
    return;
  }

  get_gutter(Gtk::TextWindowType::TEXT_WINDOW_LEFT)->insert(renderer.get(), -40);
  parse_state=ParseState::STARTING;
  parse_stop=false;
  monitor_changed=false;

  buffer_insert_connection=get_buffer()->signal_insert().connect([this](const Gtk::TextBuffer::iterator &iter ,const Glib::ustring &text, int) {
    //Do not perform git diff if no newline is added and line is already marked as added
    if(!iter.starts_line() && iter.has_tag(renderer->tag_added)) {
      bool newline=false;
      for(auto &c: text.raw()) {
        if(c=='\n') {
          newline=true;
          break;
        }
      }
      if(!newline)
        return;
    }
    //Remove tag_removed_above/below if newline is inserted
    else if(!text.empty() && text[0]=='\n' && iter.has_tag(renderer->tag_removed)) {
      auto start_iter=get_buffer()->get_iter_at_line(iter.get_line());
      auto end_iter=get_iter_at_line_end(iter.get_line());
      end_iter.forward_char();
      get_buffer()->remove_tag(renderer->tag_removed_above, start_iter, end_iter);
      get_buffer()->remove_tag(renderer->tag_removed_below, start_iter, end_iter);
    }
    parse_state=ParseState::IDLE;
    delayed_buffer_changed_connection.disconnect();
    delayed_buffer_changed_connection=Glib::signal_timeout().connect([this]() {
      parse_state=ParseState::STARTING;
      return false;
    }, 250);
  }, false);

  buffer_erase_connection=get_buffer()->signal_erase().connect([this](const Gtk::TextBuffer::iterator &start_iter, const Gtk::TextBuffer::iterator &end_iter) {
    //Do not perform git diff if start_iter and end_iter is at the same line in addition to the line is tagged added
    if(start_iter.get_line()==end_iter.get_line() && start_iter.has_tag(renderer->tag_added))
      return;

    parse_state=ParseState::IDLE;
    delayed_buffer_changed_connection.disconnect();
    delayed_buffer_changed_connection=Glib::signal_timeout().connect([this]() {
      parse_state=ParseState::STARTING;
      return false;
    }, 250);
  }, false);

  monitor_changed_connection=repository->monitor->signal_changed().connect([this](const Glib::RefPtr<Gio::File> &file,
                                                                                const Glib::RefPtr<Gio::File>&,
                                                                                Gio::FileMonitorEvent monitor_event) {
    if(monitor_event!=Gio::FileMonitorEvent::FILE_MONITOR_EVENT_CHANGES_DONE_HINT) {
      delayed_monitor_changed_connection.disconnect();
      delayed_monitor_changed_connection=Glib::signal_timeout().connect([this]() {
        check_last_write_time();
        monitor_changed=true;
        parse_state=ParseState::STARTING;
        std::unique_lock<std::mutex> lock(parse_mutex);
        diff=nullptr;
        return false;
      }, 500);
    }
  });

  parse_thread=std::thread([this]() {
    std::string status_branch;
    try {
      diff=get_diff();
      status_branch=repository->get_branch();
    }
    catch(const std::exception &) {
      status_branch="";
    }
    dispatcher.post([this, status_branch=std::move(status_branch)] {
      this->status_branch=status_branch;
      if(update_status_branch)
        update_status_branch(this);
    });

    try {
      while(true) {
        while(!parse_stop && parse_state!=ParseState::STARTING && parse_state!=ParseState::PROCESSING)
          std::this_thread::sleep_for(std::chrono::milliseconds(10));
        if(parse_stop)
          break;
        std::unique_lock<std::mutex> parse_lock(parse_mutex, std::defer_lock);
        auto expected=ParseState::STARTING;
        if(parse_state.compare_exchange_strong(expected, ParseState::PREPROCESSING)) {
          dispatcher.post([this] {
            auto expected=ParseState::PREPROCESSING;
            std::unique_lock<std::mutex> parse_lock(parse_mutex, std::defer_lock);
            if(parse_lock.try_lock()) {
              if(parse_state.compare_exchange_strong(expected, ParseState::PROCESSING))
                parse_buffer=get_buffer()->get_text();
              parse_lock.unlock();
            }
            else
              parse_state.compare_exchange_strong(expected, ParseState::STARTING);
          });
        }
        else if (parse_state==ParseState::PROCESSING && parse_lock.try_lock()) {
          bool expected_monitor_changed=true;
          if(monitor_changed.compare_exchange_strong(expected_monitor_changed, false)) {
            try {
              diff=get_diff();
              dispatcher.post([this, status_branch=repository->get_branch()] {
                this->status_branch=status_branch;
                if(update_status_branch)
                  update_status_branch(this);
              });
            }
            catch(const std::exception &) {
              dispatcher.post([this] {
                get_buffer()->remove_tag(renderer->tag_added, get_buffer()->begin(), get_buffer()->end());
                get_buffer()->remove_tag(renderer->tag_modified, get_buffer()->begin(), get_buffer()->end());
                get_buffer()->remove_tag(renderer->tag_removed, get_buffer()->begin(), get_buffer()->end());
                get_buffer()->remove_tag(renderer->tag_removed_below, get_buffer()->begin(), get_buffer()->end());
                get_buffer()->remove_tag(renderer->tag_removed_above, get_buffer()->begin(), get_buffer()->end());
                renderer->queue_draw();
                this->status_branch="";
                if(update_status_branch)
                  update_status_branch(this);
              });
            }
          }
          if(diff)
            lines=diff->get_lines(parse_buffer.raw());
          else {
            lines.added.clear();
            lines.modified.clear();
            lines.removed.clear();
          }
          auto expected=ParseState::PROCESSING;
          if(parse_state.compare_exchange_strong(expected, ParseState::POSTPROCESSING)) {
            parse_lock.unlock();
            dispatcher.post([this] {
              std::unique_lock<std::mutex> parse_lock(parse_mutex, std::defer_lock);
              if(parse_lock.try_lock()) {
                auto expected=ParseState::POSTPROCESSING;
                if(parse_state.compare_exchange_strong(expected, ParseState::IDLE))
                  update_lines();
              }
            });
          }
        }
      }
    }
    catch(const std::exception &e) {
      dispatcher.post([this, e_what=e.what()] {
        get_buffer()->remove_tag(renderer->tag_added, get_buffer()->begin(), get_buffer()->end());
        get_buffer()->remove_tag(renderer->tag_modified, get_buffer()->begin(), get_buffer()->end());
        get_buffer()->remove_tag(renderer->tag_removed, get_buffer()->begin(), get_buffer()->end());
        get_buffer()->remove_tag(renderer->tag_removed_below, get_buffer()->begin(), get_buffer()->end());
        get_buffer()->remove_tag(renderer->tag_removed_above, get_buffer()->begin(), get_buffer()->end());
        renderer->queue_draw();
        Terminal::get().print(std::string("Error (git): ")+e_what+'\n', true);
      });
    }
  });
}

Gtk::TextIter Source::DiffView::get_iter_at_line_end(int line_nr) {
  if(line_nr>=get_buffer()->get_line_count())
    return get_buffer()->end();
  else if(line_nr+1<get_buffer()->get_line_count()) {
    auto iter=get_buffer()->get_iter_at_line(line_nr+1);
    iter.backward_char();
    if(!iter.ends_line()) // for CR+LF
      iter.backward_char();
    return iter;
  }
  else {
    auto iter=get_buffer()->get_iter_at_line(line_nr);
    while(!iter.ends_line() && iter.forward_char()) {}
    return iter;
  }
}

void Source::DiffView::git_goto_next_diff() {
  auto iter=get_buffer()->get_insert()->get_iter();
  auto insert_iter=iter;
  bool wrapped=false;
  iter.forward_char();
  for(;;) {
    auto toggled_tags=iter.get_toggled_tags();
    for(auto &toggled_tag: toggled_tags) {
      if(toggled_tag->property_name()=="git_added" ||
         toggled_tag->property_name()=="git_modified" ||
         toggled_tag->property_name()=="git_removed") {
        get_buffer()->place_cursor(iter);
        scroll_to(get_buffer()->get_insert(), 0.0, 1.0, 0.5);
        return;
      }
    }
    if(wrapped && (iter==insert_iter || iter==get_buffer()->end()))
      break;
    if(!wrapped && iter==get_buffer()->end()) {
      iter=get_buffer()->begin();
      wrapped=true;
    }
    else
      iter.forward_char();
  }
  Info::get().print("No changes found in current buffer");
}

std::string Source::DiffView::git_get_diff_details() {
  std::string details;
  if(diff) {
    auto line_nr=get_buffer()->get_insert()->get_iter().get_line();
    auto iter=get_buffer()->get_iter_at_line(line_nr);
    if(iter.has_tag(renderer->tag_removed_above))
      --line_nr;
    std::unique_lock<std::mutex> lock(parse_mutex);
    parse_buffer=get_buffer()->get_text();
    details=diff->get_details(parse_buffer.raw(), line_nr);
  }
  if(details.empty())
    Info::get().print("No changes found at current line");
  return details;
}

///Return repository diff instance. Throws exception on error
std::unique_ptr<Git::Repository::Diff> Source::DiffView::get_diff() {
  auto work_path=filesystem::get_normal_path(repository->get_work_path());
  boost::filesystem::path relative_path;
  {
    std::unique_lock<std::mutex> lock(file_path_mutex);
    relative_path=filesystem::get_relative_path(canonical_file_path, work_path);
    if(relative_path.empty())
      throw std::runtime_error("not a relative path");
  }
  return std::make_unique<Git::Repository::Diff>(repository->get_diff(relative_path));
}

void Source::DiffView::update_lines() {
  get_buffer()->remove_tag(renderer->tag_added, get_buffer()->begin(), get_buffer()->end());
  get_buffer()->remove_tag(renderer->tag_modified, get_buffer()->begin(), get_buffer()->end());
  get_buffer()->remove_tag(renderer->tag_removed, get_buffer()->begin(), get_buffer()->end());
  get_buffer()->remove_tag(renderer->tag_removed_below, get_buffer()->begin(), get_buffer()->end());
  get_buffer()->remove_tag(renderer->tag_removed_above, get_buffer()->begin(), get_buffer()->end());

  for(auto &added: lines.added) {
    auto start_iter=get_buffer()->get_iter_at_line(added.first);
    auto end_iter=get_iter_at_line_end(added.second-1);
    end_iter.forward_char();
    get_buffer()->apply_tag(renderer->tag_added, start_iter, end_iter);
  }
  for(auto &modified: lines.modified) {
    auto start_iter=get_buffer()->get_iter_at_line(modified.first);
    auto end_iter=get_iter_at_line_end(modified.second-1);
    end_iter.forward_char();
    get_buffer()->apply_tag(renderer->tag_modified, start_iter, end_iter);
  }
  for(auto &line_nr: lines.removed) {
    Gtk::TextIter removed_start, removed_end;
    if(line_nr>=0) {
      auto start_iter=get_buffer()->get_iter_at_line(line_nr);
      removed_start=start_iter;
      auto end_iter=get_iter_at_line_end(line_nr);
      end_iter.forward_char();
      removed_end=end_iter;
      get_buffer()->apply_tag(renderer->tag_removed_below, start_iter, end_iter);
    }
    if(line_nr+1<get_buffer()->get_line_count()) {
      auto start_iter=get_buffer()->get_iter_at_line(line_nr+1);
      if(line_nr<0)
        removed_start=start_iter;
      auto end_iter=get_iter_at_line_end(line_nr+1);
      end_iter.forward_char();
      removed_end=end_iter;
      get_buffer()->apply_tag(renderer->tag_removed_above, start_iter, end_iter);
    }
    get_buffer()->apply_tag(renderer->tag_removed, removed_start, removed_end);
  }

  renderer->queue_draw();
}

max_stars_repo_name: MegaApuTurkUltra/jucipp

max_issues_repo_name: MegaApuTurkUltra/jucipp

max_forks_repo_name: MegaApuTurkUltra/jucipp


text:
/*
 * StringCompare.h
 *
 *  Created on: 23 janv. 2014
 *      Author: cvallee
 */

#pragma once

#include <vector>
#include <boost/regex.hpp>

#include "DiffPrinter/diffPrinter.hh"

typedef std::vector<boost::regex> tRegexes;
typedef std::vector<std::string> tStrings;

namespace LibWsDiff {

/**
 * BasicCompare class
 * Interface providing tools for string comparaison
 */
class StringCompare {
	//Vector of regex to match in order to reject any comparaison
	tRegexes mStopRegex;
	//Vector of regex to remove from any comparaison
	tRegexes mIgnoreRegex;

protected:
	/**Check the str against the initials stop regex provided
	* @param str : the string to validate
	* @return True if any regex is match in the string else false
	*/
	bool checkStopRegex(const std::string & str) const;

	/**
	 * Remove the ignore regex content in the input string
	 * @param str : the input string
	 */
	void ignoreCases(std::string & str) const;

	/**
	 * function factoring the diff between vector of string
	 * @param src : source of the diff
	 * @param dst : destination of the diff
	 * @param output : resulting diff in string format
	 */
	bool vectDiff(const tStrings& src,const tStrings& dst, std::string& output) const;

public:
	/**
	 * Initializes the regexs through vector of string
	 */
	StringCompare(const tStrings& stopRegex,const tStrings& ignoreRegex);
	/**
	 * Default Constructor.
	 */
	StringCompare();
	virtual ~StringCompare();

    virtual void merge(const StringCompare & sc);

	/**
	 * add a new regex string to ignore in the diff
	 * @param re : the string to regex ignore in the diff
	 */
	void addIgnoreRegex(const std::string& re);

	/**
	 * add a new regex string to the stop list
	 * @param re : the string which will stop the diff if match
	 */
	void addStopRegex(const std::string& re);

	/**
	 * Return the shortest execution sequence(SES) to obtain the destination string dst from the source src i.e. the diff
	 * @param src : source string
	 * @param dst : destination string
	 * @param output : the resulting SES diff in string representation
	 * @return : false if any stop flag has been matched, else true
	 */
	bool retrieveDiff(const std::string & src,const std::string& dst, std::string& output) const;

	/**
		 * Return the shortest execution sequence(SES) to obtain the destination string dst from the source src i.e. the diff
		 * @param src : source string
		 * @param dst : destination string
		 * @param printer : Pointer on the dedicated printer class
		 * @return : false if any stop flag has been matched, else true
		 */
	bool retrieveDiff(const std::string & src,
			const std::string& dst,
			LibWsDiff::diffPrinter* printer) const;
};

/**
 * BasicCompare implementation dedicated to the HTTP header comparaison
 * Handle Map comparaison and the regex stop and ignore its own way
 */
class StringCompareHeader : public StringCompare {
	typedef std::map<std::string,std::string> mapStrings;

	/**
	 * Concatenate the map in one string
	 */
	std::string mapToHeaderString(const mapStrings& map);
public:
	/**
	 * Call the super constructor.
	 */
	StringCompareHeader(const tStrings& stopRegex,const tStrings& ignoreRegex):StringCompare(stopRegex,ignoreRegex){}

	/**
	 * Call the super constructor.
	 */
	StringCompareHeader():StringCompare(){}

	/**
	 * Split both string on their newline caractere and return line by line diff
	 * @param src : source string
	 * @param dst : destination string
	 * @param output : the resulting SES diff in string representation
	 * @return : false if any stop flag has been matched, else true
	 */
	bool retrieveDiff(const std::string& src,const std::string& dst,std::string& output) const;

	bool retrieveDiff(const mapStrings& mapOrig,
			const mapStrings& mapRes,
			std::string& output) const;

	bool retrieveDiff(const std::string& src,
			const std::string& dst,
			LibWsDiff::diffPrinter& printer) const;

	bool retrieveDiff(const mapStrings& mapOrig,
				const mapStrings& mapRes,
				LibWsDiff::diffPrinter& printer) const;
};

/**
 * BasicCompare implementation dedicated to the HTTP body comparaison
 * Handle vector of string comparaison and the regex stop and ignore its own way
 */
class StringCompareBody : public StringCompare {

public:
	/**
	 * Call the super constructor.
	 */
	StringCompareBody(tStrings stopRegex,tStrings ignoreRegex):StringCompare(stopRegex,ignoreRegex){}

	/**
	 * Call the super constructor.
	 */
	StringCompareBody():StringCompare(){}

	/**
	 * Split both string on their '><' junction and return the line by line diff
	 * Stop and Ignore regex are also process on the input strings
	 * @param src : the source string
	 * @param dst : the destination string
	 * @param output : the resulting SES diff in string representation
	 * @return : false if any stop flag has been matched, else true
	 */
	bool retrieveDiff(const std::string& src,const std::string& dst,std::string& output) const;
	/**
	 * Process the Ignore and Stop regex and every input strings
	 * @param src : source vector
	 * @param dst : destination vector
	 * @param output : the resulting SES diff in string representation
	 * @return : false if any stop flag has been matched, else true
	 */
	bool retrieveDiff(const tStrings& src,const tStrings& dst,std::string& output) const;

	/**
	 * Return the shortest execution sequence(SES) to obtain the destination string dst from the source src i.e. the diff
	 * @param src : source string
	 * @param dst : destination string
	 * @param printer : Pointer on the dedicated printer class
	 * @return : false if any stop flag has been matched, else true
	 */
	bool retrieveDiff(const std::string & src,
			const std::string& dst,
			LibWsDiff::diffPrinter& printer) const;

	bool retrieveDiff(const tStrings & src,
			const tStrings& dst,
			LibWsDiff::diffPrinter& printer) const;
};

} /* namespace LibWsDiff */

ext: hh


text:
/*
 * Copyright 2011, 2012 Esrille 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.
 */

#include "CSSImportRuleImp.h"

#include <boost/bind.hpp>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>

#include "DocumentImp.h"
#include "WindowImp.h"

#include "CSSInputStream.h"
#include "CSSParser.h"
#include "CSSStyleSheetImp.h"

#include "http/HTTPRequest.h"

#include "Test.util.h"

namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

using namespace css;

CSSImportRuleImp::CSSImportRuleImp(const std::u16string& href) :
    href(href),
    mediaList(MediaListImp::All),
    request(0),
    styleSheet(0)
{
}

CSSImportRuleImp::~CSSImportRuleImp()
{
    delete request;
}

// CSSRule
unsigned short CSSImportRuleImp::getType()
{
    return CSSRule::IMPORT_RULE;
}

std::u16string CSSImportRuleImp::getCssText()
{
    std::u16string text = u"@import url(" + href + u")";
    std::u16string media = mediaList.getMediaText();
    if (!media.empty())
        text += u" " + media;
    return text;
}

// CSSImportRule
std::u16string CSSImportRuleImp::getHref()
{
    return href;
}

stylesheets::MediaList CSSImportRuleImp::getMedia()
{
    return &mediaList;
}

void CSSImportRuleImp::setMedia(const std::u16string& media)
{
    mediaList.setMediaText(media);
}

css::CSSStyleSheet CSSImportRuleImp::getStyleSheet()
{
    if (!styleSheet && !href.empty() && !request) {  // TODO: deal with ins. mem
        request = new(std::nothrow) HttpRequest(document->getDocumentURI());
        if (request) {
            request->open(u"GET", href);
            request->setHandler(boost::bind(&CSSImportRuleImp::notify, this));
            document->incrementLoadEventDelayCount();
            request->send();
        }
    }
    return styleSheet;
}

void CSSImportRuleImp::notify()
{
    if (request->getStatus() == 200) {
#if 104400 <= BOOST_VERSION
        boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), boost::iostreams::never_close_handle);
#else
        boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), false);
#endif
        CSSParser parser;
        CSSInputStream cssStream(stream, request->getResponseMessage().getContentCharset(), utfconv(document->getCharset()));
        styleSheet = parser.parse(document, cssStream);
        if (auto imp = dynamic_cast<CSSStyleSheetImp*>(styleSheet.self()))
            imp->setParentStyleSheet(getParentStyleSheet());
        if (4 <= getLogLevel())
            dumpStyleSheet(std::cerr, styleSheet.self());
    }
    document->decrementLoadEventDelayCount();

    if (WindowImp* view = document->getDefaultWindow())
        view->setFlags(1);
}

}
}
}
}

max_stars_repo_name: rvedam/es-operating-system

max_issues_repo_name: LambdaLord/es-operating-system

max_forks_repo_name: LambdaLord/es-operating-system


text:
/** $Id: histogram.cxx 172050 2019-03-15 12:47:22Z flauber $
 * @file
 * @author Jakob van Santen <vansanten@wisc.edu>
 *
 * $Revision: 172050 $
 * $Date: 2019-03-15 06:47:22 -0600 (Fri, 15 Mar 2019) $
 */

#include <MuonGun/histogram.h>
#include <boost/foreach.hpp>
#include <boost/python/slice.hpp>

namespace bp = boost::python;

#if PY_MAJOR_VERSION >= 3
static PyObject *
PyBuffer_FromMemory(void *memory, size_t size)
{
	Py_buffer buf;
	memset(&buf, 0, sizeof(buf));
	buf.buf = memory;
	buf.len = size;
	buf.readonly = true;
	buf.ndim = 1;
	buf.itemsize = sizeof(double);
        size_t s= size/sizeof(double);
        assert(s<= INT_MAX);
	Py_ssize_t shape[] = { static_cast<Py_ssize_t>(s) };
	buf.shape = shape;
	return PyMemoryView_FromBuffer(&buf);
}
#endif

static bp::object
to_dashi(boost::shared_ptr<I3MuonGun::histogram::histogram_base> h)
{
	bp::object histmodule = bp::import("dashi.histogram");
	bp::object numpy = bp::import("numpy");
	bp::list edges;
	BOOST_FOREACH(const std::vector<double> &dim, h->binedges())
		edges.append(bp::list(dim));

	bp::object dhist = histmodule.attr("histogram")(h->ndim(), edges);

	bp::list shape;
	size_t ndim = h->ndim(); (void) ndim;
	size_t tsize = 1;
	BOOST_FOREACH(size_t i, h->shape()) {
		tsize *= i;
		shape.append(i);
	}
	bp::tuple shapet(shape);
	bp::object dtype = numpy.attr("float64");

	bp::object buffer = bp::object(bp::handle<>(PyBuffer_FromMemory(
	    (void*)h->raw_bincontent(), sizeof(double)*tsize)));
	dhist.attr("_h_bincontent").attr("__setitem__")(bp::slice(),
	    numpy.attr("ndarray")(shapet, dtype, buffer));

	buffer =  bp::object(bp::handle<>(PyBuffer_FromMemory(
	    (void*)h->raw_squaredweights(), sizeof(double)*tsize)));
	dhist.attr("_h_squaredweights").attr("__setitem__")(bp::slice(),
	    numpy.attr("ndarray")(shapet, dtype, buffer));

	return dhist;
}

static boost::shared_ptr<I3MuonGun::histogram::histogram_base> test_histogram()
{
	using namespace I3MuonGun::histogram;

	histogram<3>::bin_specification edges;
	{
		using namespace binning;
		// edges[0] = uniform<>::create(0, 1, 11);
		edges[0] = uniform<cosine>::create(0, M_PI/2., 11);
		// edges[0] = boost::get<boost::shared_ptr<binning::scheme> >(edges[0])->edges();
		edges[1] = uniform<binning::log10>::create(1e3, 1e5, 11);
		edges[2] = uniform<power<2> >::create(1, 10, 11);
	}

	boost::shared_ptr<histogram<3> > h(new histogram<3>(edges));

	boost::array<double, 3> values = {{0.5, 1e4, 8}};

	for (int i=0; i < 25; i++) {
		values[0] = 1e-1*i;
		h->fill(values);
	}

	return h;
}

void register_histogram()
{
	using namespace I3MuonGun::histogram;
	namespace bp = boost::python;

	bp::def("test_histogram", &test_histogram);

	bp::class_<histogram_base, boost::shared_ptr<histogram_base>, boost::noncopyable>("histogram", bp::no_init)
		.def("to_dashi", &to_dashi)
			;
	try {
		bp::import("dashi.histogram");
		bp::import("numpy");
	} catch (const bp::error_already_set&) {

		PyErr_Clear();
	}

}


text:
/**********************************************************************
 *  Copyright (c) 2008-2016, Alliance for Sustainable Energy.
 *  All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 **********************************************************************/

#ifndef OPENSTUDIO_LOCATIONTABCONTROLLER_HPP
#define OPENSTUDIO_LOCATIONTABCONTROLLER_HPP

#include "../model/Model.hpp"

#include "MainTabController.hpp"

#include <boost/smart_ptr.hpp>

#include <QDir>
#include <QObject>

class QStackedWidget;

namespace openstudio {

class LocationTabView;

class UtilityBillsController;

class LocationTabController : public MainTabController
{
  Q_OBJECT

public:

  LocationTabController(bool isIP,
    const model::Model& model,
    const QString& modelTempDir);

  virtual ~LocationTabController();

  enum TabID
  {
    WEATHER_FILE,
    LIFE_CYCLE_COSTS,
    UTILITY_BILLS
  };

private:

  bool showUtilityBills();

  QString m_modelTempDir;

  model::Model m_model;

  bool m_isIP;

  QWidget * m_currentView = nullptr;

  int m_currentIndex = -1;

private slots:

  virtual void setSubTab(int index) override;

};

} // openstudio

#endif // OPENSTUDIO_LOCATIONTABCONTROLLER_HPP

max_stars_repo_name: jasondegraw/OpenStudio

max_issues_repo_name: jasondegraw/OpenStudio

max_forks_repo_name: jasondegraw/OpenStudio