Example #1
0
void I2PControlService::HandleRequestReceived(
    const boost::system::error_code& ecode,
    size_t bytes_transferred,
    std::shared_ptr<boost::asio::ip::tcp::socket> socket,
    std::shared_ptr<I2PControlBuffer> buf) {
  if (ecode) {
    LogPrint(eLogError, "I2PControl read error: ", ecode.message());
    return;
  }
  try {
    bool isHtml = !memcmp(buf->data(), "POST", 4);
    std::stringstream ss;
    ss.write(buf->data(), bytes_transferred);
    if (isHtml) {
      std::string header;
      while (!ss.eof() && header != "\r")
        std::getline(ss, header);
      if (ss.eof()) {
        LogPrint(eLogError,
            "Malformed I2PControl request. HTTP header expected");
        return;  // TODO(anonimal): implement
      }
    }
    I2PControlSession::Response response =
      m_Session->HandleRequest(ss);
    SendResponse(socket, buf, response.ToJsonString(), isHtml);
  } catch (const std::exception& ex) {
    LogPrint(eLogError, "I2PControl handle request: ", ex.what());
  } catch (...) {
    LogPrint(eLogError, "I2PControl handle request unknown exception");
  }
}
Example #2
0
std::shared_ptr<Matrix> ASD<VecType>::compute_1e_prop(std::shared_ptr<const Matrix> hAA, std::shared_ptr<const Matrix> hBB, std::shared_ptr<const Matrix> hAB, const double core) const {

    auto out = std::make_shared<Matrix>(dimerstates_, dimerstates_);

    for (auto iAB = subspaces_.begin(); iAB != subspaces_.end(); ++iAB) {
        const int ioff = iAB->offset();
        for (auto jAB = subspaces_.begin(); jAB != iAB; ++jAB) {
            const int joff = jAB->offset();

// TODO remove this comment once the gammaforst issue has been fixed (bra and ket have been exchanged)
            std::array<MonomerKey,4> keys {{
                    jAB->template monomerkey<0>(), jAB->template monomerkey<1>(),
                    iAB->template monomerkey<0>(), iAB->template monomerkey<1>()
                }};
            std::shared_ptr<Matrix> out_block = compute_offdiagonal_1e(keys, hAB);

            out->add_block(1.0, joff, ioff, out_block->ndim(), out_block->mdim(), out_block);
            out->add_block(1.0, ioff, joff, out_block->mdim(), out_block->ndim(), out_block->transpose());
        }
        std::shared_ptr<const Matrix> tmp = compute_diagonal_1e(*iAB, hAA->data(), hBB->data(), core);
        out->add_block(1.0, ioff, ioff, tmp->ndim(), tmp->mdim(), tmp);
    }

    return out;
}
Example #3
0
void ProcessingContextImpl::ProcessDataBlockPhase1(
    std::shared_ptr<DataBlock> data_block) {
  size_t data_size = backup_buffer_.size() + data_block->size();
  if (data_size > search_text_.size() - 1)
    data_size -= search_text_.size() - 1;
  else
    data_size = 0;
  for (size_t data_index = 0; data_index < data_size; ++data_index) {
    bool is_equal;
    for (size_t text_index = 0; text_index < search_text_.size(); ++text_index) {
      size_t char_index = data_index + text_index;
      char ch;
      if (char_index < backup_buffer_.size()) {
        ch = backup_buffer_[char_index];
      } else {
        char_index -= backup_buffer_.size();
        ch = data_block->data()[char_index];
      }
      is_equal = (ch == search_text_[text_index]);
      if (!is_equal)
        break;
    }
    if (is_equal) {
      found_.push_back(current_offset_ + data_index - backup_buffer_.size());
      data_index += search_text_.size() - 1;
    }
  }
  current_offset_ += data_block->size();
  if (backup_buffer_.size() < search_text_.size() - 1)
    backup_buffer_.resize(search_text_.size() - 1);
  if (backup_buffer_.size() <= data_block->size())
    memcpy(backup_buffer_.data(),
           data_block->data() + data_block->size() - backup_buffer_.size(),
           backup_buffer_.size());
}
Example #4
0
void I2PControlService::SendResponse(std::shared_ptr<boost::asio::ip::tcp::socket> socket,
    std::shared_ptr<I2PControlBuffer> buf, const std::string& response, bool isHtml)
{
    size_t len = response.length(), offset = 0;
    if(isHtml) {
        std::ostringstream header;
        header << "HTTP/1.1 200 OK\r\n";
        header << "Connection: close\r\n";
        header << "Content-Length: " << boost::lexical_cast<std::string>(len) << "\r\n";
        header << "Content-Type: application/json\r\n";
        header << "Date: ";
        auto facet = new boost::local_time::local_time_facet("%a, %d %b %Y %H:%M:%S GMT");
        header.imbue(std::locale(header.getloc(), facet));
        header << boost::posix_time::second_clock::local_time() << "\r\n"; 
        header << "\r\n";
        offset = header.str().size();
        memcpy(buf->data(), header.str().c_str(), offset);
    }   
    memcpy(buf->data() + offset, response.c_str(), len);
    boost::asio::async_write(
        *socket, boost::asio::buffer(buf->data(), offset + len), 
        boost::asio::transfer_all(), std::bind(
            &I2PControlService::HandleResponseSent, this, 
            std::placeholders::_1, std::placeholders::_2, socket, buf
        )
    );
}
		void PeerComm::HandleHandshake(std::shared_ptr<std::array<char, 68>> buffer, const boost::system::error_code& error)
		{
			std::unique_lock<std::mutex> _(m_Mutex);

			if ((*buffer)[0] != 19)
			{
				m_State = PeerCommState::Error;
				return;
			}
			std::string protocolId(buffer->data() + 1, 19);
			if (protocolId != "BitTorrent protocol")
			{
				m_State = PeerCommState::Error;
				return;
			}

			std::string infoHash(buffer->data() + 28, 20);
			if (infoHash != m_InfoHash)
			{
				std::cout << "bad info_hash" << std::endl;
				m_State = PeerCommState::Error;
				return;
			}

			std::string peerId(buffer->data() + 48, 20);
			m_PeerID = peerId;

			m_State = PeerCommState::Choked;
			QueueReceiveMessage();
		}
