<commit_before>// Copyright (c) 2012 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 "ash/system/ime/tray_ime.h"

#include <vector>

#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_views.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_strings.h"
#include "grit/ui_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"

namespace ash {
namespace internal {

namespace tray {

class IMEDefaultView : public TrayItemMore {
 public:
  explicit IMEDefaultView(SystemTrayItem* owner)
      : TrayItemMore(owner) {
    ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();

    SetImage(bundle.GetImageNamed(
        IDR_AURA_UBER_TRAY_IME).ToSkBitmap());

    IMEInfo info;
    Shell::GetInstance()->tray_delegate()->GetCurrentIME(&info);
    UpdateLabel(info);
  }

  virtual ~IMEDefaultView() {}

  void UpdateLabel(const IMEInfo& info) {
    SetLabel(info.name);
    SetAccessibleName(info.name);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};

class IMEDetailedView : public views::View,
                        public ViewClickListener {
 public:
  IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
      : login_(login),
        header_(NULL) {
    SetLayoutManager(new views::BoxLayout(
        views::BoxLayout::kVertical, 1, 1, 1));
    set_background(views::Background::CreateSolidBackground(kBackgroundColor));
    SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
    IMEInfoList list;
    delegate->GetAvailableIMEList(&list);
    IMEPropertyInfoList property_list;
    delegate->GetCurrentIMEProperties(&property_list);
    Update(list, property_list);
  }

  virtual ~IMEDetailedView() {}

  void Update(const IMEInfoList& list,
              const IMEPropertyInfoList& property_list) {
    RemoveAllChildViews(true);

    header_ = NULL;

    AppendHeaderEntry();
    AppendIMEList(list);
    if (!property_list.empty())
      AppendIMEProperties(property_list);
    if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
      AppendSettings();

    Layout();
    SchedulePaint();
  }

 private:
  void AppendHeaderEntry() {
    header_ = CreateDetailedHeaderEntry(IDS_ASH_STATUS_TRAY_IME, this);
    AddChildView(header_);
  }

  void AppendIMEList(const IMEInfoList& list) {
    views::View* imes = new views::View;
    imes->SetLayoutManager(new views::BoxLayout(
        views::BoxLayout::kVertical, 0, 0, 1));
    for (size_t i = 0; i < list.size(); i++) {
      HoverHighlightView* container = new HoverHighlightView(this);
      container->AddLabel(list[i].name,
          list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
      imes->AddChildView(container);
      ime_map_[container] = list[i].id;
    }
    imes->set_border(views::Border::CreateSolidSidedBorder(1, 0, 1, 0,
        kBorderLightColor));
    AddChildView(imes);
  }

  void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
    views::View* properties = new views::View;
    properties->SetLayoutManager(new views::BoxLayout(
        views::BoxLayout::kVertical, 0, 0, 1));
    for (size_t i = 0; i < property_list.size(); i++) {
      HoverHighlightView* container = new HoverHighlightView(this);
      container->AddLabel(
          property_list[i].name,
          property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
      properties->AddChildView(container);
      property_map_[container] = property_list[i].key;
    }
    properties->set_border(views::Border::CreateSolidSidedBorder(
        0, 0, 1, 0, kBorderLightColor));
    AddChildView(properties);
  }

  void AppendSettings() {
    HoverHighlightView* container = new HoverHighlightView(this);
    container->AddLabel(ui::ResourceBundle::GetSharedInstance().
        GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
        gfx::Font::NORMAL);
    AddChildView(container);
    settings_ = container;
  }

  // Overridden from ViewClickListener.
  virtual void ClickedOn(views::View* sender) OVERRIDE {
    SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
    if (sender == header_) {
      Shell::GetInstance()->tray()->ShowDefaultView();
    } else if (sender == settings_) {
      delegate->ShowIMESettings();
    } else {
      std::map<views::View*, std::string>::const_iterator ime_find;
      ime_find = ime_map_.find(sender);
      if (ime_find != ime_map_.end()) {
        std::string ime_id = ime_find->second;
        delegate->SwitchIME(ime_id);
        GetWidget()->Close();
      } else {
        std::map<views::View*, std::string>::const_iterator prop_find;
        prop_find = property_map_.find(sender);
        if (prop_find != property_map_.end()) {
          std::string key = prop_find->second;
          delegate->ActivateIMEProperty(key);
          GetWidget()->Close();
        }
      }
    }
  }

  user::LoginStatus login_;

  std::map<views::View*, std::string> ime_map_;
  std::map<views::View*, std::string> property_map_;
  views::View* header_;
  views::View* settings_;

  DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};

}  // namespace tray

TrayIME::TrayIME() {
}

TrayIME::~TrayIME() {
}

void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
  tray_label_->SetText(current.short_name);
  tray_label_->SetVisible(count > 1);
}

views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
  tray_label_.reset(new views::Label);
  SetupLabelForTray(tray_label_.get());
  tray_label_->set_border(
      views::Border::CreateEmptyBorder(0, 2, 0, 2));
  return tray_label_.get();
}

views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
  default_.reset(new tray::IMEDefaultView(this));
  return default_.get();
}

views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
  detailed_.reset(new tray::IMEDetailedView(this, status));
  return detailed_.get();
}

void TrayIME::DestroyTrayView() {
  tray_label_.reset();
}

void TrayIME::DestroyDefaultView() {
  default_.reset();
}

void TrayIME::DestroyDetailedView() {
  detailed_.reset();
}

void TrayIME::OnIMERefresh() {
  SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
  IMEInfoList list;
  IMEInfo current;
  IMEPropertyInfoList property_list;
  delegate->GetCurrentIME(&current);
  delegate->GetAvailableIMEList(&list);
  delegate->GetCurrentIMEProperties(&property_list);

  UpdateTrayLabel(current, list.size());

  if (default_.get())
    default_->UpdateLabel(current);
  if (detailed_.get())
    detailed_->Update(list, property_list);
}

}  // namespace internal
}  // namespace ash
<commit_msg>Clear ime_map_ and ime_property_map_ when mappings are recreated.<commit_after>// Copyright (c) 2012 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 "ash/system/ime/tray_ime.h"

#include <vector>

#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_views.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_strings.h"
#include "grit/ui_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"

namespace ash {
namespace internal {

namespace tray {

class IMEDefaultView : public TrayItemMore {
 public:
  explicit IMEDefaultView(SystemTrayItem* owner)
      : TrayItemMore(owner) {
    ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();

    SetImage(bundle.GetImageNamed(
        IDR_AURA_UBER_TRAY_IME).ToSkBitmap());

    IMEInfo info;
    Shell::GetInstance()->tray_delegate()->GetCurrentIME(&info);
    UpdateLabel(info);
  }

  virtual ~IMEDefaultView() {}

  void UpdateLabel(const IMEInfo& info) {
    SetLabel(info.name);
    SetAccessibleName(info.name);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};

class IMEDetailedView : public views::View,
                        public ViewClickListener {
 public:
  IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
      : login_(login),
        header_(NULL) {
    SetLayoutManager(new views::BoxLayout(
        views::BoxLayout::kVertical, 1, 1, 1));
    set_background(views::Background::CreateSolidBackground(kBackgroundColor));
    SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
    IMEInfoList list;
    delegate->GetAvailableIMEList(&list);
    IMEPropertyInfoList property_list;
    delegate->GetCurrentIMEProperties(&property_list);
    Update(list, property_list);
  }

  virtual ~IMEDetailedView() {}

  void Update(const IMEInfoList& list,
              const IMEPropertyInfoList& property_list) {
    RemoveAllChildViews(true);

    header_ = NULL;

    AppendHeaderEntry();
    AppendIMEList(list);
    if (!property_list.empty())
      AppendIMEProperties(property_list);
    if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
      AppendSettings();

    Layout();
    SchedulePaint();
  }

 private:
  void AppendHeaderEntry() {
    header_ = CreateDetailedHeaderEntry(IDS_ASH_STATUS_TRAY_IME, this);
    AddChildView(header_);
  }

  void AppendIMEList(const IMEInfoList& list) {
    ime_map_.clear();
    views::View* imes = new views::View;
    imes->SetLayoutManager(new views::BoxLayout(
        views::BoxLayout::kVertical, 0, 0, 1));
    for (size_t i = 0; i < list.size(); i++) {
      HoverHighlightView* container = new HoverHighlightView(this);
      container->AddLabel(list[i].name,
          list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
      imes->AddChildView(container);
      ime_map_[container] = list[i].id;
    }
    imes->set_border(views::Border::CreateSolidSidedBorder(1, 0, 1, 0,
        kBorderLightColor));
    AddChildView(imes);
  }

  void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
    property_map_.clear();
    views::View* properties = new views::View;
    properties->SetLayoutManager(new views::BoxLayout(
        views::BoxLayout::kVertical, 0, 0, 1));
    for (size_t i = 0; i < property_list.size(); i++) {
      HoverHighlightView* container = new HoverHighlightView(this);
      container->AddLabel(
          property_list[i].name,
          property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
      properties->AddChildView(container);
      property_map_[container] = property_list[i].key;
    }
    properties->set_border(views::Border::CreateSolidSidedBorder(
        0, 0, 1, 0, kBorderLightColor));
    AddChildView(properties);
  }

  void AppendSettings() {
    HoverHighlightView* container = new HoverHighlightView(this);
    container->AddLabel(ui::ResourceBundle::GetSharedInstance().
        GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
        gfx::Font::NORMAL);
    AddChildView(container);
    settings_ = container;
  }

  // Overridden from ViewClickListener.
  virtual void ClickedOn(views::View* sender) OVERRIDE {
    SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
    if (sender == header_) {
      Shell::GetInstance()->tray()->ShowDefaultView();
    } else if (sender == settings_) {
      delegate->ShowIMESettings();
    } else {
      std::map<views::View*, std::string>::const_iterator ime_find;
      ime_find = ime_map_.find(sender);
      if (ime_find != ime_map_.end()) {
        std::string ime_id = ime_find->second;
        delegate->SwitchIME(ime_id);
        GetWidget()->Close();
      } else {
        std::map<views::View*, std::string>::const_iterator prop_find;
        prop_find = property_map_.find(sender);
        if (prop_find != property_map_.end()) {
          std::string key = prop_find->second;
          delegate->ActivateIMEProperty(key);
          GetWidget()->Close();
        }
      }
    }
  }

  user::LoginStatus login_;

  std::map<views::View*, std::string> ime_map_;
  std::map<views::View*, std::string> property_map_;
  views::View* header_;
  views::View* settings_;

  DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};

}  // namespace tray

TrayIME::TrayIME() {
}

TrayIME::~TrayIME() {
}

void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
  tray_label_->SetText(current.short_name);
  tray_label_->SetVisible(count > 1);
}

views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
  tray_label_.reset(new views::Label);
  SetupLabelForTray(tray_label_.get());
  tray_label_->set_border(
      views::Border::CreateEmptyBorder(0, 2, 0, 2));
  return tray_label_.get();
}

views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
  default_.reset(new tray::IMEDefaultView(this));
  return default_.get();
}

views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
  detailed_.reset(new tray::IMEDetailedView(this, status));
  return detailed_.get();
}

