text: #include <boost/ptr_container/ptr_circular_buffer.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * Copyright (c) 2020 Karim, karimdavoodi@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include <exception>
#include <thread>
#include <boost/log/trivial.hpp>
#include "gst.hpp"
#include "utils.hpp"
using namespace std;
struct ProbData {
    int buffer_count;
    GstBus* bus;
    GstElement* src;
};

void uridecodebin_pad_added_s(GstElement* object, GstPad* pad,
                            gpointer data);
GstPadProbeReturn filesink_get_buffer(
                            GstPad *pad,
                            GstPadProbeInfo *info,
                            gpointer user_data);

/*
 *   The Gstreamer main function
 *   Got snapshot from udp:://in_multicast:port
 *
 *   @param in_multicast : multicast of input stream
 *   @param port: output multicast port numper
 *   @param pic_path: the path of snapshot image
 *
 * */
bool gst_capture_udp_in_jpg(string in_multicast, int port, string pic_path)
{
    Gst::Data d;
    d.loop = g_main_loop_new(nullptr, false);
    d.pipeline = GST_PIPELINE(gst_element_factory_make("pipeline", nullptr));
    string uri = "udp://" + in_multicast + ":" + to_string(port);
    LOG(info) << "Start " << uri << " --> " << pic_path;

    try{
        auto uridecodebin   = Gst::add_element(d.pipeline, "uridecodebin"),
             capsfilter     = Gst::add_element(d.pipeline, "capsfilter", "capsfilter"),
             //videoconvert   = Gst::add_element(d.pipeline, "videoconvert"),
             jpegenc        = Gst::add_element(d.pipeline, "jpegenc"),
             filesink       = Gst::add_element(d.pipeline, "filesink");

        gst_element_link_many(capsfilter, jpegenc, filesink, nullptr);

        g_object_set(uridecodebin, "uri", uri.c_str(), nullptr);
        //g_object_set(jpegenc, "snapshot", true, nullptr);
        g_object_set(filesink, "location", pic_path.c_str(), nullptr);
        auto caps = gst_caps_from_string("video/x-raw");
        g_object_set(capsfilter, "caps", caps, nullptr);
        gst_caps_unref(caps);

        g_signal_connect(uridecodebin, "pad-added",G_CALLBACK(uridecodebin_pad_added_s),
                                                &d);

        Gst::add_bus_watch(d);
        ProbData pd { 0, d.bus, uridecodebin  };
        auto filesink_pad = gst_element_get_static_pad(filesink, "sink");
        gst_pad_add_probe(filesink_pad, GST_PAD_PROBE_TYPE_BUFFER,
                GstPadProbeCallback(filesink_get_buffer), &pd, nullptr);

        LOG(debug) << "Wait to snapshot:" << SNAPSHOT_TIMEOUT;
        bool thread_running = true;
        std::thread t([&](){
                int counter = 60;
                while(thread_running && counter-- ) Util::wait(500);
                if(!d.pipeline || !d.loop || !thread_running) return;
                if(GST_OBJECT_REFCOUNT_VALUE(d.pipeline) == 0 ) return;
                LOG(debug) << "Pipeline timeout reached";
                g_main_loop_quit(d.loop);
                });
        gst_element_set_state(GST_ELEMENT(d.pipeline), GST_STATE_PLAYING);
        g_main_loop_run(d.loop);
        thread_running = false;
        t.join();

        gst_element_set_state(GST_ELEMENT(d.pipeline), GST_STATE_NULL);
        gst_object_unref(filesink_pad);
        return pd.buffer_count > 1 ;
    }catch(std::exception& e){
        LOG(error) << e.what();
        return false;
    }
}
GstPadProbeReturn filesink_get_buffer(
        GstPad * /*pad*/,
        GstPadProbeInfo * /*info*/,
        gpointer user_data)
{
    auto d = (ProbData *)user_data;
    LOG(debug) << "Got Buffer in filesink";
    d->buffer_count++;
    if(d->buffer_count > 1){
        gst_bus_post(d->bus, gst_message_new_eos(GST_OBJECT(d->src)));
        LOG(debug) << "Post EOS message";
    }
    return GST_PAD_PROBE_OK;
}
void uridecodebin_pad_added_s(GstElement* /*object*/, GstPad* pad, gpointer data)
{
    auto d = (Gst::Data *)data;
    auto pad_type = Gst::pad_caps_type(pad);
    LOG(debug) << "pad type:" << pad_type;
    if(pad_type.find("video") != string::npos){
        LOG(debug) << "try to link to capsfilter";
        auto capsfilter = gst_bin_get_by_name(GST_BIN(d->pipeline), "capsfilter");
        Gst::pad_link_element_static(pad, capsfilter, "sink");
        gst_object_unref(capsfilter);
    }else{
        //auto fakesink = Gst::add_element(d->pipeline, "fakesink", "", true);
        //Gst::pad_link_element_static(pad, fakesink, "sink");
    }
}

