<commit_before>#include "imgui-SFML.h"
#include "imgui.h"
//#include "imgui_demo.h"
#include "Planet.hpp"
#include "Universe.hpp"
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/Window/Event.hpp>
#include <stdint.h>
#include <stdlib.h>
// void myFunc() { ImGui::Button("My Func"); }
// for help things.
static void ShowHelpMarker(const char *desc) {
  ImGui::TextDisabled("(?)");
  if (ImGui::IsItemHovered()) {
    ImGui::BeginTooltip();
    ImGui::PushTextWrapPos(450.0f);
    ImGui::TextUnformatted(desc);
    ImGui::PopTextWrapPos();
    ImGui::EndTooltip();
  }
}

int main() {
  // int buttonPressed = 0;
  sf::RenderWindow window(sf::VideoMode(1300, 700), "Pixel Planet Simulator");

  window.setFramerateLimit(500);
  ImGui::SFML::Init(window);

  static bool hasFocus = true;

  sf::Font fontCapture;
  // pps::Planet::font = sf::Font();
  // if (!pps::Planet::font.loadFromFile("res/Capture_it.ttf")) {
  //  return 22;
  //}

  // pps::Planet::SetFont(fontCapture);

  sf::Text txtFps;
  txtFps.setFont(fontCapture);
  int didsomting = 0;

  // for use in imgui
  bool showMenuGod = false;
  bool showMenuPlanet = false;
  float g = 10;

  // trails vars
  int tl = 100;
  int fd = 100;
  bool dt = true;
  int uniDrawMode = 0;

  // float apc[3] = {1.0f, 0.0f, 0.2f};

  pps::Universe uni;
  pps::Planet p1("Foo", 10, 100, sf::Vector2f(200, 200), sf::Vector2f(0, 100),
                 sf::Color::Red);
  pps::Planet p2("Bar", 50, 500, sf::Vector2f(400, 200), sf::Vector2f(0, -20),
                 sf::Color::Blue);
  uni.addPlanet(p1);
  uni.addPlanet(p2);

  uni.setDrawTrails(true);

  // timing
  printf("dsfs\n");

  uint tick = 0;
  sf::Time tickTime =
      sf::seconds(0.01f);    // the amount of time to simulate every tick
  int ticksPerSecond = 1200; // number of ticks to simulate evry second
  sf::Time secondsPerTick = sf::seconds(1.0f / ticksPerSecond);

  int framesPerSecond = 120;
  int ticksPerFrame =
      ticksPerSecond /
      framesPerSecond; // todo make it adgust fps for valid ratio
  printf("asdasd\n");
  sf::Time secondsPerFrame = sf::seconds(1.0f / framesPerSecond);
  /*
  clock.resart()
  tick++;
  uni.update()
  if(tick% ticksPerFrame = 0)
    render();

  if(clock.time() < secondsPerTick )
    sleep(secondsPerTick -clock.time());
  */
  sf::Clock deltaClock;

  /*
  Main loop
   */
  printf("ghashjfdksf\n");
  while (window.isOpen()) {
    deltaClock.restart();
    tick++;

    ////Update univers////
    uni.Update(tickTime, uniDrawMode, window.getSize());

    // if we are rendering do gui and draw
    if (tick % ticksPerFrame == 0) {
      // handleEvents( ) //TODO: break out event handler
      sf::Event event;
      while (window.pollEvent(event)) {
        ImGui::SFML::ProcessEvent(event);

        // if the window has focuse and Imgui dose not
        if (hasFocus && !ImGui::IsMouseHoveringAnyWindow()) {
          // nonimgui event handling
        }

        switch (event.type) {
        case sf::Event::LostFocus:
          hasFocus = false;
          break;
        case sf::Event::GainedFocus:
          hasFocus = true;
          break;
        default:
          break;
        }

        if (event.type == sf::Event::Closed) {
          window.close();
        }
      }

      // update ImGui
      ImGui::SFML::Update(window, secondsPerFrame);

      /////GUI LOGIC /////
      if (ImGui::BeginMainMenuBar()) {
        if (ImGui::BeginMenu("File")) {
          //  ShowExampleMenuFile();

          if (ImGui::MenuItem("does", "nothing", false, false)) {
          } // Disabled item
          ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("Windows")) {
          //  ShowExampleMenuFile();

          ImGui::MenuItem("God Window", NULL, &showMenuGod);
          ImGui::MenuItem("Planet Window", NULL, &showMenuPlanet);
          ImGui::EndMenu();
        }

        if (ImGui::BeginMenu("Edit")) {
          if (ImGui::MenuItem("Undo", "CTRL+Z")) {
          }
          if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {
          } // Disabled item
          ImGui::Separator();
          if (ImGui::MenuItem("Cut", "CTRL+X")) {
          }
          if (ImGui::MenuItem("Copy", "CTRL+C")) {
          }
          if (ImGui::MenuItem("Paste", "CTRL+V")) {
          }
          ImGui::EndMenu();
        }
        ImGui::EndMainMenuBar();
      }

      if (showMenuGod) {
        ImGui::Begin("GodOLD");

        ImGui::SliderFloat("Gravitational Constant", &g, 0.0f, 10.0f,
                           "ratio = %.3f");
        uni.setG(g);
        ImGui::InputInt("Univers Draw Mode", &uniDrawMode, 1);

        ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
                    1000.0f / ImGui::GetIO().Framerate,
                    ImGui::GetIO().Framerate);
        ImGui::Text("Planet Count: %d", uni.getPlanetCount());
        ImGui::Text("Didsomting: %d", didsomting);
        sf::Vector2f *tempUE = uni.getUniverseExtents();
        ImGui::Text("Universe Extents: (%f,%f) (%f,%f)", tempUE[0].x,
                    tempUE[0].y, tempUE[1].x, tempUE[1].y);

        tempUE = uni.getMaxUniverseExtentsSeen();
        ImGui::Text("Universe Extents: (%f,%f) (%f,%f)", tempUE[0].x,
                    tempUE[0].y, tempUE[1].x, tempUE[1].y);
        ImGui::Text("Has Focus %d, imguihas focus %d", hasFocus,
                    ImGui::IsMouseHoveringAnyWindow());
        ImGui::End();
        // Checked item
      }

      if (showMenuPlanet) {
        ImGui::Begin("Planet Menu");

        uni.imguiPlanetMenu();
        uni.imguiPlanetsList();

        if (ImGui::CollapsingHeader("Global Planet Settings")) {
          // trails
          if (tl < 0)
            tl = 0;
          if (fd < 0)
            fd = 0;
          if (ImGui::CollapsingHeader("Trails")) {
            ImGui::InputInt("Trails Length", &tl);
            // ImGui::SameLine();
            ImGui::InputInt("Frame Delay", &fd);
            ImGui::Checkbox("Trailes Enabled", &dt);

            if (ImGui::Button("Update Trails")) {

              uni.setTrailLength(tl);
              uni.setTrailFrameDelay(fd);
              uni.setDrawTrails(dt);
            }
          }

          // apply
        }

        ImGui::Text("Planet Count: %d", uni.getPlanetCount());

        ImGui::End();
      }

      //// CLEAR ////
      window.clear();

      //// DRAW /////
      uni.draw(window); // draw Universe

      ImGui::Render(); // draw ImGui

      // window.draw(txtFps);

      //// DISPLAY ////
      window.display();
    }

    sf::sleep(secondsPerTick - deltaClock.getElapsedTime());
  }

  ImGui::SFML::Shutdown();
}
<commit_msg>added time slider in god menue<commit_after>#include "imgui-SFML.h"
#include "imgui.h"
//#include "imgui_demo.h"
#include "Planet.hpp"
#include "Universe.hpp"
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/Window/Event.hpp>
#include <stdint.h>
#include <stdlib.h>
// void myFunc() { ImGui::Button("My Func"); }
// for help things.
static void ShowHelpMarker(const char *desc) {
  ImGui::TextDisabled("(?)");
  if (ImGui::IsItemHovered()) {
    ImGui::BeginTooltip();
    ImGui::PushTextWrapPos(450.0f);
    ImGui::TextUnformatted(desc);
    ImGui::PopTextWrapPos();
    ImGui::EndTooltip();
  }
}