Example #6
0
			static inline
			bool
			nearEqual(std::shared_ptr<Matrix4x4> m1, std::shared_ptr<Matrix4x4> m2, float epsilon = 1e-6f)
			{
				for (auto i = 0; i < 16; ++i)
					if (!nearEqual(m1->data()[i], m2->data()[i], epsilon))
						return false;
				return true;
			}
Example #7
0
 polynomial operator+(const polynomial<T>& o) const
 {
   int len;
   const polynomial<T> *p;
   size() >= o.size() ? (p=this, len=size()) : (p=&o, len=o.size());
   polynomial<T> out(len);
   std::transform(vals->data(),vals->data()+std::min(size(),o.size()),o.vals->data(),out.vals->data(),[](T a, T b){return a+b;});
   if (size() != o.size()) std::copy_n(&p->element(std::min(size(),o.size())),abs(size()-o.size()),&out(std::min(size(),o.size())));
   return out;
 }
				void OnMouseImg(std::shared_ptr<Utilities::Image> img) {
					if (!LastMouse) {
						_ServerNetworkDriver.SendMouse(nullptr, *img);
					}
					else {
                        if(LastMouse->size() != img->size()) {
                            _ServerNetworkDriver.SendMouse(nullptr, *img);
                        } else if (memcmp(img->data(), LastMouse->data(), LastMouse->size()) != 0) {
							_ServerNetworkDriver.SendMouse(nullptr, *img);
						}
					}
					LastMouse = img;
				}