void TrayIME::DestroyTrayView() {
  tray_label_.reset();
}

void TrayIME::DestroyDefaultView() {
  default_.reset();
}

void TrayIME::DestroyDetailedView() {
  detailed_.reset();
}

void TrayIME::OnIMERefresh() {
  SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
  IMEInfoList list;
  IMEInfo current;
  IMEPropertyInfoList property_list;
  delegate->GetCurrentIME(&current);
  delegate->GetAvailableIMEList(&list);
  delegate->GetCurrentIMEProperties(&property_list);

  UpdateTrayLabel(current, list.size());

  if (default_.get())
    default_->UpdateLabel(current);
  if (detailed_.get())
    detailed_->Update(list, property_list);
}

}  // namespace internal
}  // namespace ash
<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "ui/views/controls/slider.h"

#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/view.h"

namespace {

void ClickAt(views::View* view, int x, int y) {
  views::MouseEvent press(ui::ET_MOUSE_PRESSED, x, y, ui::EF_LEFT_MOUSE_BUTTON);
  view->OnMousePressed(press);
  views::MouseEvent release(ui::ET_MOUSE_RELEASED, x, y,
      ui::EF_LEFT_MOUSE_BUTTON);
  view->OnMouseReleased(release);
}

}

namespace views {

TEST(SliderTest, UpdateFromClick) {
  Slider* slider = new Slider(NULL, Slider::HORIZONTAL);
  View* view = slider;
  gfx::Size size = view->GetPreferredSize();
  view->SetSize(size);

  ClickAt(view, 0, 0);
  EXPECT_EQ(0.0f, slider->value());

  ClickAt(view, view->width(), 0);
  EXPECT_EQ(1.0f, slider->value());
}

TEST(SliderTest, UpdateFromClickRTL) {
  std::string locale = l10n_util::GetApplicationLocale("");
  base::i18n::SetICUDefaultLocale("he");

  Slider* slider = new Slider(NULL, Slider::HORIZONTAL);
  View* view = slider;
  gfx::Size size = view->GetPreferredSize();
  view->SetSize(size);

  ClickAt(view, 0, 0);
  EXPECT_EQ(1.0f, slider->value());

  ClickAt(view, view->width(), 0);
  EXPECT_EQ(0.0f, slider->value());

  // Reset locale.
  base::i18n::SetICUDefaultLocale(locale);
}

}  // namespace views
<commit_msg>Fix leak in SliderTest<commit_after>// Copyright (c) 2012 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 "ui/views/controls/slider.h"

#include "base/memory/scoped_ptr.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/view.h"

namespace {

void ClickAt(views::View* view, int x, int y) {
  views::MouseEvent press(ui::ET_MOUSE_PRESSED, x, y, ui::EF_LEFT_MOUSE_BUTTON);
  view->OnMousePressed(press);
  views::MouseEvent release(ui::ET_MOUSE_RELEASED, x, y,
      ui::EF_LEFT_MOUSE_BUTTON);
  view->OnMouseReleased(release);
}

}

namespace views {

TEST(SliderTest, UpdateFromClick) {
  scoped_ptr<Slider> slider(new Slider(NULL, Slider::HORIZONTAL));
  View* view = slider.get();
  gfx::Size size = view->GetPreferredSize();
  view->SetSize(size);

  ClickAt(view, 0, 0);
  EXPECT_EQ(0.0f, slider->value());

  ClickAt(view, view->width(), 0);
  EXPECT_EQ(1.0f, slider->value());
}

TEST(SliderTest, UpdateFromClickRTL) {
  std::string locale = l10n_util::GetApplicationLocale("");
  base::i18n::SetICUDefaultLocale("he");

  scoped_ptr<Slider> slider(new Slider(NULL, Slider::HORIZONTAL));
  View* view = slider.get();
  gfx::Size size = view->GetPreferredSize();
  view->SetSize(size);

  ClickAt(view, 0, 0);
  EXPECT_EQ(1.0f, slider->value());

  ClickAt(view, view->width(), 0);
  EXPECT_EQ(0.0f, slider->value());

  // Reset locale.
  base::i18n::SetICUDefaultLocale(locale);
}

}  // namespace views
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>

#include "Display.h"
#include "Application.h"
#include "Util/Random.h"
#include "Util/Config.h"
#include "Util/ConfigParser.h"
#include "Util/Singleton.h"

namespace
{
    void initilize()
    {
        Random  ::init();
        Display ::init();
    }

    void loadConfig()
    {
        const std::string fileName = "HopsonCraft.conf";
        std::ifstream inFile (fileName);

        if(inFile.is_open())
        {
            Singleton<Config>::get().loadFromStream(fileName, inFile);
        }
    }
}

int main() try
{
    initilize();
    loadConfig();

    Application app;
    app.runMainGameLoop();

    return 0;
}
catch(std::exception& e)
{
    std::cout << e.what() << std::endl;
    std::cin.ignore();
}

<commit_msg>Fix black screen<commit_after>#include <iostream>
#include <fstream>

#include "Display.h"
#include "Application.h"
#include "Util/Random.h"
#include "Util/Config.h"
#include "Util/ConfigParser.h"
#include "Util/Singleton.h"

#include "World/Block/Block_Database.h"

namespace
{
    void initilize()
    {
        Random  ::init();
        Display ::init();

        Block::Database::get();
    }

    void loadConfig()
    {
        const std::string fileName = "HopsonCraft.conf";
        std::ifstream inFile (fileName);

        if(inFile.is_open())
        {
            Singleton<Config>::get().loadFromStream(fileName, inFile);
        }
    }
}

int main() try
{
    initilize();
    //loadConfig();

    Application app;
    app.runMainGameLoop();

    return 0;
}
catch(std::exception& e)
{
    std::cout << e.what() << std::endl;
    std::cin.ignore();
}

<|endoftext|>


<commit_before>/** \copyright
 * Copyright (c) 2013, Balazs Racz
 * 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.
 *
 * 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 HOLDER 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.
 *
 * \file main.cxx
 *
 * An application which acts as an openlcb hub with the GC protocol.
 *
 * @author Balazs Racz
 * @date 3 Aug 2013
 */

#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <unistd.h>

#include <memory>

#include "os/os.h"
#include "utils/constants.hxx"
#include "utils/Hub.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/ClientConnection.hxx"
#include "executor/Executor.hxx"
#include "executor/Service.hxx"

Executor<1> g_executor("g_executor", 0, 1024);
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);

OVERRIDE_CONST(gc_generate_newlines, 0);

int port = 12021;
const char *device_path = nullptr;
int upstream_port = 12021;
const char *upstream_host = nullptr;
bool timestamped = false;

void usage(const char *e)
{
    fprintf(stderr, "Usage: %s [-p port] [-d device_path] [-u upstream_host] "
                    "[-q upstream_port] [-t]\n\n",
            e);
    fprintf(stderr, "GridConnect CAN HUB.\nListens to a specific TCP port, "
                    "reads CAN packets from the incoming connections using "
                    "the GridConnect protocol, and forwards all incoming "
                    "packets to all other participants.\n\nArguments:\n");
    fprintf(stderr, "\t-p port     specifies the port number to listen on, "
                    "default is 12021.\n");
    fprintf(stderr, "\t-d device   is a path to a physical device doing "
                    "serial-CAN or USB-CAN. If specified, opens device and "
                    "adds it to the hub.\n");
    fprintf(stderr, "\t-u upstream_host   is the host name for an upstream "
                    "hub. If specified, this hub will connect to an upstream "
                    "hub.\n");
    fprintf(stderr,
            "\t-q upstream_port   is the port number for the upstream hub.\n");
    fprintf(stderr,
            "\t-t prints timestamps for each packet.\n");
    exit(1);
}

void parse_args(int argc, char *argv[])
{
    int opt;
    while ((opt = getopt(argc, argv, "hp:d:u:q:t")) >= 0)
    {
        switch (opt)
        {
            case 'h':
                usage(argv[0]);
                break;
            case 'd':
                device_path = optarg;
                break;
            case 'p':
                port = atoi(optarg);
                break;
            case 'u':
                upstream_host = optarg;
                break;
            case 'q':
                upstream_port = atoi(optarg);
                break;
            case 't':
                timestamped = true;
                break;
            default:
                fprintf(stderr, "Unknown option %c\n", opt);
                usage(argv[0]);
        }
    }
}

/** Entry point to application.
 * @param argc number of command line arguments
 * @param argv array of command line arguments
 * @return 0, should never return
 */
int appl_main(int argc, char *argv[])
{
    parse_args(argc, argv);
    GcPacketPrinter packet_printer(&can_hub0, timestamped);
    GcTcpHub hub(&can_hub0, port);
    vector<std::unique_ptr<ConnectionClient>> connections;

    if (upstream_host)
    {
        connections.emplace_back(new UpstreamConnectionClient(
                                     "upstream", &can_hub0, upstream_host, upstream_port));
    }

    if (device_path)
    {
        connections.emplace_back(
            new DeviceConnectionClient("device", &can_hub0, device_path));
    }

    while (1)
    {
        for (const auto &p : connections)
        {
            p->ping();
        }
        sleep(1);
    }
    return 0;
}
<commit_msg>Makes the hub binary batch gridconnect bytes in fewer packets.<commit_after>/** \copyright
 * Copyright (c) 2013, Balazs Racz
 * 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.
 *
 * 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 HOLDER 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.
 *
 * \file main.cxx
 *
 * An application which acts as an openlcb hub with the GC protocol.
 *
 * @author Balazs Racz
 * @date 3 Aug 2013
 */

#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <unistd.h>

#include <memory>

#include "os/os.h"
#include "utils/constants.hxx"
#include "utils/Hub.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/ClientConnection.hxx"
#include "executor/Executor.hxx"
#include "executor/Service.hxx"

Executor<1> g_executor("g_executor", 0, 1024);
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);