int main() {
  // int buttonPressed = 0;
  sf::RenderWindow window(sf::VideoMode(1300, 700), "Pixel Planet Simulator");

  window.setFramerateLimit(500);
  ImGui::SFML::Init(window);

  static bool hasFocus = true;

  sf::Font fontCapture;
  // pps::Planet::font = sf::Font();
  // if (!pps::Planet::font.loadFromFile("res/Capture_it.ttf")) {
  //  return 22;
  //}

  // pps::Planet::SetFont(fontCapture);

  sf::Text txtFps;
  txtFps.setFont(fontCapture);
  int didsomting = 0;

  // for use in imgui
  bool showMenuGod = false;
  bool showMenuPlanet = false;
  float g = 10;

  // trails vars
  int tl = 100;
  int fd = 100;
  bool dt = true;
  int uniDrawMode = 0;

  // float apc[3] = {1.0f, 0.0f, 0.2f};

  pps::Universe uni;
  pps::Planet p1("Foo", 10, 100, sf::Vector2f(200, 200), sf::Vector2f(0, 100),
                 sf::Color::Red);
  pps::Planet p2("Bar", 50, 500, sf::Vector2f(400, 200), sf::Vector2f(0, -20),
                 sf::Color::Blue);
  uni.addPlanet(p1);
  uni.addPlanet(p2);

  uni.setDrawTrails(true);

  // timing
  /*
  how the game timing works
  tickTime is the number of sim time per tick

  */

  uint tick = 0;
  sf::Time tickTime = sf::seconds(0.01f); // the amount of time to simulate
                                          // every tick (adjust this to change
                                          // the acuracy of the sim)
  int ticksPerSecond = 600; // number of ticks to simulate evry second (adjust
                            // this to change the sppd** (kind of)
  float simTimePerSecond = tickTime.asSeconds() * ticksPerSecond;
  sf::Time secondsPerTick = sf::seconds(1.0f / ticksPerSecond);

  int framesPerSecond = 120; // desired render rate
  int ticksPerFrame =
      ticksPerSecond /
      framesPerSecond; // todo: make it adgust fps for valid ratio
  sf::Time secondsPerFrame = sf::seconds(1.0f / framesPerSecond);
  /*
  clock.resart()
  tick++;
  uni.update()
  if(tick% ticksPerFrame = 0)
    render();

  if(clock.time() < secondsPerTick )
    sleep(secondsPerTick -clock.time());
  */
  sf::Clock deltaClock;

  /*
  Main loop
   */
  while (window.isOpen()) {
    deltaClock.restart();
    tick++;

    ////Update univers////
    uni.Update(tickTime, uniDrawMode, window.getSize());

    // if we are rendering do gui and draw
    if (tick % ticksPerFrame == 0) {
      // handleEvents( ) //TODO: break out event handler
      sf::Event event;
      while (window.pollEvent(event)) {
        ImGui::SFML::ProcessEvent(event);

        // if the window has focuse and Imgui dose not
        if (hasFocus && !ImGui::IsMouseHoveringAnyWindow()) {
          // nonimgui event handling
        }

        switch (event.type) {
        case sf::Event::LostFocus:
          hasFocus = false;
          break;
        case sf::Event::GainedFocus:
          hasFocus = true;
          break;
        default:
          break;
        }

        if (event.type == sf::Event::Closed) {
          window.close();
        }
      }

      // update ImGui
      ImGui::SFML::Update(window, secondsPerFrame);

      /////GUI LOGIC /////
      if (ImGui::BeginMainMenuBar()) {
        if (ImGui::BeginMenu("File")) {
          //  ShowExampleMenuFile();

          if (ImGui::MenuItem("does", "nothing", false, false)) {
          } // Disabled item
          ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("Windows")) {
          //  ShowExampleMenuFile();

          ImGui::MenuItem("God Window", NULL, &showMenuGod);
          ImGui::MenuItem("Planet Window", NULL, &showMenuPlanet);
          ImGui::EndMenu();
        }

        if (ImGui::BeginMenu("Edit")) {
          if (ImGui::MenuItem("Undo", "CTRL+Z")) {
          }
          if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {
          } // Disabled item
          ImGui::Separator();
          if (ImGui::MenuItem("Cut", "CTRL+X")) {
          }
          if (ImGui::MenuItem("Copy", "CTRL+C")) {
          }
          if (ImGui::MenuItem("Paste", "CTRL+V")) {
          }
          ImGui::EndMenu();
        }
        ImGui::EndMainMenuBar();
      }

      if (showMenuGod) {
        ImGui::Begin("GodOLD");

        ImGui::SliderFloat("Gravitational Constant", &g, 0.0f, 10.0f,
                           "ratio = %.3f");
        uni.setG(g);
        ImGui::InputInt("Univers Draw Mode", &uniDrawMode, 1);

        ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
                    1000.0f / ImGui::GetIO().Framerate,
                    ImGui::GetIO().Framerate);
        ImGui::Text("Planet Count: %d", uni.getPlanetCount());
        ImGui::Text("Didsomting: %d", didsomting);
        sf::Vector2f *tempUE = uni.getUniverseExtents();
        ImGui::Text("Universe Extents: (%f,%f) (%f,%f)", tempUE[0].x,
                    tempUE[0].y, tempUE[1].x, tempUE[1].y);

        tempUE = uni.getMaxUniverseExtentsSeen();
        ImGui::Text("Universe Extents: (%f,%f) (%f,%f)", tempUE[0].x,
                    tempUE[0].y, tempUE[1].x, tempUE[1].y);
        ImGui::Text("Has Focus %d, imguihas focus %d", hasFocus,
                    ImGui::IsMouseHoveringAnyWindow());

        if (ImGui::CollapsingHeader("Time")) {
          /// ImGui::InputFloat("Time Simulated per Tick",
          /// &(tickTime.asSeconds(), 1);
          ImGui::InputFloat("Speed (sim seconds/second)", &simTimePerSecond, 1);
          ImGui::Text("ticksPerSecond: %d", ticksPerSecond);

          ticksPerSecond = (int)simTimePerSecond / tickTime.asSeconds();
          simTimePerSecond = tickTime.asSeconds() * ticksPerSecond;
          secondsPerTick = sf::seconds(1.0f / ticksPerSecond);
          ticksPerFrame = ticksPerSecond / framesPerSecond;
        }
        ImGui::End();
        // Checked item
      }

      if (showMenuPlanet) {
        ImGui::Begin("Planet Menu");

        uni.imguiPlanetMenu();
        uni.imguiPlanetsList();

        if (ImGui::CollapsingHeader("Global Planet Settings")) {
          // trails
          if (tl < 0)
            tl = 0;
          if (fd < 0)
            fd = 0;
          if (ImGui::CollapsingHeader("Trails")) {
            ImGui::InputInt("Trails Length", &tl);
            // ImGui::SameLine();
            ImGui::InputInt("Frame Delay", &fd);
            ImGui::Checkbox("Trailes Enabled", &dt);

            if (ImGui::Button("Update Trails")) {

              uni.setTrailLength(tl);
              uni.setTrailFrameDelay(fd);
              uni.setDrawTrails(dt);
            }
          }

          // apply
        }

        ImGui::Text("Planet Count: %d", uni.getPlanetCount());

        ImGui::End();
      }

      //// CLEAR ////
      window.clear();

      //// DRAW /////
      uni.draw(window); // draw Universe

      ImGui::Render(); // draw ImGui

      // window.draw(txtFps);

      //// DISPLAY ////
      window.display();
    }

    sf::sleep(secondsPerTick - deltaClock.getElapsedTime());
  }

  ImGui::SFML::Shutdown();
}
<|endoftext|>


<commit_before>//
// Weasel Program, written in "gone-full-retard" C++14!
//
//  https://en.wikipedia.org/wiki/Weasel_program
//
// The Weasel program is a thought experiment and a very rough simulation of
// evolution, by starting with a random string of characters and gradually
// "evolving" them into the text "methinks it is like a weasel".
//
// The program can be easily modified to generate text that satisfies other
// criteria, e.g. being a palindrome, thus not choosing one particular output.
//
// The starting text is random and is mutated randomly (mutation) and it is
// then scored for suitability (natural selection), resulting in a non-random
// output (evolution).
//

#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <locale>
#include <string>
#include <random>
#include <stdexcept>
#include <string>
#include <vector>

namespace
{

///
/// @brief Global target string.
/// @todo Doesn't need to be in unnamed namespace: const's have static linkage.
///
const std::string methinks("methinks it is like a weasel");

///
/// @brief Program modes.
/// @note Uncomment the one you want used, comment all the others.
/// @todo These should be strongly-typed `enum`s used together with a
///  "static if" mechanism, such as `if constexpr` in C++17.
///
#define MODE_WEASEL
//#define MODE_PALINDROME

///
/// @brief Gives the suitability score of a candidate string.
/// @details A perfect score equals `0` (zero); the higher the worse.
/// @todo Use `if constexpr` instead of `#ifdef` once C++17 becomes available.
/// @note This function was designed to be general such that it can be modified
///  easily to score things other than resemblance to the "weasel" text, while
///  retaining the interface and usage: for example, it could score how good
///  a palindrome the `candidate` string is (as already implemented).
/// @param [in] candidate           Candidate string.
/// @returns Suitability score.
/// @retval 0                       Perfect score.
///
std::size_t score(const std::string &candidate)
try
{
#if defined MODE_WEASEL
    if (candidate.length() != methinks.length())
        return std::numeric_limits<std::size_t>::max();

    std::size_t r(methinks.length());

    for (std::size_t i(0); i < methinks.length(); ++i)
        if (candidate.at(i) == methinks.at(i))
            --r;

    return r;
#elif defined MODE_PALINDROME
    auto            ib  (candidate.cbegin());
    const auto      ie  (candidate.cend());
    auto            rib (candidate.crbegin());
    std::size_t     r   (candidate.length());

    for (; ib != ie; ++ib, ++rib)
        if (*ib == *rib)
            --r;

    return r;
#endif
}
catch (const std::out_of_range &e)
{
    std::cerr << "`std::out_of_range` exception in `" << __func__ << "`: ";
    std::cerr << e.what() << std::endl;
    throw;
}
catch (...)
{
    std::cerr << "unknown exception in `" << __func__ << '`' << std::endl;
    throw;
}

} // unnamed namespace