ext: cpp


text:
#include "client.h"
#include <boost/asio/ssl.hpp>
#include <range/v3/all.hpp>
#include <boost/beast.hpp>
#include <utility>

namespace cacheless {

client::client(int threads, intents intents) :
	m_intents(intents) ,
	m_threads(std::max(threads - 1, 0)),
	m_ioc(std::in_place_type<boost::asio::io_context>, threads){}

client::client(boost::asio::io_context& ioc, intents intents) :
	m_intents(intents),
	m_ioc(std::in_place_type<boost::asio::io_context*>, &ioc){}

void client::run() {

	do_gateway_stuff();
	//m_th

	boost::asio::executor_work_guard work_guard(context().get_executor());
	ranges::generate(m_threads, [&]() {
		return std::thread([&]() {
			context().run();
			});
		});

	context().run();
	int u = 0;
}

void client::stop() {
	context().stop();
}

void client::set_token(std::string token, const token_type type) {
	m_token = token;
	switch (type) {
	case token_type::BOT: m_authToken = "Bot " + std::move(token);
		break;
	case token_type::BEARER: m_authToken = "Bearer " + std::move(token);
		break;
	default: break;
	}
}

void client::rate_limit_global(const std::chrono::system_clock::time_point tp) {
	std::unique_lock<std::mutex> locky(m_global_rate_limit_mut, std::try_to_lock);
	//only 1 shard needs to call this to rate limit every shard
	if (!locky) {
		return;
	}
	const auto now = std::chrono::system_clock::now();
	if (m_last_global_rate_limit - now < std::chrono::seconds(3)) {//so i don't rate_limit myself twice
		m_last_global_rate_limit = now;
		//for (auto& shard : m_shards) {
		//	shard->rate_limit(tp);
		//}
	}
}

void client::do_gateway_stuff() {
	m_getGateway();
	for (int i = 0; i < m_num_shards; ++i) {
		m_shards.emplace_back(std::make_unique<internal_shard>(i, this, context(), m_gateway, m_intents));
	}
}

void client::m_getGateway() {
	boost::asio::io_context ioc;//m_ioc.run is called after this finishes, so need a different ioc
	boost::asio::ip::tcp::resolver resolver{ ioc };

	boost::asio::ssl::context ssl_context{ boost::asio::ssl::context::tlsv12_client };
	boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_socket{ ioc, ssl_context };
	boost::beast::flat_buffer buffer;

	boost::asio::connect(ssl_socket.next_layer(), resolver.resolve("discord.com", "https"));
	ssl_socket.handshake(boost::asio::ssl::stream_base::client);
	boost::beast::http::request<boost::beast::http::string_body> request(boost::beast::http::verb::get, "/api/v8/gateway/bot", 11);
	request.set("Application", "cerwy");
	request.set(boost::beast::http::field::authorization, m_authToken);
	request.set("Host", "discord.com"s);
	request.set("Upgrade-Insecure-Requests", "1");
	request.set(boost::beast::http::field::user_agent, "potato_world");

	request.keep_alive(true);

	request.set(boost::beast::http::field::accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
	//request.set(boost::beast::http::field::accept_encoding, "gzip,deflate,br");

	request.set(boost::beast::http::field::accept_language, "en-US,en;q=0.5");

	request.prepare_payload();
	boost::beast::http::write(ssl_socket, request);
	boost::beast::http::response<boost::beast::http::string_body> response;

	boost::beast::http::read(ssl_socket, buffer, response);
	if (response.result_int() == 401) {
		throw std::runtime_error("unauthorized. bad token?");
	}
	nlohmann::json yay = nlohmann::json::parse(response.body());

	m_gateway = yay["url"].get<std::string>() + "/?v=8&encoding=json";
	if (m_num_shards == 0) {
		m_num_shards = yay["shards"].get<int>();
	}
	//m_num_shards = 2;
	//std::cout << m_gateway << std::endl;
	fmt::print(m_gateway);
	fmt::print("\n");
}
}


text:
#include <metaSMT/backend/Boolector.hpp>
#include <metaSMT/DirectSolver_Context.hpp>
#include <metaSMT/frontend/QF_BV.hpp>

#include <boost/timer.hpp>
#include <iostream>

static unsigned width = 32;

static const unsigned repeat= 10;
static const unsigned limit = 10000;

static unsigned data[limit];

static unsigned all_valids = 0;

int run_metaSMT () {
  using namespace metaSMT;
  using namespace metaSMT::logic;
  using namespace metaSMT::logic::QF_BV;

  metaSMT::DirectSolver_Context<metaSMT::solver::Boolector> ctx;

  bitvector a = new_bitvector(width);
  bitvector b = new_bitvector(width);
  bitvector c = new_bitvector(2*width);

  bitvector zero = new_bitvector(width);
  assertion( ctx, equal(zero, bvuint(0,width)) );
  assertion( ctx, nequal(a, bvuint(1,width)) );
  assertion( ctx, nequal(b, bvuint(1,width)) );

  assertion( ctx, equal(c, bvmul( concat(zero, a), concat(zero,b)) ));

  int valids = 0;
  for (unsigned i = 0; i < limit; ++i) {
    assumption( ctx, equal(c, bvuint(data[i], 2*width)) );

    if( solve( ctx) ) {
      valids++;
    }
  }

  return valids;
}

int run_btor () {

  Btor* btor = boolector_new();
  boolector_enable_inc_usage(btor);
  boolector_enable_model_gen(btor);

  BtorNode* a = boolector_var(btor, width, "a");
  BtorNode* b = boolector_var(btor, width, "b");
  BtorNode* c = boolector_var(btor, 2*width, "c");

  BtorNode* zero = boolector_var(btor,width, "zero");
  boolector_assert( btor, boolector_eq(btor, zero, boolector_zero(btor, width)) );
  boolector_assert( btor, boolector_ne(btor, a, boolector_unsigned_int(btor, 1, width)) );
  boolector_assert( btor, boolector_ne(btor, b, boolector_unsigned_int(btor, 1, width)) );

  boolector_assert( btor, boolector_eq(btor,
        c, boolector_mul(btor,
          boolector_concat(btor, zero, a),
          boolector_concat(btor, zero, b))
        ));

  int valids = 0;
  for (unsigned i = 0; i < limit; ++i) {
    boolector_assume( btor, boolector_eq(btor, c,
          boolector_unsigned_int(btor, data[i], 2*width)) );

    if( boolector_sat( btor ) == BOOLECTOR_SAT ) {
      valids++;
    }
  }

  boolector_delete(btor);
  return valids;
}

double run(
      int (fun) ()
  )
{
  boost::timer timer;
  timer.restart();
  for (unsigned i = 0; i < repeat; ++i) {
    all_valids += fun();
  }
  return timer.elapsed();
}

void result( std::string const & name, double time) {
  std::cout << name << " ran " << (limit*repeat) << " in "
    << time << "s"
    << " (" << limit << " in " << (time/repeat) <<"s"
    << ", 1 in " << (time/repeat/limit) <<"s"
    << ")"
    << std::endl;
}

int main(int argc, const char *argv[])
{
  if(argc != 2) {
    std::cout << "usage: " << argv[0] << " <magic number> # even = boolector;metaSMT, odd = metaSMT;boolector " << std::endl;
    exit(1);
  }

  time_t seed = time(0);
  srand(seed);
  std::cout << "seed: " << seed << std::endl;

  std::vector<unsigned> data (limit);
  for (unsigned i = 0; i < limit; ++i) {
    data[i] = (unsigned long long)rand()%(1ull<<(width+1));
  }

  double mtime=0.0;
  double btime=0.0;

  if ( atoi(argv[1]) & 1u) {

  std::cout << "Running metaSMT" << std::endl;
  mtime = run(run_metaSMT);

  std::cout << "Running Boolector" << std::endl;
  btime = run( run_btor);
  } else {

  std::cout << "Running Boolector" << std::endl;
  btime += run( run_btor);

  std::cout << "Running metaSMT" << std::endl;
  mtime += run(run_metaSMT);

  }

  result( "metaSMT", mtime);
  result( "boolector", btime);

  return  mtime + btime + all_valids == 0;
}

max_stars_repo_name: finnhaedicke/metaSMT

max_issues_repo_name: finnhaedicke/metaSMT

max_forks_repo_name: finnhaedicke/metaSMT


text:
//
// Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

#include "connector.hpp"

#include <dlib/logger.h>

#include <chrono>
#include <utility>

using namespace std;
using namespace std::chrono;

namespace mtconnect
{
  namespace adapter
  {
    static dlib::logger g_logger("input.connector");