OVERRIDE_CONST(gc_generate_newlines, 0);
OVERRIDE_CONST(gridconnect_buffer_size, 1300);
OVERRIDE_CONST(gridconnect_buffer_delay_usec, 2000);

int port = 12021;
const char *device_path = nullptr;
int upstream_port = 12021;
const char *upstream_host = nullptr;
bool timestamped = false;

void usage(const char *e)
{
    fprintf(stderr, "Usage: %s [-p port] [-d device_path] [-u upstream_host] "
                    "[-q upstream_port] [-t]\n\n",
            e);
    fprintf(stderr, "GridConnect CAN HUB.\nListens to a specific TCP port, "
                    "reads CAN packets from the incoming connections using "
                    "the GridConnect protocol, and forwards all incoming "
                    "packets to all other participants.\n\nArguments:\n");
    fprintf(stderr, "\t-p port     specifies the port number to listen on, "
                    "default is 12021.\n");
    fprintf(stderr, "\t-d device   is a path to a physical device doing "
                    "serial-CAN or USB-CAN. If specified, opens device and "
                    "adds it to the hub.\n");
    fprintf(stderr, "\t-u upstream_host   is the host name for an upstream "
                    "hub. If specified, this hub will connect to an upstream "
                    "hub.\n");
    fprintf(stderr,
            "\t-q upstream_port   is the port number for the upstream hub.\n");
    fprintf(stderr,
            "\t-t prints timestamps for each packet.\n");
    exit(1);
}

void parse_args(int argc, char *argv[])
{
    int opt;
    while ((opt = getopt(argc, argv, "hp:d:u:q:t")) >= 0)
    {
        switch (opt)
        {
            case 'h':
                usage(argv[0]);
                break;
            case 'd':
                device_path = optarg;
                break;
            case 'p':
                port = atoi(optarg);
                break;
            case 'u':
                upstream_host = optarg;
                break;
            case 'q':
                upstream_port = atoi(optarg);
                break;
            case 't':
                timestamped = true;
                break;
            default:
                fprintf(stderr, "Unknown option %c\n", opt);
                usage(argv[0]);
        }
    }
}

/** Entry point to application.
 * @param argc number of command line arguments
 * @param argv array of command line arguments
 * @return 0, should never return
 */