///
/// @brief Enters the program.
/// @returns Whether or not the operation was successful.
/// @retval EXIT_SUCCESS            Operation success.
/// @retval EXIT_FAILURE            Operation failure.
///
int main()
try
{
    // Number of Candidate strings in a Generation
    constexpr std::size_t num_cagen(100);

    std::size_t calen(0); // Candidate string Length

#if defined MODE_WEASEL
    calen = methinks.length();
#elif defined MODE_PALINDROME
    calen = 50;
#endif

    //
    // create a candidate string
    //

    // Pseudo-Random Number Generator
    std::mt19937 prng(
        std::chrono::system_clock::now().time_since_epoch().count());

    // Random Character
    std::uniform_int_distribution<char> rand_char(
        std::numeric_limits<char>::min(),
        std::numeric_limits<char>::max());

    // Random chance to Mutate (0 == no, 1 == yes)
    std::discrete_distribution<unsigned long int> rand_mutate({
        95.0,       // 0
         5.0});     // 1

    // Generate random Printable Character
    std::function<char (void)> gen_print_char =
        [&prng, &rand_char]() -> char
        {
            char c;

            do
            {
                c = rand_char(prng);
            }
            while (!std::isprint(c, std::locale("C")));

            return c;
        };

    std::string candidate(calen, char(0)); // Candidate string

    std::generate(candidate.begin(), candidate.end(), gen_print_char);

    // the current Candidates Generation
    std::vector<std::string> cagen(num_cagen, candidate);

    // Value passed to `std::setw()` to prettify printing
    constexpr std::size_t val_setw(10);

    std::cout << std::setw(val_setw) << "FIRST: " << candidate << '\n';

    std::size_t kgen(1); // Generation counter

    while (score(candidate) != 0)
    {
        for (std::string &ca: cagen)
            for (char &c: ca)
                if (rand_mutate(prng) != 0)
                    c = gen_print_char();

        for (const std::string &ca: cagen)
            if (score(ca) < score(candidate))
            {
                candidate = ca;
                std::cout << std::setw(val_setw) << std::to_string(kgen) + ": ";
                std::cout << candidate << '\n';
            }

        std::fill(cagen.begin(), cagen.end(), candidate);
        ++kgen;
    }

    std::cout << std::setw(val_setw) << "LAST: " << candidate << std::endl;
    return EXIT_SUCCESS;
}
catch (const std::out_of_range &e)
{
    std::cerr << "`std::out_of_range` exception in `" << __func__ << "`: ";
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch (...)
{
    std::cerr << "unknown exception in `" << __func__ << '`' << std::endl;
    return EXIT_FAILURE;
}
<commit_msg>Update weasel.cpp<commit_after>//
// Weasel Program, written in "gone-full-retard" C++14!
//
//  https://en.wikipedia.org/wiki/Weasel_program
//
// The Weasel program is a thought experiment and a very rough simulation of
// evolution, by starting with a random string of characters and gradually
// "evolving" them into the text "methinks it is like a weasel".
//
// The program can be easily modified to generate text that satisfies other
// criteria, e.g. being a palindrome, thus not choosing one particular output.
//
// The starting text is random and is mutated randomly (mutation) and it is
// then scored for suitability (natural selection), resulting in a non-random
// output (evolution).
//

#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <locale>
#include <string>
#include <random>
#include <stdexcept>
#include <string>
#include <vector>

namespace
{

///
/// @brief Global target string.
/// @todo Doesn't need to be in unnamed namespace: const's have static linkage.
///
const std::string methinks("methinks it is like a weasel");

///
/// @brief Program modes.
/// @note Uncomment the one you want used, comment all the others.
/// @todo These should be strongly-typed `enum`s used together with a
///  "static if" mechanism, such as `if constexpr` in C++17.
///
#define MODE_WEASEL
//#define MODE_PALINDROME

///
/// @brief Gives the suitability score of a candidate string.
/// @details A perfect score equals `0` (zero); the higher the worse.
/// @todo Use `if constexpr` instead of `#ifdef` once C++17 becomes available.
/// @note This function was designed to be general such that it can be modified
///  easily to score things other than resemblance to the "weasel" text, while
///  retaining the interface and usage: for example, it could score how good
///  a palindrome the `candidate` string is (as already implemented).
/// @param [in] candidate           Candidate string.
/// @returns Suitability score.
/// @retval 0                       Perfect score.
///
std::size_t score(const std::string &candidate)
try
{
#if defined MODE_WEASEL
    if (candidate.length() != methinks.length())
        return std::numeric_limits<std::size_t>::max();

    std::size_t r(methinks.length());

    for (std::size_t i(0); i < methinks.length(); ++i)
        if (candidate.at(i) == methinks.at(i))
            --r;

    return r;
#elif defined MODE_PALINDROME
    auto            ib  (candidate.cbegin());
    const auto      ie  (candidate.cend());
    auto            rib (candidate.crbegin());
    std::size_t     r   (candidate.length());

    for (; ib != ie; ++ib, ++rib)
        if (*ib == *rib)
            --r;

    return r;
#endif
}
catch (const std::out_of_range &e)
{
    std::cerr << "`std::out_of_range` exception in `" << __func__ << "`: ";
    std::cerr << e.what() << std::endl;
    throw;
}
catch (...)
{
    std::cerr << "unknown exception in `" << __func__ << '`' << std::endl;
    throw;
}

} // unnamed namespace

///
/// @brief Enters the program.
/// @returns Whether or not the operation was successful.
/// @retval EXIT_SUCCESS            Operation success.
/// @retval EXIT_FAILURE            Operation failure.
///
int main()
try
{
    // Number of Candidate strings in a Generation
    constexpr std::size_t num_cagen(100);

    std::size_t calen(0); // Candidate string Length

#if defined MODE_WEASEL
    calen = methinks.length();
#elif defined MODE_PALINDROME
    calen = 50;
#endif

    //
    // create a candidate string
    //

    // Pseudo-Random Number Generator
    std::mt19937 prng(
        std::chrono::system_clock::now().time_since_epoch().count());

    // Random Character
    std::uniform_int_distribution<char> rand_char(
        std::numeric_limits<char>::min(),
        std::numeric_limits<char>::max());

    // Random chance to Mutate (0 == no, 1 == yes)
    std::discrete_distribution<unsigned long int> rand_mutate({
        95.0,       // 0
         5.0});     // 1

    // Generate random Printable Character
    std::function<char (void)> gen_print_char =
        [&prng, &rand_char]() -> char
        {
            char c;

            do
            {
                c = rand_char(prng);
            }
            while (!std::isprint(c, std::locale::classic()));

            return c;
        };

    std::string candidate(calen, char(0)); // Candidate string

    std::generate(candidate.begin(), candidate.end(), gen_print_char);

    // the current Candidates Generation
    std::vector<std::string> cagen(num_cagen, candidate);

    // Value passed to `std::setw()` to prettify printing
    constexpr std::size_t val_setw(10);

    std::cout << std::setw(val_setw) << "FIRST: " << candidate << '\n';

    std::size_t kgen(1); // Generation counter

    while (score(candidate) != 0)
    {
        for (std::string &ca: cagen)
            for (char &c: ca)
                if (rand_mutate(prng) != 0)
                    c = gen_print_char();

        for (const std::string &ca: cagen)
            if (score(ca) < score(candidate))
            {
                candidate = ca;
                std::cout << std::setw(val_setw) << std::to_string(kgen) + ": ";
                std::cout << candidate << '\n';
            }

        std::fill(cagen.begin(), cagen.end(), candidate);
        ++kgen;
    }

    std::cout << std::setw(val_setw) << "LAST: " << candidate << std::endl;
    return EXIT_SUCCESS;
}
catch (const std::out_of_range &e)
{
    std::cerr << "`std::out_of_range` exception in `" << __func__ << "`: ";
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch (...)
{
    std::cerr << "unknown exception in `" << __func__ << '`' << std::endl;
    return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_MATH_MATHUTILS_HPP
#define OUZEL_MATH_MATHUTILS_HPP

#include <cstdint>
#include <cmath>
#include <limits>
#include <type_traits>
#if defined(__ANDROID__)
#  include <cpu-features.h>
#endif

namespace ouzel
{
#if defined(__ARM_NEON__)
#  if defined(__ANDROID__) && defined(__arm__)
    // NEON support must be checked at runtime on 32-bit Android
    class AnrdoidNeonChecker final
    {
    public:
        AnrdoidNeonChecker()
        {
            neonAvailable = (android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM &&
                             (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0);
        }

        operator bool() const { return neonAvailable; }

    private:
        bool neonAvailable;
    };

    extern AnrdoidNeonChecker isSimdAvailable;
#  else
    constexpr bool isSimdAvailable = true;
#  endif
#elif defined(__SSE__)
    constexpr bool isSimdAvailable = true;
#else
    constexpr bool isSimdAvailable = false;
#endif

    template<typename T>
    constexpr T tau()
    {
        return static_cast<T>(6.28318530717958647692);
    }

    template<typename T>
    constexpr T pi()
    {
        return static_cast<T>(3.14159265358979323846);
    }

    template<typename T> inline T lerp(T v0, T v1, T t)
    {
        return (1 - t) * v0 + t * v1;
    }

    template<typename T> inline T smoothStep(T a, T b, T t)
    {
        float remapSmoothStep = t * t * (3 - 2 * t);
        return lerp(a, b, remapSmoothStep);
    }

    template<typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
    inline bool isPowerOfTwo(T x)
    {
        return (x != 0) && (((x - 1) & x) == 0);
    }

    template<typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
    inline T nextPowerOfTwo(T x)
    {
        if (x != 0)
        {
            --x;
            for (uint32_t shift = 1; shift < sizeof(T) * 8; shift *= 2)
                x |= (x >> shift);
        }
        return ++x;
    }

    template<typename T> inline int sgn(T val)
    {
        return (T(0) < val) - (val < T(0));
    }

    template<typename T> inline T degToRad(T x)
    {
        return static_cast<T>(x * 0.01745329252);
    }

    template<typename T> inline T radToDeg(T x)
    {
        return static_cast<T>(x * 57.295779513);
    }

    template<typename T>
    inline T clamp(T x, T lo, T hi)
    {
        return (x < lo) ? lo : ((x > hi) ? hi : x);
    }

    constexpr uint64_t INITIAL_FNV = 2166136261U;
    constexpr uint64_t FNV_MULTIPLE = 16777619;

    // Fowler / Noll / Vo (FNV) hash
    inline uint64_t fnvHash(uint64_t s)
    {
        uint64_t hash = INITIAL_FNV;
        for (uint64_t i = 0; i < sizeof(uint64_t); ++i)
        {
            hash = hash ^ (reinterpret_cast<uint8_t*>(&s)[i]); // xor the low 8 bits
            hash = hash * FNV_MULTIPLE; // multiply by the magic number
        }
        return hash;
    }

    template<class T>
    inline bool isNearlyEqual(T a, T b, T tolerance = std::numeric_limits<T>::min())
    {
        return fabs(a - b) <= tolerance;
    }
}

#endif // OUZEL_MATH_MATHUTILS_HPP
<commit_msg>Initialize the neonAvailable attribute in the constructor's initializer list<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_MATH_MATHUTILS_HPP
#define OUZEL_MATH_MATHUTILS_HPP

#include <cstdint>
#include <cmath>
#include <limits>
#include <type_traits>
#if defined(__ANDROID__)
#  include <cpu-features.h>
#endif

namespace ouzel
{
#if defined(__ARM_NEON__)
#  if defined(__ANDROID__) && defined(__arm__)
    // NEON support must be checked at runtime on 32-bit Android
    class AnrdoidNeonChecker final
    {
    public:
        AnrdoidNeonChecker():
            neonAvailable(android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM &&
                          (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0)
        {
        }

        operator bool() const { return neonAvailable; }

    private:
        bool neonAvailable;
    };

    extern AnrdoidNeonChecker isSimdAvailable;
#  else
    constexpr bool isSimdAvailable = true;
#  endif
#elif defined(__SSE__)
    constexpr bool isSimdAvailable = true;
#else
    constexpr bool isSimdAvailable = false;
#endif

    template<typename T>
    constexpr T tau()
    {
        return static_cast<T>(6.28318530717958647692);
    }

    template<typename T>
    constexpr T pi()
    {
        return static_cast<T>(3.14159265358979323846);
    }

    template<typename T> inline T lerp(T v0, T v1, T t)
    {
        return (1 - t) * v0 + t * v1;
    }

    template<typename T> inline T smoothStep(T a, T b, T t)
    {
        float remapSmoothStep = t * t * (3 - 2 * t);
        return lerp(a, b, remapSmoothStep);
    }

    template<typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
    inline bool isPowerOfTwo(T x)
    {
        return (x != 0) && (((x - 1) & x) == 0);
    }

    template<typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
    inline T nextPowerOfTwo(T x)
    {
        if (x != 0)
        {
            --x;
            for (uint32_t shift = 1; shift < sizeof(T) * 8; shift *= 2)
                x |= (x >> shift);
        }
        return ++x;
    }

    template<typename T> inline int sgn(T val)
    {
        return (T(0) < val) - (val < T(0));
    }

    template<typename T> inline T degToRad(T x)
    {
        return static_cast<T>(x * 0.01745329252);
    }

    template<typename T> inline T radToDeg(T x)
    {
        return static_cast<T>(x * 57.295779513);
    }

    template<typename T>
    inline T clamp(T x, T lo, T hi)
    {
        return (x < lo) ? lo : ((x > hi) ? hi : x);
    }

    constexpr uint64_t INITIAL_FNV = 2166136261U;
    constexpr uint64_t FNV_MULTIPLE = 16777619;

    // Fowler / Noll / Vo (FNV) hash
    inline uint64_t fnvHash(uint64_t s)
    {
        uint64_t hash = INITIAL_FNV;
        for (uint64_t i = 0; i < sizeof(uint64_t); ++i)
        {
            hash = hash ^ (reinterpret_cast<uint8_t*>(&s)[i]); // xor the low 8 bits
            hash = hash * FNV_MULTIPLE; // multiply by the magic number
        }
        return hash;
    }

    template<class T>
    inline bool isNearlyEqual(T a, T b, T tolerance = std::numeric_limits<T>::min())
    {
        return fabs(a - b) <= tolerance;
    }
}

#endif // OUZEL_MATH_MATHUTILS_HPP
<|endoftext|>


<commit_before>
/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <boost/bind.hpp>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/connection_queue.hpp"

namespace libtorrent
{

	connection_queue::connection_queue(io_service& ios): m_next_ticket(0)
		, m_num_connecting(0)
		, m_half_open_limit(0)
		, m_timer(ios)
#ifndef NDEBUG
		, m_in_timeout_function(false)
#endif
	{
#ifdef TORRENT_CONNECTION_LOGGING
		m_log.open("connection_queue.log");
#endif
	}

	int connection_queue::free_slots() const
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_half_open_limit == 0 ? std::numeric_limits<int>::max()
			: m_half_open_limit - m_queue.size();
	}

	void connection_queue::enqueue(boost::function<void(int)> const& on_connect
		, boost::function<void()> const& on_timeout
		, time_duration timeout, int priority)
	{
		mutex_t::scoped_lock l(m_mutex);

		INVARIANT_CHECK;

		TORRENT_ASSERT(priority >= 0);
		TORRENT_ASSERT(priority < 2);

		entry* e = 0;

		switch (priority)
		{
			case 0:
				m_queue.push_back(entry());
				e = &m_queue.back();
				break;
			case 1:
				m_queue.push_front(entry());
				e = &m_queue.front();
				break;
		}

		e->priority = priority;
		e->on_connect = on_connect;
		e->on_timeout = on_timeout;
		e->ticket = m_next_ticket;
		e->timeout = timeout;
		++m_next_ticket;
		try_connect();
	}

	void connection_queue::done(int ticket)
	{
		mutex_t::scoped_lock l(m_mutex);

		INVARIANT_CHECK;

		std::list<entry>::iterator i = std::find_if(m_queue.begin()
			, m_queue.end(), boost::bind(&entry::ticket, _1) == ticket);
		if (i == m_queue.end())
		{
			// this might not be here in case on_timeout calls remove
			return;
		}
		if (i->connecting) --m_num_connecting;
		m_queue.erase(i);
		try_connect();
	}

	void connection_queue::close()
	{
		asio::error_code ec;
		m_timer.cancel(ec);
	}

	void connection_queue::limit(int limit)
	{
		TORRENT_ASSERT(limit >= 0);
		m_half_open_limit = limit;
	}

	int connection_queue::limit() const
	{ return m_half_open_limit; }

#ifndef NDEBUG

	void connection_queue::check_invariant() const
	{
		int num_connecting = 0;
		for (std::list<entry>::const_iterator i = m_queue.begin();
			i != m_queue.end(); ++i)
		{
			if (i->connecting) ++num_connecting;
		}
		TORRENT_ASSERT(num_connecting == m_num_connecting);
	}

#endif

	void connection_queue::try_connect()
	{
		INVARIANT_CHECK;

#ifdef TORRENT_CONNECTION_LOGGING
		m_log << log_time() << " " << free_slots() << std::endl;
#endif

		if (m_num_connecting >= m_half_open_limit
			&& m_half_open_limit > 0) return;

		if (m_queue.empty())
		{
			asio::error_code ec;
			m_timer.cancel(ec);
			return;
		}

		std::list<entry>::iterator i = std::find_if(m_queue.begin()
			, m_queue.end(), boost::bind(&entry::connecting, _1) == false);
		while (i != m_queue.end())
		{
			TORRENT_ASSERT(i->connecting == false);
			ptime expire = time_now() + i->timeout;
			if (m_num_connecting == 0)
			{
				asio::error_code ec;
				m_timer.expires_at(expire, ec);
				m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));
			}
			i->connecting = true;
			++m_num_connecting;
			i->expires = expire;

			INVARIANT_CHECK;

			entry& ent = *i;
			++i;
#ifndef BOOST_NO_EXCEPTIONS
			try {
#endif
				ent.on_connect(ent.ticket);
#ifndef BOOST_NO_EXCEPTIONS
			} catch (std::exception&) {}
#endif

#ifdef TORRENT_CONNECTION_LOGGING
			m_log << log_time() << " " << free_slots() << std::endl;
#endif

			if (m_num_connecting >= m_half_open_limit
				&& m_half_open_limit > 0) break;
			i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false);
		}
	}

#ifndef NDEBUG
	struct function_guard
	{
		function_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; }
		~function_guard() { val = false; }

		bool& val;
	};
#endif

	void connection_queue::on_timeout(asio::error_code const& e)
	{
		mutex_t::scoped_lock l(m_mutex);

		INVARIANT_CHECK;
#ifndef NDEBUG
		function_guard guard_(m_in_timeout_function);
#endif

		TORRENT_ASSERT(!e || e == asio::error::operation_aborted);
		if (e) return;

		ptime next_expire = max_time();
		ptime now = time_now();
		std::list<entry> timed_out;
		for (std::list<entry>::iterator i = m_queue.begin();
			!m_queue.empty() && i != m_queue.end();)
		{
			if (i->connecting && i->expires < now)
			{
				std::list<entry>::iterator j = i;
				++i;
				timed_out.splice(timed_out.end(), m_queue, j, i);
				--m_num_connecting;
				continue;
			}
			if (i->expires < next_expire)
				next_expire = i->expires;
			++i;
		}

		// we don't want to call the timeout callback while we're locked
		// since that is a recepie for dead-locks
		l.unlock();

		for (std::list<entry>::iterator i = timed_out.begin()
			, end(timed_out.end()); i != end; ++i)
		{
			try { i->on_timeout(); } catch (std::exception&) {}
		}

		l.lock();

		if (next_expire < max_time())
		{
			asio::error_code ec;
			m_timer.expires_at(next_expire, ec);
			m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));
		}
		try_connect();
	}

}