    // Connector public methods
    Connector::Connector(string server, unsigned int port, seconds legacyTimeout)
      : m_server(std::move(server)),
        m_port(port),
        m_localPort(0),
        m_connected(false),
        m_realTime(false),
        m_heartbeatFrequency{HEARTBEAT_FREQ},
        m_legacyTimeout(duration_cast<milliseconds>(legacyTimeout)),
        m_connectionActive(false)
    {
    }

    Connector::~Connector() { close(); }

    void Connector::connect()
    {
      m_connected = false;
      connecting();

      const char *ping = "* PING\n";

      try
      {
        m_connectionActive = true;

        // Connect to server:port, failure will throw dlib::socket_error exception
        // Using a smart pointer to ensure connection is deleted if exception thrown
        g_logger << LDEBUG << "Connecting to data source: " << m_server << " on port: " << m_port;
        m_connection.reset(dlib::connect(m_server, m_port));

        m_localPort = m_connection->get_local_port();

        // Check to see if this connection supports heartbeats.
        m_heartbeats = false;
        g_logger << LDEBUG << "(Port:" << m_localPort << ")"
                 << "Sending initial PING";
        auto status = m_connection->write(ping, strlen(ping));
        if (status < 0)
        {
          g_logger << LWARN << "(Port:" << m_localPort << ")"
                   << "connect: Could not write initial heartbeat: " << to_string(status);
          close();
          return;
        }

        connected();

        // If we have heartbeats, make sure we receive something every freq milliseconds.
        m_lastSent = m_lastHeartbeat = system_clock::now();

        // Make sure connection buffer is clear
        m_buffer.clear();

        // Socket buffer to put the extracted data into
        char sockBuf[SOCKET_BUFFER_SIZE + 1] = {0};

        // Keep track of the status return, else status = character bytes read
        // Assuming it always enters the while loop, it should never be 1
        m_connected = true;

        // Boost priority if this is a real-time adapter
        if (m_realTime)
        {
#ifdef _WINDOWS
          HANDLE hand = OpenThread(THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());
          SetThreadPriority(hand, THREAD_PRIORITY_TIME_CRITICAL);
          CloseHandle(hand);
#else
          struct sched_param param;
          param.sched_priority = 30;
          if (pthread_setschedparam(pthread_self(), SCHED_FIFO, &param))
            g_logger << LDEBUG << "Cannot set high thread priority";
#endif
        }
        g_logger << LTRACE << "(Port:" << m_localPort << ")"
                 << "Heartbeat : " << m_heartbeats;
        g_logger << LTRACE << "(Port:" << m_localPort << ")"
                 << "Heartbeat Freq: " << m_heartbeatFrequency.count();
        // Read from the socket, read is a blocking call
        while (m_connected)
        {
          auto now = system_clock::now();
          milliseconds timeout(0);
          if (m_heartbeats)
          {
            timeout = m_heartbeatFrequency - duration_cast<milliseconds>(now - m_lastSent);
            g_logger << LTRACE << "(Port:" << m_localPort << ")"
                     << "Heartbeat Send Countdown: " << timeout.count();
          }
          else
          {
            timeout = m_legacyTimeout;
            g_logger << LTRACE << "(Port:" << m_localPort << ")"
                     << "Legacy Timeout: " << timeout.count();
          }

          if (timeout < milliseconds{0})
            timeout = milliseconds{1};
          sockBuf[0] = 0;

          if (m_connected)
            status = m_connection->read(sockBuf, SOCKET_BUFFER_SIZE, timeout.count());
          else
          {
            g_logger << LDEBUG << "(Port:" << m_localPort << ")"
                     << "Connection was closed, exiting adapter connect";
            break;
          }

          if (!m_connected)
          {
            g_logger << LDEBUG << "(Port:" << m_localPort << ")"
                     << "Connection was closed during read, exiting adapter";
            break;
          }

          if (status > 0)
          {
            // Give a null terminator for the end of buffer
            sockBuf[status] = '\0';
            parseBuffer(sockBuf);
          }
          else if (status == TIMEOUT && !m_heartbeats && (system_clock::now() - now) >= timeout)
          {
            // We don't stop on heartbeats, but if we have a legacy timeout, then we stop.
            g_logger << LERROR << "(Port:" << m_localPort << ")"
                     << "connect: Did not receive data for over: "
                     << duration_cast<seconds>(timeout).count() << " seconds";
            break;
          }
          else if (status != TIMEOUT)  // Something other than timeout occurred
          {
            g_logger << LERROR << "(Port:" << m_localPort << ")"
                     << "connect: Socket error, disconnecting";
            break;
          }

          if (m_heartbeats)
          {
            now = system_clock::now();
            if ((now - m_lastHeartbeat) > (m_heartbeatFrequency * 2))
            {
              g_logger << LERROR << "(Port:" << m_localPort << ")"
                       << "connect: Did not receive heartbeat for over: "
                       << (m_heartbeatFrequency * 2).count();
              break;
            }
            else if ((now - m_lastSent) >= m_heartbeatFrequency)
            {
              std::lock_guard<std::mutex> lock(m_commandLock);
              g_logger << LDEBUG << "(Port:" << m_localPort << ")"
                       << "Sending a PING for " << m_server << " on port " << m_port;
              status = m_connection->write(ping, strlen(ping));
              if (status <= 0)
              {
                g_logger << LERROR << "(Port:" << m_localPort << ")"
                         << "connect: Could not write heartbeat: " << status;
                break;
              }
              m_lastSent = now;
            }
          }
        }

        g_logger << LERROR << "(Port:" << m_localPort << ")"
                 << "connect: Connection exited with status: " << status;
      }
      catch (dlib::socket_error &e)
      {
        g_logger << LWARN << "(Port:" << m_localPort << ")"
                 << "connect: Socket exception: " << e.what();
      }
      catch (exception &e)
      {
        g_logger << LERROR << "(Port:" << m_localPort << ")"
                 << "connect: Exception in connect: " << e.what();
      }
      catch (...)
      {
        g_logger << LERROR << "(Port:" << m_localPort << ")"
                 << "connect: Unknown Exception in connect";
      }
      {
        std::unique_lock<std::mutex> lk(m_connectionMutex);
        m_connectionActive = false;
        lk.unlock();
        m_connectionCondition.notify_all();
      }
      close();
    }