int appl_main(int argc, char *argv[])
{
    parse_args(argc, argv);
    GcPacketPrinter packet_printer(&can_hub0, timestamped);
    GcTcpHub hub(&can_hub0, port);
    vector<std::unique_ptr<ConnectionClient>> connections;

    if (upstream_host)
    {
        connections.emplace_back(new UpstreamConnectionClient(
                                     "upstream", &can_hub0, upstream_host, upstream_port));
    }

    if (device_path)
    {
        connections.emplace_back(
            new DeviceConnectionClient("device", &can_hub0, device_path));
    }

    while (1)
    {
        for (const auto &p : connections)
        {
            p->ping();
        }
        sleep(1);
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "text/table.h"
#include "text/cmdline.h"
#include "cortex/class.h"
#include "cortex/cortex.h"
#include "math/clamp.hpp"
#include "math/random.hpp"
#include "math/numeric.hpp"
#include "tensor/numeric.hpp"
#include "cortex/measure.hpp"
#include "cortex/accumulator.h"
#include "text/table_row_mark.h"
#include "cortex/measure_and_log.hpp"
#include "cortex/layers/make_layers.h"
#include "cortex/tasks/task_charset.h"

int main(int argc, const char *argv[])
{
        using namespace nano;

        // parse the command line
        nano::cmdline_t cmdline("benchmark models");
        cmdline.add("s", "samples",     "number of samples to use [100, 100000]", "10000");
        cmdline.add("", "mlps",         "benchmark MLP models");
        cmdline.add("", "convnets",     "benchmark convolution networks");
        cmdline.add("", "forward",      "evaluate the \'forward\' pass (output)");
        cmdline.add("", "backward",     "evaluate the \'backward' pass (gradient)");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto cmd_samples = nano::clamp(cmdline.get<size_t>("samples"), 100, 100 * 1000);
        const auto cmd_forward = cmdline.has("forward");
        const auto cmd_backward = cmdline.has("backward");
        const auto cmd_mlps = cmdline.has("mlps");
        const auto cmd_convnets = cmdline.has("convnets");

        if (!cmd_forward && !cmd_backward)
        {
                cmdline.usage();
        }

        if (!cmd_mlps && !cmd_convnets)
        {
                cmdline.usage();
        }

        const tensor_size_t cmd_rows = 28;
        const tensor_size_t cmd_cols = 28;
        const color_mode cmd_color = color_mode::luma;

        const size_t cmd_min_nthreads = 1;
        const size_t cmd_max_nthreads = nano::logical_cpus();

        // generate synthetic task
        charset_task_t task(charset::digit, cmd_color, cmd_rows, cmd_cols, cmd_samples);
        task.load();

        // construct models
        const string_t mlp0;
        const string_t mlp1 = mlp0 + make_affine_layer(100);
        const string_t mlp2 = mlp1 + make_affine_layer(100);
        const string_t mlp3 = mlp2 + make_affine_layer(100);
        const string_t mlp4 = mlp3 + make_affine_layer(100);
        const string_t mlp5 = mlp4 + make_affine_layer(100);

        const string_t convnetk2d_9x9p_5x5p_3x3 =
                make_conv_pool_layer("conv-k2d", 16, 9, 9, 1) +
                make_conv_pool_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4);

        const string_t convnettoe_9x9p_5x5p_3x3 =
                nano::replace(convnetk2d_9x9p_5x5p_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_11x11_9x9_7x7_3x3 =
                make_conv_layer("conv-k2d", 16, 11, 11, 1) +
                make_conv_layer("conv-k2d", 32, 9, 9, 2) +
                make_conv_layer("conv-k2d", 64, 7, 7, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_11x11_9x9_7x7_3x3 =
                nano::replace(convnetk2d_11x11_9x9_7x7_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_9x9_7x7_7x7_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 9, 9, 1) +
                make_conv_layer("conv-k2d", 32, 7, 7, 2) +
                make_conv_layer("conv-k2d", 32, 7, 7, 4) +
                make_conv_layer("conv-k2d", 64, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_9x9_7x7_7x7_5x5_3x3 =
                nano::replace(convnetk2d_9x9_7x7_7x7_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 7, 7, 1) +
                make_conv_layer("conv-k2d", 16, 7, 7, 2) +
                make_conv_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 32, 5, 5, 4) +
                make_conv_layer("conv-k2d", 32, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4);

        const string_t convnettoe_7x7_7x7_5x5_5x5_5x5_3x3 =
                nano::replace(convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 5, 5, 1) +
                make_conv_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 64, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 5, 5, 8) +
                make_conv_layer("conv-k2d", 64, 5, 5, 8) +
                make_conv_layer("conv-k2d", 64, 5, 5, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_5x5_5x5_5x5_5x5_5x5_5x5_3x3 =
                nano::replace(convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3 =
                make_conv_layer("conv-k2d", 16, 3, 3, 1) +
                make_conv_layer("conv-k2d", 32, 3, 3, 2) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3 =
                nano::replace(convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3, "conv-k2d", "conv-toe");

        const string_t outlayer = make_output_layer(task.osize());

        std::vector<std::pair<string_t, string_t>> networks;
        #define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config))

        if (cmd_mlps)
        {
                DEFINE(mlp0);
                DEFINE(mlp1);
                DEFINE(mlp2);
                DEFINE(mlp3);
                DEFINE(mlp4);
                DEFINE(mlp5);
        }
        if (cmd_convnets)
        {
                DEFINE(convnetk2d_9x9p_5x5p_3x3);
                DEFINE(convnettoe_9x9p_5x5p_3x3);
                DEFINE(convnetk2d_11x11_9x9_7x7_3x3);
                DEFINE(convnettoe_11x11_9x9_7x7_3x3);
                DEFINE(convnetk2d_9x9_7x7_7x7_5x5_3x3);
                DEFINE(convnettoe_9x9_7x7_7x7_5x5_3x3);
                DEFINE(convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3);
                DEFINE(convnettoe_7x7_7x7_5x5_5x5_5x5_3x3);
                DEFINE(convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_3x3);
                DEFINE(convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_3x3);
                DEFINE(convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3);
                DEFINE(convnettoe_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3);
        }

        #undef DEFINE

        const auto loss = nano::get_losses().get("logistic");
        const auto criterion = nano::get_criteria().get("avg");

        // construct tables to compare models
        nano::table_t ftable("model-forward [us] / 1000 samples");
        nano::table_t btable("model-backward [us] / 1000 samples");

        for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
        {
                ftable.header() << (nano::to_string(nthreads) + "xCPU");
                btable.header() << (nano::to_string(nthreads) + "xCPU");
        }

        // evaluate models
        for (const auto& config : networks)
        {
                const string_t cmd_network = config.first;
                const string_t cmd_name = config.second;

                log_info() << "<<< running network [" << cmd_network << "] ...";

                // create feed-forward network
                const auto model = nano::get_models().get("forward-network", cmd_network);
                model->resize(task, true);
                model->random_params();

                nano::table_row_t& frow = ftable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")");
                nano::table_row_t& brow = btable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")");

                const auto fold = fold_t{0, protocol::train};

                // process the samples
                for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
                {
                        if (cmd_forward)
                        {
                                accumulator_t lacc(*model, *loss, *criterion, criterion_t::type::value, scalar_t(0.1));
                                lacc.set_threads(nthreads);

                                const auto duration = nano::measure_robustly_usec([&] ()
                                {
                                        lacc.reset();
                                        lacc.update(task, fold);
                                }, 1);

                                log_info() << "<<< processed [" << lacc.count()
                                           << "] forward samples in " << duration.count() << " us.";

                                frow << idiv(static_cast<size_t>(duration.count()) * 1000, lacc.count());
                        }

                        if (cmd_backward)
                        {
                                accumulator_t gacc(*model, *loss, *criterion, criterion_t::type::vgrad, scalar_t(0.1));
                                gacc.set_threads(nthreads);

                                const auto duration = nano::measure_robustly_usec([&] ()
                                {
                                        gacc.reset();
                                        gacc.update(task, fold);
                                }, 1);

                                log_info() << "<<< processed [" << gacc.count()
                                           << "] backward samples in " << duration.count() << " us.";

                                brow << idiv(static_cast<size_t>(duration.count()) * 1000, gacc.count());
                        }
                }

                log_info();
        }

        // print results
        if (cmd_forward)
        {
                ftable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
                ftable.print(std::cout);
        }
        log_info();
        if (cmd_backward)
        {
                btable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
                btable.print(std::cout);
        }

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}
<commit_msg>fix typo<commit_after>#include "text/table.h"
#include "text/cmdline.h"
#include "cortex/class.h"
#include "cortex/cortex.h"
#include "math/clamp.hpp"
#include "math/random.hpp"
#include "math/numeric.hpp"
#include "tensor/numeric.hpp"
#include "cortex/measure.hpp"
#include "cortex/accumulator.h"
#include "text/table_row_mark.h"
#include "cortex/measure_and_log.hpp"
#include "cortex/layers/make_layers.h"
#include "cortex/tasks/task_charset.h"

int main(int argc, const char *argv[])
{
        using namespace nano;

        // parse the command line
        nano::cmdline_t cmdline("benchmark models");
        cmdline.add("s", "samples",     "number of samples to use [100, 100000]", "10000");
        cmdline.add("", "mlps",         "benchmark MLP models");
        cmdline.add("", "convnets",     "benchmark convolution networks");
        cmdline.add("", "forward",      "evaluate the \'forward\' pass (output)");
        cmdline.add("", "backward",     "evaluate the \'backward' pass (gradient)");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto cmd_samples = nano::clamp(cmdline.get<size_t>("samples"), 100, 100 * 1000);
        const auto cmd_forward = cmdline.has("forward");
        const auto cmd_backward = cmdline.has("backward");
        const auto cmd_mlps = cmdline.has("mlps");
        const auto cmd_convnets = cmdline.has("convnets");

        if (!cmd_forward && !cmd_backward)
        {
                cmdline.usage();
        }

        if (!cmd_mlps && !cmd_convnets)
        {
                cmdline.usage();
        }

        const tensor_size_t cmd_rows = 28;
        const tensor_size_t cmd_cols = 28;
        const color_mode cmd_color = color_mode::luma;

        const size_t cmd_min_nthreads = 1;
        const size_t cmd_max_nthreads = nano::logical_cpus();

        // generate synthetic task
        charset_task_t task(charset::digit, cmd_color, cmd_rows, cmd_cols, cmd_samples);
        task.load();

        // construct models
        const string_t mlp0;
        const string_t mlp1 = mlp0 + make_affine_layer(100);
        const string_t mlp2 = mlp1 + make_affine_layer(100);
        const string_t mlp3 = mlp2 + make_affine_layer(100);
        const string_t mlp4 = mlp3 + make_affine_layer(100);
        const string_t mlp5 = mlp4 + make_affine_layer(100);

        const string_t convnetk2d_9x9p_5x5p_3x3 =
                make_conv_pool_layer("conv-k2d", 16, 9, 9, 1) +
                make_conv_pool_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4);

        const string_t convnettoe_9x9p_5x5p_3x3 =
                nano::replace(convnetk2d_9x9p_5x5p_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_11x11_9x9_7x7_3x3 =
                make_conv_layer("conv-k2d", 16, 11, 11, 1) +
                make_conv_layer("conv-k2d", 32, 9, 9, 2) +
                make_conv_layer("conv-k2d", 64, 7, 7, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_11x11_9x9_7x7_3x3 =
                nano::replace(convnetk2d_11x11_9x9_7x7_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_9x9_7x7_7x7_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 9, 9, 1) +
                make_conv_layer("conv-k2d", 32, 7, 7, 2) +
                make_conv_layer("conv-k2d", 32, 7, 7, 4) +
                make_conv_layer("conv-k2d", 64, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_9x9_7x7_7x7_5x5_3x3 =
                nano::replace(convnetk2d_9x9_7x7_7x7_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 7, 7, 1) +
                make_conv_layer("conv-k2d", 16, 7, 7, 2) +
                make_conv_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 32, 5, 5, 4) +
                make_conv_layer("conv-k2d", 32, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4);

        const string_t convnettoe_7x7_7x7_5x5_5x5_5x5_3x3 =
                nano::replace(convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 5, 5, 1) +
                make_conv_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 64, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 5, 5, 8) +
                make_conv_layer("conv-k2d", 64, 5, 5, 8) +
                make_conv_layer("conv-k2d", 64, 5, 5, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_5x5_5x5_5x5_5x5_5x5_5x5_3x3 =
                nano::replace(convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3 =
                make_conv_layer("conv-k2d", 16, 3, 3, 1) +
                make_conv_layer("conv-k2d", 32, 3, 3, 2) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3 =
                nano::replace(convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3, "conv-k2d", "conv-toe");

        const string_t outlayer = make_output_layer(task.osize());

        std::vector<std::pair<string_t, string_t>> networks;
        #define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config))

        if (cmd_mlps)
        {
                DEFINE(mlp0);
                DEFINE(mlp1);
                DEFINE(mlp2);
                DEFINE(mlp3);
                DEFINE(mlp4);
                DEFINE(mlp5);
        }
        if (cmd_convnets)
        {
                DEFINE(convnetk2d_9x9p_5x5p_3x3);
                DEFINE(convnettoe_9x9p_5x5p_3x3);
                DEFINE(convnetk2d_11x11_9x9_7x7_3x3);
                DEFINE(convnettoe_11x11_9x9_7x7_3x3);
                DEFINE(convnetk2d_9x9_7x7_7x7_5x5_3x3);
                DEFINE(convnettoe_9x9_7x7_7x7_5x5_3x3);
                DEFINE(convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3);
                DEFINE(convnettoe_7x7_7x7_5x5_5x5_5x5_3x3);
                DEFINE(convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_3x3);
                DEFINE(convnettoe_5x5_5x5_5x5_5x5_5x5_5x5_3x3);
                DEFINE(convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3);
                DEFINE(convnettoe_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3);
        }

        #undef DEFINE

        const auto loss = nano::get_losses().get("logistic");
        const auto criterion = nano::get_criteria().get("avg");

        // construct tables to compare models
        nano::table_t ftable("model-forward [us] / 1000 samples");
        nano::table_t btable("model-backward [us] / 1000 samples");

        for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
        {
                ftable.header() << (nano::to_string(nthreads) + "xCPU");
                btable.header() << (nano::to_string(nthreads) + "xCPU");
        }

        // evaluate models
        for (const auto& config : networks)
        {
                const string_t cmd_network = config.first;
                const string_t cmd_name = config.second;

                log_info() << "<<< running network [" << cmd_network << "] ...";

                // create feed-forward network
                const auto model = nano::get_models().get("forward-network", cmd_network);
                model->resize(task, true);
                model->random_params();

                nano::table_row_t& frow = ftable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")");
                nano::table_row_t& brow = btable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")");

                const auto fold = fold_t{0, protocol::train};

                // process the samples
                for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
                {
                        if (cmd_forward)
                        {
                                accumulator_t lacc(*model, *loss, *criterion, criterion_t::type::value, scalar_t(0.1));
                                lacc.set_threads(nthreads);

                                const auto duration = nano::measure_robustly_usec([&] ()
                                {
                                        lacc.reset();
                                        lacc.update(task, fold);
                                }, 1);

                                log_info() << "<<< processed [" << lacc.count()
                                           << "] forward samples in " << duration.count() << " us.";

                                frow << idiv(static_cast<size_t>(duration.count()) * 1000, lacc.count());
                        }

                        if (cmd_backward)
                        {
                                accumulator_t gacc(*model, *loss, *criterion, criterion_t::type::vgrad, scalar_t(0.1));
                                gacc.set_threads(nthreads);

                                const auto duration = nano::measure_robustly_usec([&] ()
                                {
                                        gacc.reset();
                                        gacc.update(task, fold);
                                }, 1);

                                log_info() << "<<< processed [" << gacc.count()
                                           << "] backward samples in " << duration.count() << " us.";

                                brow << idiv(static_cast<size_t>(duration.count()) * 1000, gacc.count());
                        }
                }

                log_info();
        }

        // print results
        if (cmd_forward)
        {
                ftable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
                ftable.print(std::cout);
        }
        log_info();
        if (cmd_backward)
        {
                btable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
                btable.print(std::cout);
        }

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#ifndef UAVCAN_PROTOCOL_FILE_SERVER_HPP_INCLUDED
#define UAVCAN_PROTOCOL_FILE_SERVER_HPP_INCLUDED

#include <uavcan/build_config.hpp>
#include <uavcan/debug.hpp>
#include <uavcan/node/service_server.hpp>
#include <uavcan/util/method_binder.hpp>
// UAVCAN types
#include <uavcan/protocol/file/GetInfo.hpp>
#include <uavcan/protocol/file/GetDirectoryEntryInfo.hpp>
#include <uavcan/protocol/file/Read.hpp>
#include <uavcan/protocol/file/Write.hpp>
#include <uavcan/protocol/file/Delete.hpp>

namespace uavcan
{
/**
 * The file server backend should implement this interface.
 */
class UAVCAN_EXPORT IFileServerBackend
{
public:
    typedef protocol::file::Path::FieldTypes::path Path;
    typedef protocol::file::EntryType EntryType;
    typedef protocol::file::Error Error;

    /**
     * Use this class to compute CRC64 for uavcan.protocol.file.GetInfo.
     */
    typedef DataTypeSignatureCRC FileCRC;

    /**
     * All read operations must return this number of bytes, unless end of file is reached.
     */
    enum { ReadSize = protocol::file::Read::Response::FieldTypes::data::MaxSize };

    /**
     * Shortcut for uavcan.protocol.file.Path.SEPARATOR.
     */
    static char getPathSeparator() { return static_cast<char>(protocol::file::Path::SEPARATOR); }

    /**
     * Backend for uavcan.protocol.file.GetInfo.
     * Implementation of this method is required.
     * On success the method must return zero.
     */
    virtual int16_t getInfo(const Path& path, uint64_t& out_crc64, uint32_t& out_size, EntryType& out_type) = 0;

    /**
     * Backend for uavcan.protocol.file.Read.
     * Implementation of this method is required.
     * @ref inout_size is set to @ref ReadSize; read operation is required to return exactly this amount, except
     * if the end of file is reached.
     * On success the method must return zero.
     */
    virtual int16_t read(const Path& path, const uint32_t offset, uint8_t* out_buffer, uint16_t& inout_size) = 0;

    // Methods below are optional.

    /**
     * Backend for uavcan.protocol.file.Write.
     * Implementation of this method is NOT required; by default it returns uavcan.protocol.file.Error.NOT_IMPLEMENTED.
     * On success the method must return zero.
     */
    virtual int16_t write(const Path& path, const uint32_t offset, const uint8_t* buffer, const uint16_t size)
    {
        (void)path;
        (void)offset;
        (void)buffer;
        (void)size;
        return Error::NOT_IMPLEMENTED;
    }

    /**
     * Backend for uavcan.protocol.file.Delete. ('delete' is a C++ keyword, so 'remove' is used instead)
     * Implementation of this method is NOT required; by default it returns uavcan.protocol.file.Error.NOT_IMPLEMENTED.
     * On success the method must return zero.
     */
    virtual int16_t remove(const Path& path)
    {
        (void)path;
        return Error::NOT_IMPLEMENTED;
    }

    /**
     * Backend for uavcan.protocol.file.GetDirectoryEntryInfo.
     * Implementation of this method is NOT required; by default it returns uavcan.protocol.file.Error.NOT_IMPLEMENTED.
     * On success the method must return zero.
     */
    virtual int16_t getDirectoryEntryInfo(const Path& directory_path, const uint32_t entry_index,
                                          EntryType& out_type, Path& out_entry_full_path)
    {
        (void)directory_path;
        (void)entry_index;
        (void)out_type;
        (void)out_entry_full_path;
        return Error::NOT_IMPLEMENTED;
    }

    virtual ~IFileServerBackend() { }
};

/**
 * Basic file server implements only the following services:
 *      uavcan.protocol.file.GetInfo
 *      uavcan.protocol.file.Read
 * Also see @ref IFileServerBackend.
 */
class BasicFileServer
{
    typedef MethodBinder<BasicFileServer*,
        void (BasicFileServer::*)(const protocol::file::GetInfo::Request&, protocol::file::GetInfo::Response&)>
            GetInfoCallback;

    typedef MethodBinder<BasicFileServer*,
        void (BasicFileServer::*)(const protocol::file::Read::Request&, protocol::file::Read::Response&)>
            ReadCallback;

    ServiceServer<protocol::file::GetInfo, GetInfoCallback> get_info_srv_;
    ServiceServer<protocol::file::Read, ReadCallback> read_srv_;

    void handleGetInfo(const protocol::file::GetInfo::Request& req, protocol::file::GetInfo::Response& resp)
    {
        resp.error.value = backend_.getInfo(req.path.path, resp.crc64, resp.size, resp.entry_type);
    }

    void handleRead(const protocol::file::Read::Request& req, protocol::file::Read::Response& resp)
    {
        uint16_t inout_size = resp.data.capacity();

        resp.data.resize(inout_size);

        resp.error.value = backend_.read(req.path.path, req.offset, resp.data.begin(), inout_size);

        if (inout_size > resp.data.capacity())
        {
            UAVCAN_ASSERT(0);
            resp.error.value = protocol::file::Error::UNKNOWN_ERROR;
        }
        else
        {
            resp.data.resize(inout_size);
        }
    }

protected:
    IFileServerBackend& backend_;       ///< Derived types can use it

public:
    BasicFileServer(INode& node, IFileServerBackend& backend)
        : get_info_srv_(node)
        , read_srv_(node)
        , backend_(backend)
    { }

    int start()
    {
        int res = get_info_srv_.start(GetInfoCallback(this, &BasicFileServer::handleGetInfo));
        if (res < 0)
        {
            return res;
        }

        res = read_srv_.start(ReadCallback(this, &BasicFileServer::handleRead));
        if (res < 0)
        {
            return res;
        }

        return 0;
    }
};

/**
 * Full file server implements all file services:
 *      uavcan.protocol.file.GetInfo
 *      uavcan.protocol.file.Read
 *      uavcan.protocol.file.Write
 *      uavcan.protocol.file.Delete
 *      uavcan.protocol.file.GetDirectoryEntryInfo
 * Also see @ref IFileServerBackend.
 */
class FileServer : protected BasicFileServer
{
    typedef MethodBinder<FileServer*,
        void (FileServer::*)(const protocol::file::Write::Request&, protocol::file::Write::Response&)>
            WriteCallback;

    typedef MethodBinder<FileServer*,
        void (FileServer::*)(const protocol::file::Delete::Request&, protocol::file::Delete::Response&)>
            DeleteCallback;

    typedef MethodBinder<FileServer*,
        void (FileServer::*)(const protocol::file::GetDirectoryEntryInfo::Request&,
                             protocol::file::GetDirectoryEntryInfo::Response&)>
            GetDirectoryEntryInfoCallback;

    ServiceServer<protocol::file::Write, WriteCallback> write_srv_;
    ServiceServer<protocol::file::Delete, DeleteCallback> delete_srv_;
    ServiceServer<protocol::file::GetDirectoryEntryInfo, GetDirectoryEntryInfoCallback> get_directory_entry_info_srv_;

    void handleWrite(const protocol::file::Write::Request& req, protocol::file::Write::Response& resp)
    {
        resp.error.value = backend_.write(req.path.path, req.offset, req.data.begin(), req.data.size());
    }

    void handleDelete(const protocol::file::Delete::Request& req, protocol::file::Delete::Response& resp)
    {
        resp.error.value = backend_.remove(req.path.path);
    }

    void handleGetDirectoryEntryInfo(const protocol::file::GetDirectoryEntryInfo::Request& req,
                                     protocol::file::GetDirectoryEntryInfo::Response& resp)
    {
        resp.error.value = backend_.getDirectoryEntryInfo(req.directory_path.path, req.entry_index,
                                                          resp.entry_type, resp.entry_full_path.path);
    }

public:
    FileServer(INode& node, IFileServerBackend& backend)
        : BasicFileServer(node, backend)
        , write_srv_(node)
        , delete_srv_(node)
        , get_directory_entry_info_srv_(node)
    { }

    int start()
    {
        int res = BasicFileServer::start();
        if (res < 0)
        {
            return res;
        }

        res = write_srv_.start(WriteCallback(this, &FileServer::handleWrite));
        if (res < 0)
        {
            return res;
        }

        res = delete_srv_.start(DeleteCallback(this, &FileServer::handleDelete));
        if (res < 0)
        {
            return res;
        }

        res = get_directory_entry_info_srv_.start(
            GetDirectoryEntryInfoCallback(this, &FileServer::handleGetDirectoryEntryInfo));
        if (res < 0)
        {
            return res;
        }

        return 0;
    }
};

}

#endif // Include guard
<commit_msg>BasicFileServer::handleRead() error handling fix<commit_after>/*
 * Copyright (C) 2015 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#ifndef UAVCAN_PROTOCOL_FILE_SERVER_HPP_INCLUDED
#define UAVCAN_PROTOCOL_FILE_SERVER_HPP_INCLUDED

#include <uavcan/build_config.hpp>
#include <uavcan/debug.hpp>
#include <uavcan/node/service_server.hpp>
#include <uavcan/util/method_binder.hpp>
// UAVCAN types
#include <uavcan/protocol/file/GetInfo.hpp>
#include <uavcan/protocol/file/GetDirectoryEntryInfo.hpp>
#include <uavcan/protocol/file/Read.hpp>
#include <uavcan/protocol/file/Write.hpp>
#include <uavcan/protocol/file/Delete.hpp>

namespace uavcan
{
/**
 * The file server backend should implement this interface.
 */
class UAVCAN_EXPORT IFileServerBackend
{
public:
    typedef protocol::file::Path::FieldTypes::path Path;
    typedef protocol::file::EntryType EntryType;
    typedef protocol::file::Error Error;

    /**
     * Use this class to compute CRC64 for uavcan.protocol.file.GetInfo.
     */
    typedef DataTypeSignatureCRC FileCRC;

    /**
     * All read operations must return this number of bytes, unless end of file is reached.
     */
    enum { ReadSize = protocol::file::Read::Response::FieldTypes::data::MaxSize };

    /**
     * Shortcut for uavcan.protocol.file.Path.SEPARATOR.
     */
    static char getPathSeparator() { return static_cast<char>(protocol::file::Path::SEPARATOR); }

    /**
     * Backend for uavcan.protocol.file.GetInfo.
     * Implementation of this method is required.
     * On success the method must return zero.
     */
    virtual int16_t getInfo(const Path& path, uint64_t& out_crc64, uint32_t& out_size, EntryType& out_type) = 0;

    /**
     * Backend for uavcan.protocol.file.Read.
     * Implementation of this method is required.
     * @ref inout_size is set to @ref ReadSize; read operation is required to return exactly this amount, except
     * if the end of file is reached.
     * On success the method must return zero.
     */
    virtual int16_t read(const Path& path, const uint32_t offset, uint8_t* out_buffer, uint16_t& inout_size) = 0;

    // Methods below are optional.

    /**
     * Backend for uavcan.protocol.file.Write.
     * Implementation of this method is NOT required; by default it returns uavcan.protocol.file.Error.NOT_IMPLEMENTED.
     * On success the method must return zero.
     */
    virtual int16_t write(const Path& path, const uint32_t offset, const uint8_t* buffer, const uint16_t size)
    {
        (void)path;
        (void)offset;
        (void)buffer;
        (void)size;
        return Error::NOT_IMPLEMENTED;
    }

    /**
     * Backend for uavcan.protocol.file.Delete. ('delete' is a C++ keyword, so 'remove' is used instead)
     * Implementation of this method is NOT required; by default it returns uavcan.protocol.file.Error.NOT_IMPLEMENTED.
     * On success the method must return zero.
     */
    virtual int16_t remove(const Path& path)
    {
        (void)path;
        return Error::NOT_IMPLEMENTED;
    }

    /**
     * Backend for uavcan.protocol.file.GetDirectoryEntryInfo.
     * Implementation of this method is NOT required; by default it returns uavcan.protocol.file.Error.NOT_IMPLEMENTED.
     * On success the method must return zero.
     */
    virtual int16_t getDirectoryEntryInfo(const Path& directory_path, const uint32_t entry_index,
                                          EntryType& out_type, Path& out_entry_full_path)
    {
        (void)directory_path;
        (void)entry_index;
        (void)out_type;
        (void)out_entry_full_path;
        return Error::NOT_IMPLEMENTED;
    }

    virtual ~IFileServerBackend() { }
};

/**
 * Basic file server implements only the following services:
 *      uavcan.protocol.file.GetInfo
 *      uavcan.protocol.file.Read
 * Also see @ref IFileServerBackend.
 */
class BasicFileServer
{
    typedef MethodBinder<BasicFileServer*,
        void (BasicFileServer::*)(const protocol::file::GetInfo::Request&, protocol::file::GetInfo::Response&)>
            GetInfoCallback;

    typedef MethodBinder<BasicFileServer*,
        void (BasicFileServer::*)(const protocol::file::Read::Request&, protocol::file::Read::Response&)>
            ReadCallback;

    ServiceServer<protocol::file::GetInfo, GetInfoCallback> get_info_srv_;
    ServiceServer<protocol::file::Read, ReadCallback> read_srv_;

    void handleGetInfo(const protocol::file::GetInfo::Request& req, protocol::file::GetInfo::Response& resp)
    {
        resp.error.value = backend_.getInfo(req.path.path, resp.crc64, resp.size, resp.entry_type);
    }

    void handleRead(const protocol::file::Read::Request& req, protocol::file::Read::Response& resp)
    {
        uint16_t inout_size = resp.data.capacity();

        resp.data.resize(inout_size);

        resp.error.value = backend_.read(req.path.path, req.offset, resp.data.begin(), inout_size);

        if (resp.error.value != protocol::file::Error::OK)
        {
            inout_size = 0;
        }

        if (inout_size > resp.data.capacity())
        {
            UAVCAN_ASSERT(0);
            resp.error.value = protocol::file::Error::UNKNOWN_ERROR;
        }
        else
        {
            resp.data.resize(inout_size);
        }
    }

protected:
    IFileServerBackend& backend_;       ///< Derived types can use it

public:
    BasicFileServer(INode& node, IFileServerBackend& backend)
        : get_info_srv_(node)
        , read_srv_(node)
        , backend_(backend)
    { }

    int start()
    {
        int res = get_info_srv_.start(GetInfoCallback(this, &BasicFileServer::handleGetInfo));
        if (res < 0)
        {
            return res;
        }

        res = read_srv_.start(ReadCallback(this, &BasicFileServer::handleRead));
        if (res < 0)
        {
            return res;
        }

        return 0;
    }
};

/**
 * Full file server implements all file services:
 *      uavcan.protocol.file.GetInfo
 *      uavcan.protocol.file.Read
 *      uavcan.protocol.file.Write
 *      uavcan.protocol.file.Delete
 *      uavcan.protocol.file.GetDirectoryEntryInfo
 * Also see @ref IFileServerBackend.
 */
class FileServer : protected BasicFileServer
{
    typedef MethodBinder<FileServer*,
        void (FileServer::*)(const protocol::file::Write::Request&, protocol::file::Write::Response&)>
            WriteCallback;

    typedef MethodBinder<FileServer*,
        void (FileServer::*)(const protocol::file::Delete::Request&, protocol::file::Delete::Response&)>
            DeleteCallback;

    typedef MethodBinder<FileServer*,
        void (FileServer::*)(const protocol::file::GetDirectoryEntryInfo::Request&,
                             protocol::file::GetDirectoryEntryInfo::Response&)>
            GetDirectoryEntryInfoCallback;

    ServiceServer<protocol::file::Write, WriteCallback> write_srv_;
    ServiceServer<protocol::file::Delete, DeleteCallback> delete_srv_;
    ServiceServer<protocol::file::GetDirectoryEntryInfo, GetDirectoryEntryInfoCallback> get_directory_entry_info_srv_;

    void handleWrite(const protocol::file::Write::Request& req, protocol::file::Write::Response& resp)
    {
        resp.error.value = backend_.write(req.path.path, req.offset, req.data.begin(), req.data.size());
    }

    void handleDelete(const protocol::file::Delete::Request& req, protocol::file::Delete::Response& resp)
    {
        resp.error.value = backend_.remove(req.path.path);
    }

    void handleGetDirectoryEntryInfo(const protocol::file::GetDirectoryEntryInfo::Request& req,
                                     protocol::file::GetDirectoryEntryInfo::Response& resp)
    {
        resp.error.value = backend_.getDirectoryEntryInfo(req.directory_path.path, req.entry_index,
                                                          resp.entry_type, resp.entry_full_path.path);
    }

public:
    FileServer(INode& node, IFileServerBackend& backend)
        : BasicFileServer(node, backend)
        , write_srv_(node)
        , delete_srv_(node)
        , get_directory_entry_info_srv_(node)
    { }

    int start()
    {
        int res = BasicFileServer::start();
        if (res < 0)
        {
            return res;
        }

        res = write_srv_.start(WriteCallback(this, &FileServer::handleWrite));
        if (res < 0)
        {
            return res;
        }

        res = delete_srv_.start(DeleteCallback(this, &FileServer::handleDelete));
        if (res < 0)
        {
            return res;
        }

        res = get_directory_entry_info_srv_.start(
            GetDirectoryEntryInfoCallback(this, &FileServer::handleGetDirectoryEntryInfo));
        if (res < 0)
        {
            return res;
        }

        return 0;
    }
};

}

#endif // Include guard
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  TestApp.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Assets/Gfx/ShapeBuilder.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "shaders.h"

using namespace Oryol;

// derived application class
class TestApp : public App {
public:
    AppState::Code OnRunning();
    AppState::Code OnInit();
    AppState::Code OnCleanup();
private:
    glm::mat4 computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos);

    Id renderTarget;
    Id offscreenDrawState;
    Id displayDrawState;
    ClearState offscreenClearState;
    ClearState displayClearState;
    glm::mat4 view;
    glm::mat4 offscreenProj;
    glm::mat4 displayProj;
    float32 angleX = 0.0f;
    float32 angleY = 0.0f;
    Shaders::RenderTarget::VSParams offscreenParams;
    Shaders::Main::VSParams displayVSParams;
    Shaders::Main::FSTextures displayFSTextures;
};
OryolMain(TestApp);

//------------------------------------------------------------------------------
AppState::Code
TestApp::OnRunning() {

    // update animated parameters
    this->angleY += 0.01f;
    this->angleX += 0.02f;
    this->offscreenParams.ModelViewProjection = this->computeMVP(this->offscreenProj, this->angleX, this->angleY, glm::vec3(0.0f, 0.0f, -3.0f));
    this->displayVSParams.ModelViewProjection = this->computeMVP(this->displayProj, -this->angleX * 0.25f, this->angleY * 0.25f, glm::vec3(0.0f, 0.0f, -1.5f));;

    // render donut to offscreen render target
    Gfx::ApplyRenderTarget(this->renderTarget, this->offscreenClearState);
    Gfx::ApplyDrawState(this->offscreenDrawState);
    Gfx::ApplyUniformBlock(this->offscreenParams);
    Gfx::Draw(0);

    // render sphere to display, with offscreen render target as texture
    Gfx::ApplyDefaultRenderTarget(this->displayClearState);
    Gfx::ApplyDrawState(this->displayDrawState, this->displayFSTextures);
    Gfx::ApplyUniformBlock(this->displayVSParams);
    Gfx::Draw(0);

    Gfx::CommitFrame();

    // continue running or quit?
    return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
TestApp::OnInit() {
    // setup rendering system
    auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, "Oryol Test App");
    Gfx::Setup(gfxSetup);

    // create an offscreen render target, we explicitly want repeat texture wrap mode
    // and linear blending...
    auto rtSetup = TextureSetup::RenderTarget(128, 128);
    rtSetup.ColorFormat = PixelFormat::RGBA8;
    rtSetup.DepthFormat = PixelFormat::D16;
    rtSetup.Sampler.WrapU = TextureWrapMode::Repeat;
    rtSetup.Sampler.WrapV = TextureWrapMode::Repeat;
    rtSetup.Sampler.MagFilter = TextureFilterMode::Linear;
    rtSetup.Sampler.MinFilter = TextureFilterMode::Linear;
    this->renderTarget = Gfx::CreateResource(rtSetup);

    // create a donut (this will be rendered into the offscreen render target)
    ShapeBuilder shapeBuilder;
    shapeBuilder.Layout
        .Add(VertexAttr::Position, VertexFormat::Float3)
        .Add(VertexAttr::Normal, VertexFormat::Byte4N);
    shapeBuilder.Box(1.0f, 1.0f, 1.0f, 1);
    Id torus = Gfx::CreateResource(shapeBuilder.Build());

    // create a sphere mesh with normals and uv coords
    shapeBuilder.Layout
        .Add(VertexAttr::Position, VertexFormat::Float3)
        .Add(VertexAttr::Normal, VertexFormat::Byte4N)
        .Add(VertexAttr::TexCoord0, VertexFormat::Float2);
    shapeBuilder.Sphere(0.5f, 72.0f, 40.0f);
    Id sphere = Gfx::CreateResource(shapeBuilder.Build());

    // create shaders
    Id offScreenShader = Gfx::CreateResource(Shaders::RenderTarget::Setup());
    Id dispShader = Gfx::CreateResource(Shaders::Main::Setup());

    // create one draw state for offscreen rendering, and one draw state for main target rendering
    auto offdsSetup = DrawStateSetup::FromMeshAndShader(torus, offScreenShader);
    offdsSetup.DepthStencilState.DepthWriteEnabled = true;
    offdsSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
    offdsSetup.BlendState.ColorFormat = rtSetup.ColorFormat;
    offdsSetup.BlendState.DepthFormat = rtSetup.DepthFormat;
    this->offscreenDrawState = Gfx::CreateResource(offdsSetup);
    auto dispdsSetup = DrawStateSetup::FromMeshAndShader(sphere, dispShader);
    dispdsSetup.DepthStencilState.DepthWriteEnabled = true;
    dispdsSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
    dispdsSetup.RasterizerState.SampleCount = gfxSetup.SampleCount;
    this->displayDrawState = Gfx::CreateResource(dispdsSetup);
    this->displayFSTextures.Texture = this->renderTarget;

    // setup clear states
    this->offscreenClearState.Color = glm::vec4(1.0f, 0.5f, 0.25f, 1.0f);
    this->displayClearState.Color = glm::vec4(0.25f, 0.5f, 1.0f, 1.0f);

    // setup static transform matrices
    float32 fbWidth = Gfx::DisplayAttrs().FramebufferWidth;
    float32 fbHeight = Gfx::DisplayAttrs().FramebufferHeight;
    this->offscreenProj = glm::perspective(glm::radians(45.0f), 1.0f, 0.01f, 20.0f);
    this->displayProj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f);
    this->view = glm::mat4();

    return App::OnInit();
}