<commit_msg>msvc fix<commit_after>
/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <boost/bind.hpp>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/connection_queue.hpp"

namespace libtorrent
{

	connection_queue::connection_queue(io_service& ios): m_next_ticket(0)
		, m_num_connecting(0)
		, m_half_open_limit(0)
		, m_timer(ios)
#ifndef NDEBUG
		, m_in_timeout_function(false)
#endif
	{
#ifdef TORRENT_CONNECTION_LOGGING
		m_log.open("connection_queue.log");
#endif
	}

	int connection_queue::free_slots() const
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_half_open_limit == 0 ? (std::numeric_limits<int>::max)()
			: m_half_open_limit - m_queue.size();
	}

	void connection_queue::enqueue(boost::function<void(int)> const& on_connect
		, boost::function<void()> const& on_timeout
		, time_duration timeout, int priority)
	{
		mutex_t::scoped_lock l(m_mutex);

		INVARIANT_CHECK;

		TORRENT_ASSERT(priority >= 0);
		TORRENT_ASSERT(priority < 2);

		entry* e = 0;

		switch (priority)
		{
			case 0:
				m_queue.push_back(entry());
				e = &m_queue.back();
				break;
			case 1:
				m_queue.push_front(entry());
				e = &m_queue.front();
				break;
		}

		e->priority = priority;
		e->on_connect = on_connect;
		e->on_timeout = on_timeout;
		e->ticket = m_next_ticket;
		e->timeout = timeout;
		++m_next_ticket;
		try_connect();
	}

	void connection_queue::done(int ticket)
	{
		mutex_t::scoped_lock l(m_mutex);

		INVARIANT_CHECK;

		std::list<entry>::iterator i = std::find_if(m_queue.begin()
			, m_queue.end(), boost::bind(&entry::ticket, _1) == ticket);
		if (i == m_queue.end())
		{
			// this might not be here in case on_timeout calls remove
			return;
		}
		if (i->connecting) --m_num_connecting;
		m_queue.erase(i);
		try_connect();
	}

	void connection_queue::close()
	{
		asio::error_code ec;
		m_timer.cancel(ec);
	}

	void connection_queue::limit(int limit)
	{
		TORRENT_ASSERT(limit >= 0);
		m_half_open_limit = limit;
	}

	int connection_queue::limit() const
	{ return m_half_open_limit; }

#ifndef NDEBUG

	void connection_queue::check_invariant() const
	{
		int num_connecting = 0;
		for (std::list<entry>::const_iterator i = m_queue.begin();
			i != m_queue.end(); ++i)
		{
			if (i->connecting) ++num_connecting;
		}
		TORRENT_ASSERT(num_connecting == m_num_connecting);
	}

#endif

	void connection_queue::try_connect()
	{
		INVARIANT_CHECK;

#ifdef TORRENT_CONNECTION_LOGGING
		m_log << log_time() << " " << free_slots() << std::endl;
#endif

		if (m_num_connecting >= m_half_open_limit
			&& m_half_open_limit > 0) return;

		if (m_queue.empty())
		{
			asio::error_code ec;
			m_timer.cancel(ec);
			return;
		}

		std::list<entry>::iterator i = std::find_if(m_queue.begin()
			, m_queue.end(), boost::bind(&entry::connecting, _1) == false);
		while (i != m_queue.end())
		{
			TORRENT_ASSERT(i->connecting == false);
			ptime expire = time_now() + i->timeout;
			if (m_num_connecting == 0)
			{
				asio::error_code ec;
				m_timer.expires_at(expire, ec);
				m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));
			}
			i->connecting = true;
			++m_num_connecting;
			i->expires = expire;

			INVARIANT_CHECK;

			entry& ent = *i;
			++i;
#ifndef BOOST_NO_EXCEPTIONS
			try {
#endif
				ent.on_connect(ent.ticket);
#ifndef BOOST_NO_EXCEPTIONS
			} catch (std::exception&) {}
#endif

#ifdef TORRENT_CONNECTION_LOGGING
			m_log << log_time() << " " << free_slots() << std::endl;
#endif

			if (m_num_connecting >= m_half_open_limit
				&& m_half_open_limit > 0) break;
			i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false);
		}
	}

#ifndef NDEBUG
	struct function_guard
	{
		function_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; }
		~function_guard() { val = false; }

		bool& val;
	};
#endif

	void connection_queue::on_timeout(asio::error_code const& e)
	{
		mutex_t::scoped_lock l(m_mutex);

		INVARIANT_CHECK;
#ifndef NDEBUG
		function_guard guard_(m_in_timeout_function);
#endif

		TORRENT_ASSERT(!e || e == asio::error::operation_aborted);
		if (e) return;

		ptime next_expire = max_time();
		ptime now = time_now();
		std::list<entry> timed_out;
		for (std::list<entry>::iterator i = m_queue.begin();
			!m_queue.empty() && i != m_queue.end();)
		{
			if (i->connecting && i->expires < now)
			{
				std::list<entry>::iterator j = i;
				++i;
				timed_out.splice(timed_out.end(), m_queue, j, i);
				--m_num_connecting;
				continue;
			}
			if (i->expires < next_expire)
				next_expire = i->expires;
			++i;
		}

		// we don't want to call the timeout callback while we're locked
		// since that is a recepie for dead-locks
		l.unlock();

		for (std::list<entry>::iterator i = timed_out.begin()
			, end(timed_out.end()); i != end; ++i)
		{
			try { i->on_timeout(); } catch (std::exception&) {}
		}

		l.lock();

		if (next_expire < max_time())
		{
			asio::error_code ec;
			m_timer.expires_at(next_expire, ec);
			m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));
		}
		try_connect();
	}

}

<|endoftext|>


<commit_before>/*
 *
 *    <COPYRIGHT>
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

/**
 *    @file
 *      This file implements a QRCode Setup Payload generator in accordance
 *      with the CHIP specification.
 *
 */

#include "QRCodeSetupPayloadGenerator.h"
#include "SetupCodeUtils.h"

#include <iostream>
#include <stdlib.h>

using namespace chip;
using namespace std;

// Populates numberOfBits starting from LSB of input into bits, which is assumed to be zero-initialized
static void populateBits(uint8_t * bits, int & offset, uint64_t input, size_t numberOfBits)
{
    // do nothing in the case where we've overflowed. should never happen
    if (offset + numberOfBits > kTotalPayloadDataSizeInBits || input >= 1 << numberOfBits)
    {
        return;
    }

    int index = offset;
    offset += numberOfBits;
    while (input != 0)
    {
        if (input & 1)
        {
            bits[index / 8] |= 1 << index % 8;
        }
        index++;
        input >>= 1;
    }
}

static void generateBitSet(SetupPayload & payload, uint8_t * bits)
{
    int offset = 0;

    populateBits(bits, offset, payload.version, kVersionFieldLengthInBits);
    populateBits(bits, offset, payload.vendorID, kVendorIDFieldLengthInBits);
    populateBits(bits, offset, payload.productID, kProductIDFieldLengthInBits);
    populateBits(bits, offset, payload.requiresCustomFlow, kCustomFlowRequiredFieldLengthInBits);
    populateBits(bits, offset, payload.rendezvousInformation, kRendezvousInfoFieldLengthInBits);
    populateBits(bits, offset, payload.discriminator, kPayloadDiscriminatorFieldLengthInBits);
    populateBits(bits, offset, payload.setUpPINCode, kSetupPINCodeFieldLengthInBits);
    populateBits(bits, offset, 0, kReservedFieldLengthInBits);
}