void
AbstractDiscreteLight::targetAddedHandler(AbstractComponent::Ptr cmp, std::shared_ptr<scene::Node> target)
{
	AbstractLight::targetAddedHandler(cmp, target);

	_modelToWorldChangedSlot = target->data()->propertyValueChanged("transform.modelToWorldMatrix")->connect(std::bind(
		&AbstractDiscreteLight::modelToWorldMatrixChangedHandler,
		std::dynamic_pointer_cast<AbstractDiscreteLight>(shared_from_this()),
		std::placeholders::_1,
		std::placeholders::_2
	));

	if (target->data()->hasProperty("transform.modelToWorldMatrix"))
		updateModelToWorldMatrix(target->data()->get<math::Matrix4x4::Ptr>("transform.modelToWorldMatrix"));
}
Example #10
0
 polynomial operator-(const polynomial<T>& o) const
 {
   int len, sign;
   int min = std::min(size(),o.size());
   const polynomial<T> *p;
   size() >= o.size() ? (p=this, len=size(), sign=1) : (p=&o, len=o.size(), sign=-1);
   polynomial<T> out(len);
   std::transform(vals->data(),vals->data()+min,o.vals->data(),out.vals->data(),[](T a, T b){return a-b;});
   if (size() != o.size())
   {
     std::copy_n(&p->element(min),abs(size()-o.size()),&out(min));
     if (sign == -1) std::transform(&out(min),&out(min)+abs(size()-o.size()),&out(min),[](T a){return -1.0*a;});
   }
   return out;
 }