//------------------------------------------------------------------------------
AppState::Code
TestApp::OnCleanup() {
    Gfx::Discard();
    return App::OnCleanup();
}

//------------------------------------------------------------------------------
glm::mat4
TestApp::computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos) {
    glm::mat4 modelTform = glm::translate(glm::mat4(), pos);
    modelTform = glm::rotate(modelTform, rotX, glm::vec3(1.0f, 0.0f, 0.0f));
    modelTform = glm::rotate(modelTform, rotY, glm::vec3(0.0f, 1.0f, 0.0f));
    return proj * this->view * modelTform;
}
<commit_msg>Fixed for latest Oryol changes<commit_after>//------------------------------------------------------------------------------
//  TestApp.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/Main.h"
#include "Gfx/Gfx.h"
#include "Assets/Gfx/ShapeBuilder.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "shaders.h"

using namespace Oryol;

// derived application class
class TestApp : public App {
public:
    AppState::Code OnRunning();
    AppState::Code OnInit();
    AppState::Code OnCleanup();
private:
    glm::mat4 computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos);

    Id renderTarget;
    Id offscreenDrawState;
    Id displayDrawState;
    ClearState offscreenClearState;
    ClearState displayClearState;
    glm::mat4 view;
    glm::mat4 offscreenProj;
    glm::mat4 displayProj;
    float32 angleX = 0.0f;
    float32 angleY = 0.0f;
    Shaders::RenderTarget::VSParams offscreenParams;
    Shaders::Main::VSParams displayVSParams;
    Shaders::Main::FSTextures displayFSTextures;
};
OryolMain(TestApp);