    void Connector::parseBuffer(const char *buffer)
    {
      // Treat any data as a heartbeat.
      if (m_heartbeats)
        m_lastHeartbeat = system_clock::now();

      // Append the temporary buffer to the socket buffer
      m_buffer.append(buffer);

      auto newLine = m_buffer.find_last_of('\n');

      // Check to see if there is even a '\n' in buffer
      if (newLine != string::npos)
      {
        // If the '\n' is not at the end of the buffer, then save the overflow
        string overflow;

        if (newLine != m_buffer.length() - 1)
        {
          overflow = m_buffer.substr(newLine + 1);
          m_buffer = m_buffer.substr(0, newLine);
        }

        // TODO: Use string Views and skip getline. Use
        // find_first_of and then clip to subview of line.
        // Search the buffer for new complete lines
        string line;
        stringstream stream(m_buffer, stringstream::in);

        while (!stream.eof())
        {
          getline(stream, line);
          g_logger << LTRACE << "(Port:" << m_localPort << ") Received line: '" << line << '\'';

          if (line.empty())
            continue;

          auto end = line.find_last_not_of(" \t\n\r");
          if (end != string::npos)
            line.erase(end + 1);

          // Check for heartbeats
          if (line[0] == '*')
          {
            if (!line.compare(0, 6, "* PONG"))
            {
              if (g_logger.level().priority <= LDEBUG.priority)
              {
                g_logger << LDEBUG << "(Port:" << m_localPort << ")"
                         << "Received a PONG for " << m_server << " on port " << m_port;
                auto delta = date::floor<milliseconds>(system_clock::now() - m_lastHeartbeat);
                g_logger << LDEBUG << "(Port:" << m_localPort << ")"
                         << "    Time since last heartbeat: " << delta.count() << "ms";
              }
              if (!m_heartbeats)
                startHeartbeats(line);
            }
            else
            {
              protocolCommand(line);
            }
          }
          else
          {
            processData(line);
          }
        }

        // Clear buffer/insert overflow data
        m_buffer = overflow;
      }
    }