string QRCodeSetupPayloadGenerator::payloadBinaryRepresentation()
{
    if (mPayload.isValid())
    {
        uint8_t bits[kTotalPayloadDataSizeInBits / 8] = { 0 };

        generateBitSet(mPayload, bits);

        string binary;
        for (int i = sizeof(bits) / sizeof(bits[0]) - 1; i >= 0; i--)
        {
            for (unsigned j = 1 << 8; j != 0;)
            {
                j >>= 1;
                binary += bits[i] & j ? "1" : "0";
            }
        }
        return binary;
    }
    return string();
}

string QRCodeSetupPayloadGenerator::payloadBase45Representation()
{
    if (mPayload.isValid())
    {
        uint8_t bits[kTotalPayloadDataSizeInBits / 8] = { 0 };

        generateBitSet(mPayload, bits);

        return base45Encode(bits, sizeof(bits) / sizeof(bits[0]));
    }
    return string();
}
<commit_msg>use size in bytes, in case bits isn't a multiple of 8<commit_after>/*
 *
 *    <COPYRIGHT>
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

/**
 *    @file
 *      This file implements a QRCode Setup Payload generator in accordance
 *      with the CHIP specification.
 *
 */

#include "QRCodeSetupPayloadGenerator.h"
#include "SetupCodeUtils.h"

#include <iostream>
#include <stdlib.h>

using namespace chip;
using namespace std;

// Populates numberOfBits starting from LSB of input into bits, which is assumed to be zero-initialized
static void populateBits(uint8_t * bits, int & offset, uint64_t input, size_t numberOfBits)
{
    // do nothing in the case where we've overflowed. should never happen
    if (offset + numberOfBits > kTotalPayloadDataSizeInBits || input >= 1 << numberOfBits)
    {
        return;
    }

    int index = offset;
    offset += numberOfBits;
    while (input != 0)
    {
        if (input & 1)
        {
            bits[index / 8] |= 1 << index % 8;
        }
        index++;
        input >>= 1;
    }
}

static void generateBitSet(SetupPayload & payload, uint8_t * bits)
{
    int offset = 0;

    populateBits(bits, offset, payload.version, kVersionFieldLengthInBits);
    populateBits(bits, offset, payload.vendorID, kVendorIDFieldLengthInBits);
    populateBits(bits, offset, payload.productID, kProductIDFieldLengthInBits);
    populateBits(bits, offset, payload.requiresCustomFlow, kCustomFlowRequiredFieldLengthInBits);
    populateBits(bits, offset, payload.rendezvousInformation, kRendezvousInfoFieldLengthInBits);
    populateBits(bits, offset, payload.discriminator, kPayloadDiscriminatorFieldLengthInBits);
    populateBits(bits, offset, payload.setUpPINCode, kSetupPINCodeFieldLengthInBits);
    populateBits(bits, offset, 0, kReservedFieldLengthInBits);
}

string QRCodeSetupPayloadGenerator::payloadBinaryRepresentation()
{
    if (mPayload.isValid())
    {
        uint8_t bits[kTotalPayloadDataSizeInBytes] = { 0 };

        generateBitSet(mPayload, bits);

        string binary;
        for (int i = sizeof(bits) / sizeof(bits[0]) - 1; i >= 0; i--)
        {
            for (unsigned j = 1 << 8; j != 0;)
            {
                j >>= 1;
                binary += bits[i] & j ? "1" : "0";
            }
        }
        return binary;
    }
    return string();
}

string QRCodeSetupPayloadGenerator::payloadBase45Representation()
{
    if (mPayload.isValid())
    {
        uint8_t bits[kTotalPayloadDataSizeInBytes] = { 0 };

        generateBitSet(mPayload, bits);

        return base45Encode(bits, sizeof(bits) / sizeof(bits[0]));
    }
    return string();
}
<|endoftext|>


<commit_before>///
/// @file  prime_iterator.cpp
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve.h>
#include <primesieve/soe/prime_iterator.h>
#include <primesieve/soe/primesieve_error.h>

#include <algorithm>
#include <cmath>
#include <string>
#include <vector>

namespace primesieve {

prime_iterator::prime_iterator(uint64_t start)
{
  skip_to(start);
}

void prime_iterator::skip_to(uint64_t start)
{
  first_ = true;
  adjust_skip_to_ = false;
  i_ = 0;
  count_ = 0;
  start_ = start;

  if (start_ > max_stop())
    throw primesieve_error("start must be <= " + max_stop_string());

  if (!primes_.empty() &&
       primes_.front() <= start_ &&
       primes_.back() >= start_)
  {
    adjust_skip_to_ = true;
    i_ = std::lower_bound(primes_.begin(), primes_.end(), start_) - primes_.begin();
  }
}

/// Calculate an interval size that ensures a good load balance.
/// @param n  Start or stop number.
///
uint64_t prime_iterator::get_interval_size(uint64_t n)
{
  count_++;
  const uint64_t KILOBYTE = 1 << 10;
  const uint64_t MEGABYTE = 1 << 20;

  double x = std::max(static_cast<double>(n), 10.0);
  double sqrtx = std::sqrt(x);
  uint64_t sqrtx_primes = static_cast<uint64_t>(sqrtx / (std::log(sqrtx) - 1));

  uint64_t max_primes = (MEGABYTE * 512) / sizeof(uint64_t);
  uint64_t primes = ((count_ < 10) ? (KILOBYTE * 32) : (MEGABYTE * 4))  / sizeof(uint64_t);
  primes = std::min(std::max(primes, sqrtx_primes), max_primes);

  return static_cast<uint64_t>(primes * std::log(x));
}

void prime_iterator::generate_primes(uint64_t start, uint64_t stop)
{
  primes_.clear();
  primesieve::generate_primes(start, stop, &primes_);
  if (primes_.empty())
    primes_.push_back(0);
}

void prime_iterator::generate_next_primes()
{
  if (adjust_skip_to_)
  {
    adjust_skip_to_ = false;
    if (i_ > 0 && primes_[i_ - 1] >= start_)
      i_--;
  }
  else
  {
    uint64_t start = (first_) ? start_ : primes_.back() + 1;
    uint64_t interval_size = get_interval_size(start);
    uint64_t stop = (start < max_stop() - interval_size) ? start + interval_size : max_stop();
    generate_primes(start, stop);
    i_ = 0;
  }
  first_ = false;
}

void prime_iterator::generate_previous_primes()
{
  if (adjust_skip_to_)
  {
    adjust_skip_to_ = false;
    if (i_ > 0 && primes_[i_] > start_)
      i_--;
  }
  else
  {
    uint64_t stop = start_;
    if (!first_)
      stop = (primes_.front() > 1) ? primes_.front() - 1 : 0;
    uint64_t interval_size = get_interval_size(stop);
    uint64_t start = (stop > interval_size) ? stop - interval_size : 0;
    generate_primes(start, stop);
    i_ = primes_.size();
  }
  first_ = false;
}

} // end namespace
<commit_msg>Update prime_iterator.cpp<commit_after>///
/// @file  prime_iterator.cpp
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve.h>
#include <primesieve/soe/prime_iterator.h>
#include <primesieve/soe/primesieve_error.h>

#include <algorithm>
#include <cmath>
#include <string>
#include <vector>

namespace primesieve {

prime_iterator::prime_iterator(uint64_t start)
{
  skip_to(start);
}

void prime_iterator::skip_to(uint64_t start)
{
  first_ = true;
  adjust_skip_to_ = false;
  i_ = 0;
  count_ = 0;
  start_ = start;

  if (start_ > max_stop())
    throw primesieve_error("start must be <= " + max_stop_string());

  if (!primes_.empty() &&
       primes_.front() <= start_ &&
       primes_.back() >= start_)
  {
    adjust_skip_to_ = true;
    i_ = std::lower_bound(primes_.begin(), primes_.end(), start_) - primes_.begin();
  }
}

void prime_iterator::generate_primes(uint64_t start, uint64_t stop)
{
  primes_.clear();
  primesieve::generate_primes(start, stop, &primes_);
  if (primes_.empty())
    primes_.push_back(0);
}

void prime_iterator::generate_next_primes()
{
  if (adjust_skip_to_)
  {
    adjust_skip_to_ = false;
    if (i_ > 0 && primes_[i_ - 1] >= start_)
      i_--;
  }
  else
  {
    uint64_t start = (first_) ? start_ : primes_.back() + 1;
    uint64_t interval_size = get_interval_size(start);
    uint64_t stop = (start < max_stop() - interval_size) ? start + interval_size : max_stop();
    generate_primes(start, stop);
    i_ = 0;
  }
  first_ = false;
}

void prime_iterator::generate_previous_primes()
{
  if (adjust_skip_to_)
  {
    adjust_skip_to_ = false;
    if (i_ > 0 && primes_[i_] > start_)
      i_--;
  }
  else
  {
    uint64_t stop = start_;
    if (!first_)
      stop = (primes_.front() > 1) ? primes_.front() - 1 : 0;
    uint64_t interval_size = get_interval_size(stop);
    uint64_t start = (stop > interval_size) ? stop - interval_size : 0;
    generate_primes(start, stop);
    i_ = primes_.size();
  }
  first_ = false;
}

/// Calculate an interval size that ensures a good load balance.
/// @param n  Start or stop number.
///
uint64_t prime_iterator::get_interval_size(uint64_t n)
{
  count_++;
  const uint64_t KILOBYTE = 1 << 10;
  const uint64_t MEGABYTE = 1 << 20;

  double x = std::max(static_cast<double>(n), 10.0);
  double sqrtx = std::sqrt(x);
  uint64_t sqrtx_primes = static_cast<uint64_t>(sqrtx / (std::log(sqrtx) - 1));

  uint64_t max_primes = (MEGABYTE * 512) / sizeof(uint64_t);
  uint64_t primes = ((count_ < 10) ? (KILOBYTE * 32) : (MEGABYTE * 4))  / sizeof(uint64_t);
  primes = std::min(std::max(primes, sqrtx_primes), max_primes);

  return static_cast<uint64_t>(primes * std::log(x));
}

} // end namespace
<|endoftext|>


<commit_before>//Copyright 2016 Adam G. Smith
//
//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 <cstdio>
#include <ctype.h>
#include "solaire/serial/xml.hpp"

namespace solaire { namespace serial {

	struct element {
		typedef std::pair<std::string, std::string> attribute;

		std::vector<attribute> attributes;
		std::vector<element> children;
		std::string body;
		std::string name;
	};

	void child_value(const element&, value_parser&, const xml_conflict_mode);

	element from_xml_tree(std::istream& aStream) {
		//! \todo Implement
		return element();
	}

	void primative_value(const std::string& aValue, value_parser& aParser) {
		//! \todo Implement
	}

	inline void primative_value(const std::string& aName, const std::string& aValue, value_parser& aParser) {
		aParser.name(aName.c_str());
		primative_value(aValue, aParser);
	}

	inline void body_value(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		primative_value(aElement.name, aElement.body, aParser);
	}

	inline void attribute_value(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		primative_value(aElement.attributes[0].second, aParser);
	}

	void attribute_object(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_object();
		for(const element::attribute& i : aElement.attributes) {
			primative_value(i.first, i.second, aParser);
		}
		aParser.end_object();
	}

	void attribute_array(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_array();
		for(const element::attribute& i : aElement.attributes) {
			primative_value(i.second, aParser);
		}
		aParser.begin_array();
	}