//------------------------------------------------------------------------------
AppState::Code
TestApp::OnRunning() {

    // update animated parameters
    this->angleY += 0.01f;
    this->angleX += 0.02f;
    this->offscreenParams.ModelViewProjection = this->computeMVP(this->offscreenProj, this->angleX, this->angleY, glm::vec3(0.0f, 0.0f, -3.0f));
    this->displayVSParams.ModelViewProjection = this->computeMVP(this->displayProj, -this->angleX * 0.25f, this->angleY * 0.25f, glm::vec3(0.0f, 0.0f, -1.5f));;

    // render donut to offscreen render target
    Gfx::ApplyRenderTarget(this->renderTarget, this->offscreenClearState);
    Gfx::ApplyDrawState(this->offscreenDrawState);
    Gfx::ApplyUniformBlock(this->offscreenParams);
    Gfx::Draw(0);

    // render sphere to display, with offscreen render target as texture
    Gfx::ApplyDefaultRenderTarget(this->displayClearState);
    Gfx::ApplyDrawState(this->displayDrawState, this->displayFSTextures);
    Gfx::ApplyUniformBlock(this->displayVSParams);
    Gfx::Draw(0);

    Gfx::CommitFrame();

    // continue running or quit?
    return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
TestApp::OnInit() {
    // setup rendering system
    auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, "Oryol Test App");
    Gfx::Setup(gfxSetup);

    // create an offscreen render target, we explicitly want repeat texture wrap mode
    // and linear blending...
    auto rtSetup = TextureSetup::RenderTarget(128, 128);
    rtSetup.ColorFormat = PixelFormat::RGBA8;
    rtSetup.DepthFormat = PixelFormat::DEPTH;
    rtSetup.Sampler.WrapU = TextureWrapMode::Repeat;
    rtSetup.Sampler.WrapV = TextureWrapMode::Repeat;
    rtSetup.Sampler.MagFilter = TextureFilterMode::Linear;
    rtSetup.Sampler.MinFilter = TextureFilterMode::Linear;
    this->renderTarget = Gfx::CreateResource(rtSetup);

    // create a donut (this will be rendered into the offscreen render target)
    ShapeBuilder shapeBuilder;
    shapeBuilder.Layout
        .Add(VertexAttr::Position, VertexFormat::Float3)
        .Add(VertexAttr::Normal, VertexFormat::Byte4N);
    shapeBuilder.Box(1.0f, 1.0f, 1.0f, 1);
    Id torus = Gfx::CreateResource(shapeBuilder.Build());

    // create a sphere mesh with normals and uv coords
    shapeBuilder.Layout
        .Add(VertexAttr::Position, VertexFormat::Float3)
        .Add(VertexAttr::Normal, VertexFormat::Byte4N)
        .Add(VertexAttr::TexCoord0, VertexFormat::Float2);
    shapeBuilder.Sphere(0.5f, 72.0f, 40.0f);
    Id sphere = Gfx::CreateResource(shapeBuilder.Build());

    // create shaders
    Id offScreenShader = Gfx::CreateResource(Shaders::RenderTarget::Setup());
    Id dispShader = Gfx::CreateResource(Shaders::Main::Setup());

    // create one draw state for offscreen rendering, and one draw state for main target rendering
    auto offdsSetup = DrawStateSetup::FromMeshAndShader(torus, offScreenShader);
    offdsSetup.DepthStencilState.DepthWriteEnabled = true;
    offdsSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
    offdsSetup.BlendState.ColorFormat = rtSetup.ColorFormat;
    offdsSetup.BlendState.DepthFormat = rtSetup.DepthFormat;
    this->offscreenDrawState = Gfx::CreateResource(offdsSetup);
    auto dispdsSetup = DrawStateSetup::FromMeshAndShader(sphere, dispShader);
    dispdsSetup.DepthStencilState.DepthWriteEnabled = true;
    dispdsSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
    dispdsSetup.RasterizerState.SampleCount = gfxSetup.SampleCount;
    this->displayDrawState = Gfx::CreateResource(dispdsSetup);
    this->displayFSTextures.Texture = this->renderTarget;

    // setup clear states
    this->offscreenClearState.Color = glm::vec4(1.0f, 0.5f, 0.25f, 1.0f);
    this->displayClearState.Color = glm::vec4(0.25f, 0.5f, 1.0f, 1.0f);

    // setup static transform matrices
    float32 fbWidth = Gfx::DisplayAttrs().FramebufferWidth;
    float32 fbHeight = Gfx::DisplayAttrs().FramebufferHeight;
    this->offscreenProj = glm::perspective(glm::radians(45.0f), 1.0f, 0.01f, 20.0f);
    this->displayProj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f);
    this->view = glm::mat4();

    return App::OnInit();
}