    void Connector::sendCommand(const string &command)
    {
      std::lock_guard<std::mutex> lock(m_commandLock);

      if (m_connected)
      {
        string completeCommand = "* " + command + "\n";
        long status = m_connection->write(completeCommand.c_str(), completeCommand.length());
        if (status <= 0)
        {
          g_logger << LWARN << "(Port:" << m_localPort << ")"
                   << "sendCommand: Could not write command: '" << command << "' - "
                   << to_string(status);
        }
      }
    }

    void Connector::startHeartbeats(const string &arg)
    {
      size_t pos;
      if (arg.length() > 7 && arg[6] == ' ' &&
          (pos = arg.find_first_of("0123456789", 7)) != string::npos)
      {
        auto freq = milliseconds{atoi(arg.substr(pos).c_str())};
        constexpr minutes maxTimeOut = minutes{30};  // Make the maximum timeout 30 minutes.

        if (freq > 0ms && freq < maxTimeOut)
        {
          g_logger << LDEBUG << "(Port:" << m_localPort << ")"
                   << "Received PONG, starting heartbeats every " << freq.count() << "ms";
          m_heartbeats = true;
          m_heartbeatFrequency = freq;
        }
        else
        {
          g_logger << LERROR << "(Port:" << m_localPort << ")"
                   << "startHeartbeats: Bad heartbeat frequency " << arg << ", ignoring";
        }
      }
      else
      {
        g_logger << LERROR << "(Port:" << m_localPort << ")"
                 << "startHeartbeats: Bad heartbeat command " << arg << ", ignoring";
      }
    }