Example #11
0
void
AbstractDiscreteLight::targetAdded(std::shared_ptr<scene::Node> target)
{
	AbstractLight::targetAdded(target);

	_modelToWorldChangedSlot = target->data().propertyChanged("modelToWorldMatrix").connect(std::bind(
		&AbstractDiscreteLight::modelToWorldMatrixChangedHandler,
		std::static_pointer_cast<AbstractDiscreteLight>(shared_from_this()),
		std::placeholders::_1,
        std::placeholders::_3
	));

	if (target->data().hasProperty("modelToWorldMatrix"))
		updateModelToWorldMatrix(target->data().get<math::mat4>("modelToWorldMatrix"));
}
Example #12
0
void Client::ClientSession::DoWriteUDP(std::shared_ptr<std::string> data, const udp::endpoint& endpoint)
{
    socket_udp_.async_send_to(
        boost::asio::buffer(data->data(), data->size()), endpoint,
        boost::bind(&Client::ClientSession::WriteUDP, this,
          boost::asio::placeholders::error));
}
Example #13
0
void Conn::onRead(const boost::system::error_code& error, std::shared_ptr< boost::asio::streambuf > rd_buf) {
	if( unlikely(error) ) {
		log_func("[iproto_conn] %s:%u read error: %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str() );
		dismissCallbacks(CB_ERR);
		if( error != boost::asio::error::operation_aborted ) {
			reconnect();
		}
		return;
	}
	if( unlikely(!rd_buf) )
		rd_buf.reset(new boost::asio::streambuf);
	if( LOG_DEBUG )
		log_func("[iproto_conn] %s:%u onRead rd_buf->size=%zu", ep.address().to_string().c_str(), ep.port(), rd_buf->size());
	while( rd_buf->size() >= sizeof(Header) ) {
		const PacketPtr *buf = boost::asio::buffer_cast< const PacketPtr * >( rd_buf->data() );
		if( LOG_DEBUG )
			log_func("[iproto_conn] %s:%u onRead buffer iproto packet hdr: len=%u sync=%u msg=%u", ep.address().to_string().c_str(), ep.port(),
				buf->hdr.len, buf->hdr.sync, buf->hdr.msg);
		size_t want_read = sizeof(Header)+buf->hdr.len;
		if( want_read <= rd_buf->size() ) {
			invokeCallback(buf->hdr.sync, RequestResult(CB_OK, Packet(buf)) );
			rd_buf->consume( sizeof(Header) + buf->hdr.len );
		}else{
			size_t rd = want_read - rd_buf->size();
			if( LOG_DEBUG )
				log_func("[iproto_conn] %s:%u onRead want_read=%zu", ep.address().to_string().c_str(), ep.port(), rd);
			boost::asio::async_read(sock, *rd_buf, boost::asio::transfer_at_least(rd),
				boost::bind(&Conn::onRead, shared_from_this(), boost::asio::placeholders::error, rd_buf) );
			return;
		}
	}
	if( likely(sock.is_open()) )
		boost::asio::async_read(sock, *rd_buf, boost::asio::transfer_at_least(sizeof(Header)-rd_buf->size()),
			boost::bind(&Conn::onRead, shared_from_this(), boost::asio::placeholders::error, rd_buf) );
}
std::shared_ptr<STTx const>
TransactionMaster::fetch (std::shared_ptr<SHAMapItem> const& item,
    SHAMapTreeNode::TNType type,
        bool checkDisk, std::uint32_t uCommitLedger)
{
    std::shared_ptr<STTx const>  txn;
    auto iTx = fetch (item->key(), false);

    if (!iTx)
    {

        if (type == SHAMapTreeNode::tnTRANSACTION_NM)
        {
            SerialIter sit (item->slice());
            txn = std::make_shared<STTx const> (std::ref (sit));
        }
        else if (type == SHAMapTreeNode::tnTRANSACTION_MD)
        {
            auto blob = SerialIter{item->data(), item->size()}.getVL();
            txn = std::make_shared<STTx const>(SerialIter{blob.data(), blob.size()});
        }
    }
    else
    {
        if (uCommitLedger)
            iTx->setStatus (COMMITTED, uCommitLedger);

        txn = iTx->getSTransaction ();
    }

    return txn;
}
Example #15
0
std::string
GeometryWriter::serializeVertexStream(std::shared_ptr<render::VertexBuffer> vertexBuffer)
{
	std::list<render::VertexBuffer::AttributePtr>									attributes			= vertexBuffer->attributes();
	std::vector<msgpack::type::tuple<std::string, unsigned char, unsigned char>>	serializedAttributes;
	
	auto attributesIt = attributes.begin();
	
	while (attributesIt != attributes.end())
	{
		serializedAttributes.push_back(msgpack::type::tuple<std::string, unsigned char, unsigned char>(
			std::get<0>((**attributesIt)), 
			std::get<1>((**attributesIt)), 
			std::get<2>((**attributesIt))));

		attributesIt++;
	}

	std::string serializedVector = serialize::TypeSerializer::serializeVector<float>(vertexBuffer->data());

	std::stringstream			sbuf;
	msgpack::type::tuple<std::string, std::vector<msgpack::type::tuple<std::string, unsigned char, unsigned char>>> res(
		serializedVector,
		serializedAttributes);

	msgpack::pack(sbuf, res);

	return sbuf.str();
}
Example #16
0
void work_manager::submit_work(const std::shared_ptr<stratum_work> & val)
{
    /**
     * Update the statistics.
     */
    stack_impl_.update_statistics();
    
    auto time = utility::to_hex(val->time());
    
    std::uint32_t nonce_little = utility::le32dec(&val->data()[19]);

    auto nonce = utility::to_hex(
        reinterpret_cast<std::uint8_t *>(&nonce_little),
        reinterpret_cast<std::uint8_t *>(&nonce_little) + sizeof(std::uint32_t)
    );
    
    auto extranonce2 = utility::to_hex(val->extranonce2());

    std::string json_line =
        "{\"params\": [\"" + val->worker_name() +
        "\", \"" + val->job_id() + "\", \"" + extranonce2 + "\", \"" + time +
        "\", \"" + nonce + "\"], \"id\": 4, \"method\": \"mining.submit\"}\n"
    ;

    for (auto & i : stratum_connections_)
    {
        if (auto j = i.lock())
        {
            j->write(json_line);
        }
    }
}
Example #17
0
static std::function<typename sample_type::array_type const&()>
wrap_get(std::shared_ptr<sample_type> self)
{
    return [self]() -> typename sample_type::array_type const&
    {
        return self->data();
    };
}
				void OnScreen(std::shared_ptr<Utilities::Image> img) {
					if (!_NewClients.empty()) {
						//make sure to send the full screens to any new connects
						std::lock_guard<std::mutex> lock(_NewClientLock);
						for (auto& a : _NewClients) {
							_ServerNetworkDriver.SendScreenFull(a.get(), *img);
						}
						_NewClients.clear();
					}
					if (LastScreen) {
						if (img->data() != LastScreen->data()) {
							for (auto r : SL::Remote_Access_Library::Utilities::Image::GetDifs(*LastScreen, *img)) {
								_ServerNetworkDriver.SendScreenDif(nullptr, r, *img);
							}
						}
					}
					LastScreen = img;//swap
				}
Example #19
0
void TcpSession::handle_read(std::shared_ptr<TcpSession> s, std::shared_ptr<ByteArray> d, const boost::system::error_code &error, size_t bytes_transferred) {

	if (!error) {
		ByteArray read(reinterpret_cast<const unsigned char*>(d->data()),bytes_transferred);

		handleIncoming(read);

		scheduleRead();
	}
}
Example #20
0
	polymorph_factory_manufacturer_holder(
		const manager_data& parent_data,
		Context context
	): manager(
		parent_data.factory_builder->make_manager(
			parent_data.factory_data,
			source_traits.context_data(context)
		)
	), data(parent_data, manager->data())
	{ }
void UdpSocket::asyncReceive(boost::asio::ip::udp::socket *sock,
		std::shared_ptr<std::array<uint8_t, 65536>> recvbuffer) {
	boost::lock_guard<boost::recursive_mutex> guard(commonMutex_);
	auto endpoint = std::make_shared<udp::endpoint>();
	sock->async_receive_from(
			boost::asio::mutable_buffers_1(recvbuffer->data(), recvbuffer->size()),
			*endpoint,
			boost::bind(&UdpSocket::handleReceive, std::weak_ptr<UdpSocket>(shared_from_this()),
					boost::asio::placeholders::error,
					boost::asio::placeholders::bytes_transferred, endpoint,
					sock, recvbuffer));
}
void SL::Remote_Access_Library::UI::MainWindow::Update(Network::Commands::ImageChange * info, std::shared_ptr<Utilities::Image>& img)
{
	auto h(0), w(0);
	if (image != nullptr) {
		h = image->h();
		w = image->w();
	}
	if (image == nullptr || info->height >= h || info->width >= w) {	
		delete image;
		image = new Fl_RGB_Image((unsigned char*)img->data(), info->width, info->height, 3, info->width * 3);
		img_box->image(image);
		img_box->size(info->width, info->height);
	}
	else if (info->height < h && info->width < w) {
		for (auto i = 0; i < info->width; i++) {
			auto ptr = image->array + (info->left * 4) + (info->top*image->w() * 4);
			memcpy((void*)ptr, img->data() + (i*info->width * 4), info->width * 4);
		}
	}
	img_box->redraw();
	Fl::check();

}
std::shared_ptr<Effect> ResourceLoader::build<Effect>(std::shared_ptr<File> file)
{
	std::string loc = "";

	EffectLoaderBypass bypass(loc);

	xeffect::XEffectLoader loader;

	loader.setLoadFileCallback(std::bind(&EffectLoaderBypass::loadFileResource, bypass, std::placeholders::_1));

	std::shared_ptr<Effect> effect = loader.loadFromSource(file->data());

	return effect;
}
Example #24
0
	inline polymorph_factory_manufacturer_holder(
		const manufacturer_data& parent_data,
		ConstructionInfo construction_info
	): arrayer(
		parent_data.factory_builder->make_arrayer(
			parent_data.factory_data,
			source_traits.product_meta_data(
				typename reflected<Element>::type()
			),
			source_traits.context_data(
				typename ConstructionInfo::context()
			)
		)
	), data(parent_data, arrayer->data())
	 , producer(data, construction_info)
	{
		arrayer->assign_producer(producer);
	}
Example #25
0
void RegexSearch::ProcessDataBlockPhase1(
    std::shared_ptr<DataBlock> data_block) {
  sre_int_t* pending_matches;
  sre_char* ch_ptr = data_block->data();
  for (uint32_t offset = 0; offset < data_block->size(); ++offset, ++ch_ptr) {
    sre_int_t res = sre_vm_pike_exec(sre_ctx_, ch_ptr, 1, 0, &pending_matches);
    if (res >= 0) {
      Result result;
      result.offset = matches_[0] + block_offset_;
      result.size = matches_[1] - matches_[0];
      found_.push_back(result);
    } else if (res == SRE_DECLINED) {
    } else if (res == SRE_AGAIN) {
    } else {
      assert(false);
    }
  }
  block_offset_ += data_block->size();
}
Example #26
0
File: main.cpp Project: CCJY/coliru
        void draw_text(double x, double y, std::string text, std::shared_ptr<color_rgb> color){
            std::lock_guard<std::mutex> lock(texture_mutex);
            (*texture_data) = (*texture_clear_buffer);

//            const unsigned char black[] = { 0, 0, 0};

            cimg_library::CImg<unsigned char> imgtext =
                    cimg_library::CImg<unsigned char>().draw_text(0,0,text.c_str(), color->data(), NULL).
                            resize(-100,-100, 1, 4);

            //@TODO move this to widget.hpp and implement alignment.
            (*texture_data).draw_image(x - imgtext.width()/2,
                                       y - imgtext.height()/2,
                                       0,
                                       0,
                                       imgtext,
                                       imgtext.get_channel(3),
                                       1,
                                       255);

        }
Example #27
0
vector<double> compute_ssf(
    std::shared_ptr<position_sample_type> position_sample
  , vector<vector_type> const& wavevector
)
{
    unsigned nq = wavevector.size();
    vector<double> ssf(nq);
    vector<double> cos_(nq, 0);
    vector<double> sin_(nq, 0);
    size_t npart = position_sample->data().size();
    BOOST_FOREACH(typename position_sample_type::data_type const& r, position_sample->data()) {
        for (unsigned j = 0; j < nq; ++j) {
            double qr = inner_prod(wavevector[j], static_cast<vector_type>(r));
            cos_[j] += cos(qr);
            sin_[j] += sin(qr);
        }
    }
    for (size_t j = 0; j < nq; ++j) {
        ssf[j] = (cos_[j] * cos_[j] + sin_[j] * sin_[j]) / npart;
    }
    return ssf;
}
void UdpSocket::handleReceive(std::weak_ptr<UdpSocket> ptr, const boost::system::error_code &err,
		size_t bytesTransferred,
		std::shared_ptr<boost::asio::ip::udp::endpoint> endpoint,
		boost::asio::ip::udp::socket *sock,
		std::shared_ptr<std::array<uint8_t, 65536>> recvbuffer) {
	std::shared_ptr<UdpSocket> sockPtr = ptr.lock();
	if(!sockPtr) {
		// The UdpSocket has been destroyed or has errored out, no need to keep receiving
		return;
	}

	boost::lock_guard<boost::recursive_mutex> guard(sockPtr->commonMutex_);
	if (!err) {
		auto buffer = std::make_shared<Buffer>();
		buffer->write(recvbuffer->data(), bytesTransferred);
		boost::system::error_code ec;
		sockPtr->receivequeue_.push(QueueItem(buffer, endpoint->address().to_string(ec), endpoint->port()));
	}

	if(sock->is_open()) {
		sockPtr->asyncReceive(sock, recvbuffer);
	}
}
std::shared_ptr<SL::Remote_Access_Library::Utilities::Image> SL::Remote_Access_Library::Utilities::Image::Resize(const std::shared_ptr<Image>& inimg, int height, int width, Image_Resamples resample)
{
	UNUSED(resample);
	/*
	TODO ADD SUPPORT FOR LINEAR AND BICUBIC RESAMPLE.. They are in commented out code above and below
	*/

	auto m_width = width;
	auto m_height = height;
	auto outimg = CreateImage(m_height, m_width);
	auto temp = (int*)outimg->data();
	auto pixels = (int*)inimg->data();
	double x_ratio = inimg->Width() / (double)m_width;
	double y_ratio = inimg->Height() / (double)m_height;
	double px, py;
	for (int i = 0; i < m_height; i++) {
		for (int j = 0; j < m_width; j++) {
			px = floor(j*x_ratio);
			py = floor(i*y_ratio);
			temp[(i*m_width) + j] = pixels[(int)((py*inimg->Width()) + px)];
		}
	}
	return outimg;
}
Example #30
0
void print_live_query(std::shared_ptr<meteorpp::live_query> const& live_query)
{
    std::system("clear");
    std::cout << live_query->data().dump(4) << std::endl;
}