//------------------------------------------------------------------------------
AppState::Code
TestApp::OnCleanup() {
    Gfx::Discard();
    return App::OnCleanup();
}

//------------------------------------------------------------------------------
glm::mat4
TestApp::computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos) {
    glm::mat4 modelTform = glm::translate(glm::mat4(), pos);
    modelTform = glm::rotate(modelTform, rotX, glm::vec3(1.0f, 0.0f, 0.0f));
    modelTform = glm::rotate(modelTform, rotY, glm::vec3(0.0f, 1.0f, 0.0f));
    return proj * this->view * modelTform;
}
<|endoftext|>


<commit_before>#ifndef _MEDIAFOUNDATION_WEBMMFVORBISDEC_VORBISDECODER_HPP_
#define _MEDIAFOUNDATION_WEBMMFVORBISDEC_VORBISDECODER_HPP_

#ifndef DISALLOW_COPY_AND_ASSIGN
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
  TypeName(const TypeName&);               \
  void operator=(const TypeName&)
#endif

#include "vorbis/codec.h"

namespace WebmMfVorbisDecLib
{

const UINT32 VORBIS_SETUP_HEADER_COUNT = 3;

class VorbisDecoder
{
public:
    VorbisDecoder();
    ~VorbisDecoder();
    int CreateDecoder(const BYTE** const ptr_headers,
                      const DWORD* const header_lengths,
                      unsigned int num_headers /* must be == 3 */);
    void DestroyDecoder();

    int Decode(BYTE* ptr_samples, UINT32 length);

    int GetOutputSamplesAvailable(UINT32* ptr_num_samples_available);
    int ConsumeOutputSamples(float* ptr_out_sample_buffer,
                             UINT32 blocks_to_consume);
    void Flush();

    int GetVorbisRate() const
    {
        return m_vorbis_info.rate;
    };
    int GetVorbisChannels() const
    {
        return m_vorbis_info.channels;
    };

private:
    int NextOggPacket_(const BYTE* ptr_packet, DWORD packet_size);

    ogg_packet m_ogg_packet;
    DWORD m_ogg_packet_count;

    vorbis_info m_vorbis_info; // contains static bitstream settings
    vorbis_comment m_vorbis_comment; // contains user comments
    vorbis_dsp_state m_vorbis_state; // decoder state
    vorbis_block m_vorbis_block; // working space for packet->PCM decode

    const int m_bytes_per_sample;

    WAVEFORMATEX m_wave_format;

    typedef std::vector<float> pcm_samples_t;
    pcm_samples_t m_output_samples;

    // disallow copy and assign
    DISALLOW_COPY_AND_ASSIGN(VorbisDecoder);
};

} // namespace WebmMfVorbisDecLib

#endif // _MEDIAFOUNDATION_WEBMMFVORBISDEC_VORBISDECODER_HPP_
<commit_msg>webmmfvorbisdec: fix EoLs<commit_after>#ifndef _MEDIAFOUNDATION_WEBMMFVORBISDEC_VORBISDECODER_HPP_
#define _MEDIAFOUNDATION_WEBMMFVORBISDEC_VORBISDECODER_HPP_

#ifndef DISALLOW_COPY_AND_ASSIGN
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
  TypeName(const TypeName&);               \
  void operator=(const TypeName&)
#endif

#include "vorbis/codec.h"

namespace WebmMfVorbisDecLib
{

const UINT32 VORBIS_SETUP_HEADER_COUNT = 3;

class VorbisDecoder
{
public:
    VorbisDecoder();
    ~VorbisDecoder();
    int CreateDecoder(const BYTE** const ptr_headers,
                      const DWORD* const header_lengths,
                      unsigned int num_headers /* must be == 3 */);
    void DestroyDecoder();

    int Decode(BYTE* ptr_samples, UINT32 length);

    int GetOutputSamplesAvailable(UINT32* ptr_num_samples_available);
    int ConsumeOutputSamples(float* ptr_out_sample_buffer,
                             UINT32 blocks_to_consume);
    void Flush();

    int GetVorbisRate() const
    {
        return m_vorbis_info.rate;
    };
    int GetVorbisChannels() const
    {
        return m_vorbis_info.channels;
    };

private:
    int NextOggPacket_(const BYTE* ptr_packet, DWORD packet_size);

    ogg_packet m_ogg_packet;
    DWORD m_ogg_packet_count;

    vorbis_info m_vorbis_info; // contains static bitstream settings
    vorbis_comment m_vorbis_comment; // contains user comments
    vorbis_dsp_state m_vorbis_state; // decoder state
    vorbis_block m_vorbis_block; // working space for packet->PCM decode

    const int m_bytes_per_sample;

    WAVEFORMATEX m_wave_format;

    typedef std::vector<float> pcm_samples_t;
    pcm_samples_t m_output_samples;

    // disallow copy and assign
    DISALLOW_COPY_AND_ASSIGN(VorbisDecoder);
};

} // namespace WebmMfVorbisDecLib