    void Connector::close()
    {
      if (m_connected && m_connection.get())
      {
        // Shutdown the socket and close the connection.
        try
        {
          m_connected = false;
          m_connection->shutdown();
        }
        catch (exception &e)
        {
          g_logger << LERROR << "(Port:" << m_localPort << ")"
                   << "close: Exception when shutting down connection: " << e.what();
        }

        g_logger << LDEBUG << "(Port:" << m_localPort << ")"
                 << "Waiting for connect method to exit and signal connection closed";

        if (m_connectionActive)
        {
          std::unique_lock<std::mutex> lk(m_connectionMutex);
          m_connectionCondition.wait(lk, [this]() { return !m_connectionActive; });
        }

        // Destroy the connection object.
        m_connection.reset();

        disconnected();
      }
    }
  }  // namespace adapter
}  // namespace mtconnect

max_stars_repo_name: masonhieb/cppagent

max_issues_repo_name: masonhieb/cppagent

max_forks_repo_name: masonhieb/cppagent


text:
/*
 * Copyright (c) 2018-2020 Steven Varga, Toronto,ON Canada
 * Author: Varga, Steven <steven@vargaconsulting.ca>
 */
#include <armadillo>
#include <cstdint>
#include "struct.h"
#include <h5cpp/core>
	// generated file must be sandwiched between core and io
	// to satisfy template dependencies in <h5cpp/io>
	#include "generated.h"
#include <h5cpp/io>
#include "utils.hpp"

#define CHUNK_SIZE 5
#define NROWS 4*CHUNK_SIZE
#define NCOLS 1*CHUNK_SIZE

int main(){
	//RAII will close resource, noo need H5Fclose( any_longer );
	h5::fd_t fd = h5::create("example.h5",H5F_ACC_TRUNC);

	{// LINARG:=[armaidllo|eigen3|blaze|blitz|it++|dlib|ublas] supported
		arma::imat M(NROWS,NCOLS);              // define a linalg object
		h5::write(fd, "/linalg/armadillo",M);   // save it somewhere, partial and full read|write and append supported
	}
	{// create a Matrix of STRUCT with chunked and GZIP compressed properties ready for partial read|write
	 // upto 7 dimensions/extents are supported
		h5::create<sn::example::Record>(fd, "/orm/chunked_2D",
				h5::current_dims{NROWS,NCOLS}, h5::chunk{1,CHUNK_SIZE} | h5::gzip{8} );
		//FIXME: defaults to unit chunk, which may not the best setting, yet chunking is required for unlimted
		// should we have some plausable value: 1024 instead?
		h5::create<sn::typecheck::Record>(fd, "/orm/typecheck",	h5::max_dims{H5S_UNLIMITED} );
	}

	{ // creates + writes entire object tree
		std::vector<sn::example::Record> vec = h5::utils::get_test_data<sn::example::Record>(20);
		h5::write(fd, "orm/partial/vector one_shot", vec );
		// dimensions and other properties specified additional argument
		h5::write(fd, "orm/partial/vector custom_dims", vec,
			h5::max_dims{H5S_UNLIMITED}, h5::gzip{9} | h5::chunk{20} );
		// you don't need to remember order, compiler will do it for you without runtime penalty:
		 h5::write(fd, "orm/partial/vector custom_dims different_order", vec,
			h5::chunk{20} | h5::gzip{9},
			h5::max_dims{H5S_UNLIMITED},
			// how much to move from current location to next, stide[i] >= block[i] must hold
			// gap = block[i] - stride[i]
			h5::stride{6}, h5::block{4},
			h5::current_dims{100}, h5::offset{2});
	}

	{ // read entire dataset back
		using T = std::vector<sn::example::Record>;
		auto data = h5::read<T>(fd,"/orm/partial/vector one_shot");
		std::cerr <<"reading back data previously written:\n\t";
		for( auto r:data )
			std::cerr << r.idx <<" ";
		std::cerr << std::endl;
	}
}