	void child_object(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_object();
		for(const element& i : aElement.children) {
			aParser.name(i.name.c_str());
			child_value(aElement, aParser, aConflictMode);
		}
		aParser.end_object();
	}

	void child_array(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_array();
		for(const element& i : aElement.children) {
			child_value(aElement, aParser, aConflictMode);
		}
		aParser.begin_array();
	}

	void attribute_child_object(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_object();
		for(const element::attribute& i : aElement.attributes) {
			primative_value(i.first, i.second, aParser);
		}
		for(const element& i : aElement.children) {
			aParser.name(i.name.c_str());
			child_value(aElement, aParser, aConflictMode);
		}
		aParser.end_object();
	}

	void attribute_child_array(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_array();
		for(const element::attribute& i : aElement.attributes) {
			primative_value(i.second, aParser);
		}
		for(const element& i : aElement.children) {
			child_value(aElement, aParser, aConflictMode);
		}
		aParser.begin_array();
	}

	bool is_attribute_array(const element& aElement) {
		//! \todo implement
		return false;
	}

	bool is_object_array(const element& aElement) {
		for(const element& i : aElement.children) {
			if(i.name == "value") continue;
			else if(i.name == "array") continue;
			else if(i.name == "object") continue;
			else return false;
		}
		return true;
	}

	void pure_attribute(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		if(aElement.attributes.size() == 1 && aElement.attributes[0].first == "value") primative_value(aElement.attributes[0].second, aParser);
		else if(is_attribute_array(aElement)) attribute_array(aElement, aParser, aConflictMode);
		else attribute_object(aElement, aParser, aConflictMode);
	}

	void pure_children(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		if(aElement.children.size() == 1) child_value(aElement.children[0], aParser, aConflictMode);
		else if(is_object_array(aElement)) child_array(aElement, aParser, aConflictMode);
		else child_object(aElement, aParser, aConflictMode);
	}

	void mixed_attribute_children(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		const bool aa = is_attribute_array(aElement);
		const bool oa = is_object_array(aElement);
		if(aa && oa) attribute_child_array(aElement, aParser, aConflictMode);
		else if(aa && ! oa) throw std::runtime_error("solaire::serial::from_xml : Attribute array / Child object");
		else if (oa && !aa) throw std::runtime_error("solaire::serial::from_xml : Attribute object / Child array");
		else attribute_child_object(aElement, aParser, aConflictMode);
	}

	void child_value(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		const bool body = ! aElement.body.empty();
		const bool attributes = ! aElement.attributes.empty();
		const bool children = ! aElement.children.empty();

		if(attributes || children) {
			if(body) {
				switch(aConflictMode)
				{
				case XML_CONFLICT_IGNORE_BODY :
					pure_attribute(aElement, aParser, aConflictMode);
					break;
				case XML_CONFLICT_IGNORE_ATTRIBUTES :
					body_value(aElement, aParser, aConflictMode);
					break;
				default: // XML_CONFLICT_ERROR
					throw std::runtime_error("solaire::serial::from_xml : Element with both body value and attributes (XML_CONFLICT_ERROR)");
				}
			}else {
				if(attributes && ! children) {
					pure_attribute(aElement, aParser, aConflictMode);
				}else if (children && ! attributes) {
					pure_children(aElement, aParser, aConflictMode);
				}else {
					mixed_attribute_children(aElement, aParser, aConflictMode);
				}
			}
		}else if(body) {
			body_value(aElement, aParser, aConflictMode);
		}else {
			aParser.value_void();
		}
	}

	void from_xml(std::istream& aStream, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		child_value(from_xml_tree(aStream), aParser, aConflictMode);
	}

	// to_xml

	//! \todo Add header element

	to_xml::to_xml(std::ostream& aStream) :
		mStream(aStream)
	{}

	void to_xml::write_value(const char* const aValue) {
		state& tmp = mStateStack.back();
		++tmp.size;
		if(tmp.is_array) mName = "value";
		mStream << '<' << mName.c_str() << " value=\"" << aValue << "\"/>";
	}

	void to_xml::begin_array() {
		if(mStateStack.empty() || mStateStack.back().is_array) mName = "array";
		state tmp;
		tmp.size = 0;
		tmp.is_object = 1;
		mStateStack.push_back(tmp);
		mStream << '<' << mName.c_str() << '>';
	}

	void to_xml::end_array() {
		const state tmp = mStateStack.back();
		mStateStack.pop_back();
		if (tmp.is_object) mName = "array";
		mStream << '</' << mName.c_str() << '>';
	}

	void to_xml::begin_object() {
		if(mStateStack.empty() || mStateStack.back().is_array) mName = "object";
		state tmp;
		tmp.size = 0;
		tmp.is_object = 1;
		mStateStack.push_back(tmp);
		mStream << '<' << mName.c_str() << '>';
	}

	void to_xml::end_object() {
		const state tmp = mStateStack.back();
		mStateStack.pop_back();
		if(tmp.is_object) mName = "object";
		mStream << '<' << '/' << mName.c_str() << '>';
		//! \todo Write primative members as attributes
	}

	void to_xml::name(const char* aName) {
		mName = aName;
	}

	void to_xml::value_void() {
		write_value("void");
	}

	void to_xml::value_bool(const bool aValue) {
		write_value(aValue ? "true" : "false");
	}

	void to_xml::value_char(const char aValue) {
		const char tmp[2] = { aValue, '\0' };
		write_value(tmp);
	}

	void to_xml::value_unsigned(const uint64_t aValue) {
		char buffer[32];
		snprintf(buffer, 32, "%llu", aValue);
		write_value(buffer);
	}

	void to_xml::value_signed(const int64_t aValue) {
		char buffer[32];
		snprintf(buffer, 32, "%lli", aValue);
		write_value(buffer);
	}

	void to_xml::value_float(const double aValue) {
		char buffer[32];
		snprintf(buffer, 32, "%lf", aValue);
		write_value(buffer);
	}

	void to_xml::value_pointer(void* const aValue) {
		char buffer[32];
		buffer[0] = '#';
		snprintf(buffer + 1, 31, "%llu", *reinterpret_cast<uint64_t* const*>(&aValue));
		write_value(buffer);
	}

	void to_xml::value_string(const char* const aValue) {
		write_value(aValue);
	}

}}<commit_msg>Implemented is_attribute_array<commit_after>//Copyright 2016 Adam G. Smith
//
//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 <cstdio>
#include <ctype.h>
#include "solaire/serial/xml.hpp"

namespace solaire { namespace serial {

	struct element {
		typedef std::pair<std::string, std::string> attribute;

		std::vector<attribute> attributes;
		std::vector<element> children;
		std::string body;
		std::string name;
	};

	void child_value(const element&, value_parser&, const xml_conflict_mode);

	element from_xml_tree(std::istream& aStream) {
		//! \todo Implement
		return element();
	}

	void primative_value(const std::string& aValue, value_parser& aParser) {
		//! \todo Implement
	}

	inline void primative_value(const std::string& aName, const std::string& aValue, value_parser& aParser) {
		aParser.name(aName.c_str());
		primative_value(aValue, aParser);
	}

	inline void body_value(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		primative_value(aElement.name, aElement.body, aParser);
	}

	inline void attribute_value(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		primative_value(aElement.attributes[0].second, aParser);
	}

	void attribute_object(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_object();
		for(const element::attribute& i : aElement.attributes) {
			primative_value(i.first, i.second, aParser);
		}
		aParser.end_object();
	}

	void attribute_array(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_array();
		for(const element::attribute& i : aElement.attributes) {
			primative_value(i.second, aParser);
		}
		aParser.begin_array();
	}

	void child_object(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_object();
		for(const element& i : aElement.children) {
			aParser.name(i.name.c_str());
			child_value(aElement, aParser, aConflictMode);
		}
		aParser.end_object();
	}

	void child_array(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_array();
		for(const element& i : aElement.children) {
			child_value(aElement, aParser, aConflictMode);
		}
		aParser.begin_array();
	}

	void attribute_child_object(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_object();
		for(const element::attribute& i : aElement.attributes) {
			primative_value(i.first, i.second, aParser);
		}
		for(const element& i : aElement.children) {
			aParser.name(i.name.c_str());
			child_value(aElement, aParser, aConflictMode);
		}
		aParser.end_object();
	}

	void attribute_child_array(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		aParser.begin_array();
		for(const element::attribute& i : aElement.attributes) {
			primative_value(i.second, aParser);
		}
		for(const element& i : aElement.children) {
			child_value(aElement, aParser, aConflictMode);
		}
		aParser.begin_array();
	}

	bool is_attribute_array(const element& aElement) {
		uint32_t i = 0;
		char buf[32];
		for(const element::attribute& j : aElement.attributes) {
			for(const char c : j.first) if (c < '0' || c >= '9') return false;
			uint64_t tmp;
			sscanf(buf, "%llu", &tmp);
			if(tmp != i) return false;
			++i;
		}
		return true;
	}

	bool is_object_array(const element& aElement) {
		for(const element& i : aElement.children) {
			if(i.name == "value") continue;
			else if(i.name == "array") continue;
			else if(i.name == "object") continue;
			else return false;
		}
		return true;
	}

	void pure_attribute(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		if(aElement.attributes.size() == 1 && aElement.attributes[0].first == "value") primative_value(aElement.attributes[0].second, aParser);
		else if(is_attribute_array(aElement)) attribute_array(aElement, aParser, aConflictMode);
		else attribute_object(aElement, aParser, aConflictMode);
	}

	void pure_children(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		if(aElement.children.size() == 1) child_value(aElement.children[0], aParser, aConflictMode);
		else if(is_object_array(aElement)) child_array(aElement, aParser, aConflictMode);
		else child_object(aElement, aParser, aConflictMode);
	}

	void mixed_attribute_children(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		const bool aa = is_attribute_array(aElement);
		const bool oa = is_object_array(aElement);
		if(aa && oa) attribute_child_array(aElement, aParser, aConflictMode);
		else if(aa && ! oa) throw std::runtime_error("solaire::serial::from_xml : Attribute array / Child object");
		else if (oa && !aa) throw std::runtime_error("solaire::serial::from_xml : Attribute object / Child array");
		else attribute_child_object(aElement, aParser, aConflictMode);
	}

	void child_value(const element& aElement, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		const bool body = ! aElement.body.empty();
		const bool attributes = ! aElement.attributes.empty();
		const bool children = ! aElement.children.empty();

		if(attributes || children) {
			if(body) {
				switch(aConflictMode)
				{
				case XML_CONFLICT_IGNORE_BODY :
					pure_attribute(aElement, aParser, aConflictMode);
					break;
				case XML_CONFLICT_IGNORE_ATTRIBUTES :
					body_value(aElement, aParser, aConflictMode);
					break;
				default: // XML_CONFLICT_ERROR
					throw std::runtime_error("solaire::serial::from_xml : Element with both body value and attributes (XML_CONFLICT_ERROR)");
				}
			}else {
				if(attributes && ! children) {
					pure_attribute(aElement, aParser, aConflictMode);
				}else if (children && ! attributes) {
					pure_children(aElement, aParser, aConflictMode);
				}else {
					mixed_attribute_children(aElement, aParser, aConflictMode);
				}
			}
		}else if(body) {
			body_value(aElement, aParser, aConflictMode);
		}else {
			aParser.value_void();
		}
	}

	void from_xml(std::istream& aStream, value_parser& aParser, const xml_conflict_mode aConflictMode) {
		child_value(from_xml_tree(aStream), aParser, aConflictMode);
	}

	// to_xml

	//! \todo Add header element