#endif // _MEDIAFOUNDATION_WEBMMFVORBISDEC_VORBISDECODER_HPP_
<|endoftext|>


<commit_before>///
/// @file  Li.cpp
/// @brief Logarithmic integral and Riemann R function.
///        Both the Logarithmic integral and the Riemann R function
///        are very accurate approximations of PrimePi(x). The inverse
///        Logarithmic integral and the inverse Riemann R function are
///        very accurate approximations of the nth prime.
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount-internal.hpp>
#include <generate.hpp>
#include <int128_t.hpp>

#include <stdint.h>
#include <cassert>
#include <cmath>
#include <limits>

using namespace std;

namespace primecount {

/// Calculate the logarithmic integral using
/// Ramanujan's formula:
/// https://en.wikipedia.org/wiki/Logarithmic_integral_function#Series_representation
///
long double li(long double x)
{
  assert(x >= 2);

  long double gamma = 0.57721566490153286061L;
  long double sum = 0;
  long double inner_sum = 0;
  long double factorial = 1;
  long double p = -1;
  long double q = 0;
  long double power2 = 1;
  long double logx = log(x);
  int k = 0;

  for (int n = 1; n < 200; n++)
  {
    p *= -logx;
    factorial *= n;
    q = factorial * power2;
    power2 *= 2;
    for (; k <= (n - 1) / 2; k++)
      inner_sum += 1.0L / (2 * k + 1);
    long double term = (p / q) * inner_sum;
    sum += term;
    if (abs(term) < numeric_limits<long double>::epsilon())
      break;
  }

  return gamma + log(logx) + sqrt(x) * sum;
}

/// Calculate the offset logarithmic integral which is a very
/// accurate approximation of the number of primes <= x.
/// Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
long double Li(long double x)
{
  if (x < 2)
    return 0;

  long double li2 = 1.04516378011749278484L;

  return li(x) - li2;
}

/// Calculate the inverse offset logarithmic integral which
/// is a very accurate approximation of the nth prime.
/// Li^-1(x) < nth_prime(x) for 7 <= x <= 10^316
///
long double Li_inverse(long double x)
{
  if (x < 2)
    return 0;

  long double t = x * log(x);
  long double old_term = numeric_limits<long double>::infinity();

  for (int i = 0; i < 100; i++)
  {
    long double term = (Li(t) - x) * log(t);
    t -= term;
    // not converging anymore
    if (abs(term) >= abs(old_term))
      break;
    old_term = term;
  }

  return t;
}

/// Calculate the Riemann R function which is a very accurate
/// approximation of the number of primes below x.
///
long double Ri(long double x)
{
  if (x < 2)
    return 0;

  int terms = 200;
  auto mu = generate_moebius(terms);
  long double sum = 0;

  for (int n = 1; n < terms; n++)
  {
    if (mu[n])
    {
      long double root = pow(x, 1.0L / n);
      long double term = (Li(root) * mu[n]) / n;
      sum += term;
      if (abs(term) < numeric_limits<long double>::epsilon())
        break;
    }
  }

  return sum;
}

/// Calculate the inverse Riemann R function which is a very
/// accurate approximation of the nth prime.
///
long double Ri_inverse(long double x)
{
  if (x < 2)
    return 0;

  long double t = Li_inverse(x);
  long double old_term = numeric_limits<long double>::infinity();

  for (int i = 0; i < 100; i++)
  {
    long double term = (Ri(t) - x) * log(t);
    t -= term;
    // not converging anymore
    if (abs(term) >= abs(old_term))
      break;
    old_term = term;
  }

  return t;
}

int64_t Li(int64_t x)
{
  return (int64_t) Li((long double) x);
}

int64_t Li_inverse(int64_t x)
{
  return (int64_t) Li_inverse((long double) x);
}

#ifdef HAVE_INT128_T

int128_t Li(int128_t x)
{
  return (int128_t) Li((long double) x);
}

int128_t Li_inverse(int128_t x)
{
  return (int128_t) Li_inverse((long double) x);
}

#endif

int64_t Ri(int64_t x)
{
  return (int64_t) Ri((long double) x);
}

int64_t Ri_inverse(int64_t x)
{
  return (int64_t) Ri_inverse((long double) x);
}

#ifdef HAVE_INT128_T

int128_t Ri(int128_t x)
{
  return (int128_t) Ri((long double) x);
}

int128_t Ri_inverse(int128_t x)
{
  return (int128_t) Ri_inverse((long double) x);
}

#endif

} // namespace
<commit_msg>Update documentation<commit_after>///
/// @file  Li.cpp
/// @brief Logarithmic integral and Riemann R function.
///        Both the Logarithmic integral and the Riemann R function
///        are very accurate approximations of PrimePi(x). The inverse
///        Logarithmic integral and the inverse Riemann R function are
///        very accurate approximations of the nth prime.
///
///        Note that these implementations are only accurate up to
///        about 10^19 if the compiler supports the long double type.
///        We also include implementations based on libquadmath and the
///        non-standard __float128 type. However it is currently
///        impossible to compile this code without warnings because of
///        a GCC but and hence this code is disabled for the time being.
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount-internal.hpp>
#include <generate.hpp>
#include <int128_t.hpp>

#include <stdint.h>
#include <cassert>
#include <cmath>
#include <limits>

using namespace std;

namespace primecount {

/// Calculate the logarithmic integral using
/// Ramanujan's formula:
/// https://en.wikipedia.org/wiki/Logarithmic_integral_function#Series_representation
///
long double li(long double x)
{
  assert(x >= 2);

  long double gamma = 0.57721566490153286061L;
  long double sum = 0;
  long double inner_sum = 0;
  long double factorial = 1;
  long double p = -1;
  long double q = 0;
  long double power2 = 1;
  long double logx = log(x);
  int k = 0;

  for (int n = 1; n < 200; n++)
  {
    p *= -logx;
    factorial *= n;
    q = factorial * power2;
    power2 *= 2;
    for (; k <= (n - 1) / 2; k++)
      inner_sum += 1.0L / (2 * k + 1);
    long double term = (p / q) * inner_sum;
    sum += term;
    if (abs(term) < numeric_limits<long double>::epsilon())
      break;
  }

  return gamma + log(logx) + sqrt(x) * sum;
}

/// Calculate the offset logarithmic integral which is a very
/// accurate approximation of the number of primes <= x.
/// Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
long double Li(long double x)
{
  if (x < 2)
    return 0;

  long double li2 = 1.04516378011749278484L;

  return li(x) - li2;
}

/// Calculate the inverse offset logarithmic integral which
/// is a very accurate approximation of the nth prime.
/// Li^-1(x) < nth_prime(x) for 7 <= x <= 10^316
///
long double Li_inverse(long double x)
{
  if (x < 2)
    return 0;

  long double t = x * log(x);
  long double old_term = numeric_limits<long double>::infinity();

  for (int i = 0; i < 100; i++)
  {
    long double term = (Li(t) - x) * log(t);
    t -= term;
    // not converging anymore
    if (abs(term) >= abs(old_term))
      break;
    old_term = term;
  }

  return t;
}

/// Calculate the Riemann R function which is a very accurate
/// approximation of the number of primes below x.
///
long double Ri(long double x)
{
  if (x < 2)
    return 0;

  int terms = 200;
  auto mu = generate_moebius(terms);
  long double sum = 0;

  for (int n = 1; n < terms; n++)
  {
    if (mu[n])
    {
      long double root = pow(x, 1.0L / n);
      long double term = (Li(root) * mu[n]) / n;
      sum += term;
      if (abs(term) < numeric_limits<long double>::epsilon())
        break;
    }
  }

  return sum;
}

/// Calculate the inverse Riemann R function which is a very
/// accurate approximation of the nth prime.
///
long double Ri_inverse(long double x)
{
  if (x < 2)
    return 0;

  long double t = Li_inverse(x);
  long double old_term = numeric_limits<long double>::infinity();

  for (int i = 0; i < 100; i++)
  {
    long double term = (Ri(t) - x) * log(t);
    t -= term;
    // not converging anymore
    if (abs(term) >= abs(old_term))
      break;
    old_term = term;
  }

  return t;
}

int64_t Li(int64_t x)
{
  return (int64_t) Li((long double) x);
}

int64_t Li_inverse(int64_t x)
{
  return (int64_t) Li_inverse((long double) x);
}

#ifdef HAVE_INT128_T

int128_t Li(int128_t x)
{
  return (int128_t) Li((long double) x);
}

int128_t Li_inverse(int128_t x)
{
  return (int128_t) Li_inverse((long double) x);
}

#endif

int64_t Ri(int64_t x)
{
  return (int64_t) Ri((long double) x);
}

int64_t Ri_inverse(int64_t x)
{
  return (int64_t) Ri_inverse((long double) x);
}

#ifdef HAVE_INT128_T

int128_t Ri(int128_t x)
{
  return (int128_t) Ri((long double) x);
}

int128_t Ri_inverse(int128_t x)
{
  return (int128_t) Ri_inverse((long double) x);
}

#endif

} // namespace
<|endoftext|>


<commit_before>#ifdef _WIN32
#include "WindowsContainer.h"
int WINAPI WinMain(
	HINSTANCE	hInstance,
	HINSTANCE	hPrevInstance,
	LPSTR		lpCmdLine,
	int			nCmdShow)
{
	WindowsContainer win;
	win.main(hInstance, hPrevInstance, lpCmdLine, nCmdShow);

	return 0;
}

#else

//#include "vld.h" //insert debug-flag here

#include "LinuxContainer.h"
int main(int argc, char** argv)
{
	LinuxContainer* linuxContainer = new LinuxContainer();
	linuxContainer->mainContainer(argc, argv);
	DELETE_NULL(linuxContainer);

	return 0;
}
#endif //_WIN32
<commit_msg>redundant<commit_after>#ifndef _WIN32
#include "WindowsContainer.h"
int WINAPI WinMain(
	HINSTANCE	hInstance,
	HINSTANCE	hPrevInstance,
	LPSTR		lpCmdLine,
	int			nCmdShow)
{
	WindowsContainer win;
	win.main(hInstance, hPrevInstance, lpCmdLine, nCmdShow);

	return 0;
}

#else

#include "vld.h" //insert debug-flag here

#include "LinuxContainer.h"
int main(int argc, char** argv)
{
	LinuxContainer* linuxContainer = new LinuxContainer();
	linuxContainer->mainContainer(argc, argv);
	DELETE_NULL(linuxContainer);

	return 0;
}
#endif //_WIN32
<|endoftext|>