	to_xml::to_xml(std::ostream& aStream) :
		mStream(aStream)
	{}

	void to_xml::write_value(const char* const aValue) {
		state& tmp = mStateStack.back();
		++tmp.size;
		if(tmp.is_array) mName = "value";
		mStream << '<' << mName.c_str() << " value=\"" << aValue << "\"/>";
	}

	void to_xml::begin_array() {
		if(mStateStack.empty() || mStateStack.back().is_array) mName = "array";
		state tmp;
		tmp.size = 0;
		tmp.is_object = 1;
		mStateStack.push_back(tmp);
		mStream << '<' << mName.c_str() << '>';
	}

	void to_xml::end_array() {
		const state tmp = mStateStack.back();
		mStateStack.pop_back();
		if (tmp.is_object) mName = "array";
		mStream << '</' << mName.c_str() << '>';
	}

	void to_xml::begin_object() {
		if(mStateStack.empty() || mStateStack.back().is_array) mName = "object";
		state tmp;
		tmp.size = 0;
		tmp.is_object = 1;
		mStateStack.push_back(tmp);
		mStream << '<' << mName.c_str() << '>';
	}

	void to_xml::end_object() {
		const state tmp = mStateStack.back();
		mStateStack.pop_back();
		if(tmp.is_object) mName = "object";
		mStream << '<' << '/' << mName.c_str() << '>';
		//! \todo Write primative members as attributes
	}

	void to_xml::name(const char* aName) {
		mName = aName;
	}

	void to_xml::value_void() {
		write_value("void");
	}

	void to_xml::value_bool(const bool aValue) {
		write_value(aValue ? "true" : "false");
	}

	void to_xml::value_char(const char aValue) {
		const char tmp[2] = { aValue, '\0' };
		write_value(tmp);
	}

	void to_xml::value_unsigned(const uint64_t aValue) {
		char buffer[32];
		snprintf(buffer, 32, "%llu", aValue);
		write_value(buffer);
	}

	void to_xml::value_signed(const int64_t aValue) {
		char buffer[32];
		snprintf(buffer, 32, "%lli", aValue);
		write_value(buffer);
	}

	void to_xml::value_float(const double aValue) {
		char buffer[32];
		snprintf(buffer, 32, "%lf", aValue);
		write_value(buffer);
	}

	void to_xml::value_pointer(void* const aValue) {
		char buffer[32];
		buffer[0] = '#';
		snprintf(buffer + 1, 31, "%llu", *reinterpret_cast<uint64_t* const*>(&aValue));
		write_value(buffer);
	}

	void to_xml::value_string(const char* const aValue) {
		write_value(aValue);
	}

}}<|endoftext|>


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

#include "chrome/nacl/nacl_thread.h"

#include "chrome/common/notification_service.h"
#include "chrome/common/nacl_messages.h"

// This is ugly.  We need an interface header file for the exported
// sel_ldr interfaces.
// TODO(gregoryd,sehr): Add an interface header.
#if defined(OS_WIN)
typedef HANDLE NaClHandle;
#else
typedef int NaClHandle;
#endif  // NaClHandle

// This is currently necessary because we have a conflict between
// NaCl's "struct NaClThread" and Chromium's "class NaClThread".
extern "C" int NaClMainForChromium(int handle_count, const NaClHandle* handles);

NaClThread::NaClThread() {
}

NaClThread::~NaClThread() {
}

NaClThread* NaClThread::current() {
  return static_cast<NaClThread*>(ChildThread::current());
}

void NaClThread::OnControlMessageReceived(const IPC::Message& msg) {
  IPC_BEGIN_MESSAGE_MAP(NaClThread, msg)
    IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStartSelLdr)
  IPC_END_MESSAGE_MAP()
}

void NaClThread::OnStartSelLdr(std::vector<nacl::FileDescriptor> handles) {
  NaClHandle* array = new NaClHandle[handles.size()];
  for (size_t i = 0; i < handles.size(); i++) {
    array[i] = nacl::ToNativeHandle(handles[i]);
  }
  NaClMainForChromium(static_cast<int>(handles.size()), array);
  delete array;
}
<commit_msg>nacl: Use a scoped_array rather than a bare pointer.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/nacl/nacl_thread.h"

#include "base/scoped_ptr.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/nacl_messages.h"

// This is ugly.  We need an interface header file for the exported
// sel_ldr interfaces.
// TODO(gregoryd,sehr): Add an interface header.
#if defined(OS_WIN)
typedef HANDLE NaClHandle;
#else
typedef int NaClHandle;
#endif  // NaClHandle

// This is currently necessary because we have a conflict between
// NaCl's "struct NaClThread" and Chromium's "class NaClThread".
extern "C" int NaClMainForChromium(int handle_count, const NaClHandle* handles);

NaClThread::NaClThread() {
}

NaClThread::~NaClThread() {
}

NaClThread* NaClThread::current() {
  return static_cast<NaClThread*>(ChildThread::current());
}

void NaClThread::OnControlMessageReceived(const IPC::Message& msg) {
  IPC_BEGIN_MESSAGE_MAP(NaClThread, msg)
    IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStartSelLdr)
  IPC_END_MESSAGE_MAP()
}

void NaClThread::OnStartSelLdr(std::vector<nacl::FileDescriptor> handles) {
  scoped_array<NaClHandle> array(new NaClHandle[handles.size()]);
  for (size_t i = 0; i < handles.size(); i++) {
    array[i] = nacl::ToNativeHandle(handles[i]);
  }
  NaClMainForChromium(static_cast<int>(handles.size()), array.get());
}
<|endoftext|>


<commit_before>/*
    This file is part of KContactManager.

    Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kuniqueapplication.h>

#include "mainwindow.h"

int main( int argc, char **argv )
{
  KAboutData *about = new KAboutData( "kcontactmanager", 0, ki18n( "KContactManager" ),
                                      "0.1", ki18n( "The KDE Contact Management Application" ),
                                      KAboutData::License_GPL_V2,
                                      ki18n( "(c) 2007-2009 The KDE PIM Team" ) );
  about->addAuthor( ki18n( "Tobias Koenig" ), ki18n( "Current maintainer" ), "tokoe@kde.org" );

  KCmdLineArgs::init( argc, argv, about );

  KCmdLineOptions options;
  KCmdLineArgs::addCmdLineOptions( options );
  KUniqueApplication::addCmdLineOptions();

  if ( !KUniqueApplication::start() )
    exit( 0 );

  KUniqueApplication app;

  MainWindow *window = new MainWindow;
  window->show();

  app.exec();
}
<commit_msg>start Akonadi if it is not yet running<commit_after>/*
    This file is part of KContactManager.

    Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kuniqueapplication.h>
#include <akonadi/control.h>

#include "mainwindow.h"

int main( int argc, char **argv )
{
  KAboutData *about = new KAboutData( "kcontactmanager", 0, ki18n( "KContactManager" ),
                                      "0.1", ki18n( "The KDE Contact Management Application" ),
                                      KAboutData::License_GPL_V2,
                                      ki18n( "(c) 2007-2009 The KDE PIM Team" ) );
  about->addAuthor( ki18n( "Tobias Koenig" ), ki18n( "Current maintainer" ), "tokoe@kde.org" );

  KCmdLineArgs::init( argc, argv, about );

  KCmdLineOptions options;
  KCmdLineArgs::addCmdLineOptions( options );
  KUniqueApplication::addCmdLineOptions();

  if ( !KUniqueApplication::start() )
    exit( 0 );

  KUniqueApplication app;

  MainWindow *window = new MainWindow;
  window->show();

  Akonadi::Control::start( window );

  app.exec();
}
<|endoftext|>


<commit_before>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap
 *
 * Copyright 2012 Matthew McCormick
 *
 * 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 <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib> // EXIT_SUCCESS, atoi()
#include <getopt.h> // getopt_long

#include "version.h"
#include "graph.h"

// Tmux color lookup tables for the different metrics.
#include "luts.h"

#include "cpu.h"
#include "memory.h"
#include "load.h"

#include "powerline.h"

std::string cpu_string( CPU_MODE cpu_mode, unsigned int cpu_usage_delay, unsigned int graph_lines,
    bool use_colors = false,
    bool use_powerline_left = false, bool use_powerline_right = false )
{

  float percentage;
  float multiplier = 1.0f;

  //output stuff
  std::ostringstream oss;
  oss.precision( 1 );
  oss.setf( std::ios::fixed | std::ios::right );

  // get %
  percentage = cpu_percentage( cpu_usage_delay );

  // set multiplier to number of threads ?
  if ( cpu_mode == CPU_MODE_THREADS )
  {
    multiplier = get_cpu_count();
  }

  // if percentage*multiplier >= 100, remove decimal point to keep number short
  if ( percentage*multiplier >= 100.0f )
  {
    oss.precision( 0 );
  }

  unsigned int percent = static_cast<unsigned int>( percentage );
  if( use_colors )
  {
    if( use_powerline_right )
    {
      powerline( oss, cpu_percentage_lut[percent], POWERLINE_RIGHT );
    }
    else if( use_powerline_left )
    {
      powerline( oss, cpu_percentage_lut[percent], POWERLINE_LEFT );
    }
    else
    {
      powerline( oss, cpu_percentage_lut[percent], NONE );
    }
  }

  if( graph_lines > 0)
  {
    oss << " [";
    oss << get_graph_by_percentage( unsigned( percentage ), graph_lines );
    oss << "]";
  }
  oss.width( 5 );
  oss << percentage * multiplier;
  oss << "%";
  if( use_colors )
  {
    if( use_powerline_left )
    {
      powerline( oss, cpu_percentage_lut[percent], POWERLINE_LEFT, true );
    }
    else if( !use_powerline_right )
    {
      oss << "#[fg=default,bg=default]";
    }
  }

  return oss.str();
}

void print_help()
{
  using std::cout;
  using std::endl;

  cout << "tmux-mem-cpu-load v" << tmux_mem_cpu_load_VERSION << endl
    << "Usage: tmux-mem-cpu-load [OPTIONS]\n\n"
    << "Available options:\n"
    << "-h, --help\n"
    << "\t Prints this help message\n"
    << "-c, --colors\n"
    << "\tUse tmux colors in output\n"
    << "-p, --powerline-left\n"
    << "\tUse powerline left symbols throughout the output, enables --colors\n"
    << "-q, --powerline-right\n"
    << "\tUse powerline right symbols throughout the output, enables --colors\n"
    << "-i <value>, --interval <value>\n"
    << "\tSet tmux status refresh interval in seconds. Default: 1 second\n"
    << "-g <value>, --graph-lines <value>\n"
    << "\tSet how many lines should be drawn in a graph. Default: 10\n"
    << "-m <value>, --mem-mode <value>\n"
    << "\tSet memory display mode. 0: Default, 1: Free memory, 2: Usage percent.\n"
    << "-t <value>, --cpu-mode <value>\n"
    << "\tSet cpu % display mode. 0: Default max 100%, 1: Max 100% * number of threads. \n"
    << "-a <value>, --averages-count <value>\n"
    << "\tSet how many load-averages should be drawn. Default: 3\n"
    << endl;
}

int main( int argc, char** argv )
{
  unsigned cpu_usage_delay = 990000;
  short averages_count = 3;
  short graph_lines = 10; // max 32767 should be enough
  bool use_colors = false;
  bool use_powerline_left = false;
  bool use_powerline_right = false;
  MEMORY_MODE mem_mode = MEMORY_MODE_DEFAULT;
  CPU_MODE cpu_mode = CPU_MODE_DEFAULT;

  static struct option long_options[] =
  {
    // Struct is a s follows:
    //   const char * name, int has_arg, int *flag, int val
    // if *flag is null, val is option identifier to use in switch()
    // otherwise it's a value to set the variable *flag points to
    { "help", no_argument, NULL, 'h' },
    { "colors", no_argument, NULL, 'c' },
    { "powerline-left", no_argument, NULL, 'p' },
    { "powerline-right", no_argument, NULL, 'q' },
    { "interval", required_argument, NULL, 'i' },
    { "graph-lines", required_argument, NULL, 'g' },
    { "mem-mode", required_argument, NULL, 'm' },
    { "cpu-mode", required_argument, NULL, 't' },
    { "averages-count", required_argument, NULL, 'a' },
    { 0, 0, 0, 0 } // used to handle unknown long options
  };

  int c;
  // while c != -1
  while( (c = getopt_long( argc, argv, "hi:cpqg:m:a:t:", long_options, NULL) ) != -1 )
  {
    switch( c )
    {
      case 'h': // --help, -h
        print_help();
        return EXIT_FAILURE;
        break;
      case 'c': // --colors
        use_colors = true;
        break;
      case 'p': // --powerline-left
        use_colors = true;
        use_powerline_left = true;
        break;
      case 'q': // --powerline-right
        use_colors = true;
        use_powerline_right = true;
        break;
      case 'i': // --interval, -i
        if( atoi( optarg ) < 1 )
          {
            std::cerr << "Status interval argument must be one or greater.\n";
            return EXIT_FAILURE;
          }
        cpu_usage_delay = atoi( optarg ) * 1000000 - 10000;
        break;
      case 'g': // --graph-lines, -g
        if( atoi( optarg ) < 0 )
          {
            std::cerr << "Graph lines argument must be zero or greater.\n";
            return EXIT_FAILURE;
          }
        graph_lines = atoi( optarg );
        break;
      case 'm': // --mem-mode, -m
        if( atoi( optarg ) < 0 )
          {
            std::cerr << "Memory mode argument must be zero or greater.\n";
            return EXIT_FAILURE;
          }
        mem_mode = static_cast< MEMORY_MODE >( atoi( optarg ) );
        break;
      case 't': // --cpu-mode, -t
        if( atoi( optarg ) < 0 )
          {
            std::cerr << "CPU mode argument must be zero or greater.\n";
            return EXIT_FAILURE;
          }
        cpu_mode = static_cast< CPU_MODE >( atoi( optarg ) );
        break;
      case 'a': // --averages-count, -a
        if( atoi( optarg ) < 0 || atoi( optarg ) > 3 )
          {
            std::cerr << "Valid averages-count arguments are: 0, 1, 2, 3\n";
            return EXIT_FAILURE;
          }
        averages_count = atoi( optarg );
        break;
      case '?':
        // getopt_long prints error message automatically
        return EXIT_FAILURE;
        break;
      default:
        std::cerr << "?? getopt returned character code 0 " << c << std::endl;
        return EXIT_FAILURE;
    }
  }
  // Detect old option specification and return and error message.
  if( argc > optind )
  {
    std::cout <<
      "The interval and graph lines options are now specified with flags.\n\n";
    print_help();
    return EXIT_FAILURE;
  }

  MemoryStatus memory_status;
  mem_status( memory_status );
  std::cout << mem_string( memory_status, mem_mode, use_colors, use_powerline_left, use_powerline_right )
    << cpu_string( cpu_mode, cpu_usage_delay, graph_lines, use_colors, use_powerline_left, use_powerline_right )
    << load_string( use_colors, use_powerline_left, use_powerline_right, averages_count );

  std::cout << std::endl;

  return EXIT_SUCCESS;
}

<commit_msg>Specify precision in CPU percent output<commit_after>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap
 *
 * Copyright 2012 Matthew McCormick
 *
 * 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 <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib> // EXIT_SUCCESS, atoi()
#include <getopt.h> // getopt_long

#include "version.h"
#include "graph.h"

// Tmux color lookup tables for the different metrics.
#include "luts.h"

#include "cpu.h"
#include "memory.h"
#include "load.h"

#include "powerline.h"

std::string cpu_string( CPU_MODE cpu_mode, unsigned int cpu_usage_delay, unsigned int graph_lines,
    bool use_colors = false,
    bool use_powerline_left = false, bool use_powerline_right = false )
{

  float percentage;
  float multiplier = 1.0f;

  //output stuff
  std::ostringstream oss;
  oss.precision( 1 );
  oss.setf( std::ios::fixed | std::ios::right );

  // get %
  percentage = cpu_percentage( cpu_usage_delay );

  // set multiplier to number of threads ?
  if ( cpu_mode == CPU_MODE_THREADS )
  {
    multiplier = get_cpu_count();
  }

  // if percentage*multiplier >= 100, remove decimal point to keep number short
  if ( percentage*multiplier >= 100.0f )
  {
    oss.precision( 0 );
  }

  unsigned int percent = static_cast<unsigned int>( percentage );
  if( use_colors )
  {
    if( use_powerline_right )
    {
      powerline( oss, cpu_percentage_lut[percent], POWERLINE_RIGHT );
    }
    else if( use_powerline_left )
    {
      powerline( oss, cpu_percentage_lut[percent], POWERLINE_LEFT );
    }
    else
    {
      powerline( oss, cpu_percentage_lut[percent], NONE );
    }
  }

  if( graph_lines > 0)
  {
    oss << " [";
    oss << get_graph_by_percentage( unsigned( percentage ), graph_lines );
    oss << "]";
  }
  oss.width( 5 );
  oss.setf( std::ios::fixed, std::ios::floatfield );
  oss.precision( 1 );
  oss.fill( ' ' );
  oss << std::right << percentage * multiplier;
  oss << "%";
  if( use_colors )
  {
    if( use_powerline_left )
    {
      powerline( oss, cpu_percentage_lut[percent], POWERLINE_LEFT, true );
    }
    else if( !use_powerline_right )
    {
      oss << "#[fg=default,bg=default]";
    }
  }

  return oss.str();
}

void print_help()
{
  using std::cout;
  using std::endl;

  cout << "tmux-mem-cpu-load v" << tmux_mem_cpu_load_VERSION << endl
    << "Usage: tmux-mem-cpu-load [OPTIONS]\n\n"
    << "Available options:\n"
    << "-h, --help\n"
    << "\t Prints this help message\n"
    << "-c, --colors\n"
    << "\tUse tmux colors in output\n"
    << "-p, --powerline-left\n"
    << "\tUse powerline left symbols throughout the output, enables --colors\n"
    << "-q, --powerline-right\n"
    << "\tUse powerline right symbols throughout the output, enables --colors\n"
    << "-i <value>, --interval <value>\n"
    << "\tSet tmux status refresh interval in seconds. Default: 1 second\n"
    << "-g <value>, --graph-lines <value>\n"
    << "\tSet how many lines should be drawn in a graph. Default: 10\n"
    << "-m <value>, --mem-mode <value>\n"
    << "\tSet memory display mode. 0: Default, 1: Free memory, 2: Usage percent.\n"
    << "-t <value>, --cpu-mode <value>\n"
    << "\tSet cpu % display mode. 0: Default max 100%, 1: Max 100% * number of threads. \n"
    << "-a <value>, --averages-count <value>\n"
    << "\tSet how many load-averages should be drawn. Default: 3\n"
    << endl;
}

int main( int argc, char** argv )
{
  unsigned cpu_usage_delay = 990000;
  short averages_count = 3;
  short graph_lines = 10; // max 32767 should be enough
  bool use_colors = false;
  bool use_powerline_left = false;
  bool use_powerline_right = false;
  MEMORY_MODE mem_mode = MEMORY_MODE_DEFAULT;
  CPU_MODE cpu_mode = CPU_MODE_DEFAULT;

  static struct option long_options[] =
  {
    // Struct is a s follows:
    //   const char * name, int has_arg, int *flag, int val
    // if *flag is null, val is option identifier to use in switch()
    // otherwise it's a value to set the variable *flag points to
    { "help", no_argument, NULL, 'h' },
    { "colors", no_argument, NULL, 'c' },
    { "powerline-left", no_argument, NULL, 'p' },
    { "powerline-right", no_argument, NULL, 'q' },
    { "interval", required_argument, NULL, 'i' },
    { "graph-lines", required_argument, NULL, 'g' },
    { "mem-mode", required_argument, NULL, 'm' },
    { "cpu-mode", required_argument, NULL, 't' },
    { "averages-count", required_argument, NULL, 'a' },
    { 0, 0, 0, 0 } // used to handle unknown long options
  };

  int c;
  // while c != -1
  while( (c = getopt_long( argc, argv, "hi:cpqg:m:a:t:", long_options, NULL) ) != -1 )
  {
    switch( c )
    {
      case 'h': // --help, -h
        print_help();
        return EXIT_FAILURE;
        break;
      case 'c': // --colors
        use_colors = true;
        break;
      case 'p': // --powerline-left
        use_colors = true;
        use_powerline_left = true;
        break;
      case 'q': // --powerline-right
        use_colors = true;
        use_powerline_right = true;
        break;
      case 'i': // --interval, -i
        if( atoi( optarg ) < 1 )
          {
            std::cerr << "Status interval argument must be one or greater.\n";
            return EXIT_FAILURE;
          }
        cpu_usage_delay = atoi( optarg ) * 1000000 - 10000;
        break;
      case 'g': // --graph-lines, -g
        if( atoi( optarg ) < 0 )
          {
            std::cerr << "Graph lines argument must be zero or greater.\n";
            return EXIT_FAILURE;
          }
        graph_lines = atoi( optarg );
        break;
      case 'm': // --mem-mode, -m
        if( atoi( optarg ) < 0 )
          {
            std::cerr << "Memory mode argument must be zero or greater.\n";
            return EXIT_FAILURE;
          }
        mem_mode = static_cast< MEMORY_MODE >( atoi( optarg ) );
        break;
      case 't': // --cpu-mode, -t
        if( atoi( optarg ) < 0 )
          {
            std::cerr << "CPU mode argument must be zero or greater.\n";
            return EXIT_FAILURE;
          }
        cpu_mode = static_cast< CPU_MODE >( atoi( optarg ) );
        break;
      case 'a': // --averages-count, -a
        if( atoi( optarg ) < 0 || atoi( optarg ) > 3 )
          {
            std::cerr << "Valid averages-count arguments are: 0, 1, 2, 3\n";
            return EXIT_FAILURE;
          }
        averages_count = atoi( optarg );
        break;
      case '?':
        // getopt_long prints error message automatically
        return EXIT_FAILURE;
        break;
      default:
        std::cerr << "?? getopt returned character code 0 " << c << std::endl;
        return EXIT_FAILURE;
    }
  }
  // Detect old option specification and return and error message.
  if( argc > optind )
  {
    std::cout <<
      "The interval and graph lines options are now specified with flags.\n\n";
    print_help();
    return EXIT_FAILURE;
  }

  MemoryStatus memory_status;
  mem_status( memory_status );
  std::cout << mem_string( memory_status, mem_mode, use_colors, use_powerline_left, use_powerline_right )
    << cpu_string( cpu_mode, cpu_usage_delay, graph_lines, use_colors, use_powerline_left, use_powerline_right )
    << load_string( use_colors, use_powerline_left, use_powerline_right, averages_count );

  std::cout << std::endl;

  return EXIT_SUCCESS;
}

<|endoftext|>