<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "ut_mapplicationpage.h"

#include <MApplicationWindow>
#include <MApplication>
#include "mapplicationpage_p.h"
#include <MSceneManager>

#include <MPannableViewport>
#include <MAction>
#include <MButton>
#include <MLayout>
#include <MGridLayoutPolicy>

#include "mondisplaychangeevent.h"

void Ut_MApplicationPage::initTestCase()
{
    static int argc = 1;
    static char *app_name[1] = { (char *) "./ut_mapplicationpage" };
    app = new MApplication(argc, app_name);
    appWin = new MApplicationWindow;

    qRegisterMetaType<MApplicationPage *>();
    qRegisterMetaType<MEscapeButtonPanelModel::EscapeMode>();
}

void Ut_MApplicationPage::cleanupTestCase()
{
    delete appWin;
    delete app;
}

void Ut_MApplicationPage::init()
{
    m_subject = new MApplicationPage;
}

void Ut_MApplicationPage::cleanup()
{
    // important: testCentralWidget deletes m_subject on its own
    if (m_subject) {
        delete m_subject;
        m_subject = 0;
    }
}

void Ut_MApplicationPage::testInitialValues()
{
    QCOMPARE(m_subject->title(), QString());
    QCOMPARE(m_subject->isContentCreated(), false);
    QVERIFY(m_subject->centralWidget());

    QCOMPARE(m_subject->isPannable(), true);
    QCOMPARE(m_subject->escapeMode(), MApplicationPageModel::EscapeAuto);
    QCOMPARE(m_subject->rememberPosition(), true);
}

void Ut_MApplicationPage::testProperties()
{
    QString title("Title of the page");
    bool pannable = true;
    Qt::Orientations panningDirection = Qt::Horizontal | Qt::Vertical;
    bool autoMarginsForComponents = true;
    MApplicationPageModel::PageEscapeMode escapeMode = MApplicationPageModel::EscapeManualBack;
    bool rememberPosition = false;

    m_subject->setTitle(title);
    QCOMPARE(m_subject->title(), title);
    m_subject->setPannable(pannable);
    QCOMPARE(m_subject->isPannable(), pannable);
    m_subject->setPanningDirection(panningDirection);
    QCOMPARE(m_subject->panningDirection(), panningDirection);
    m_subject->setAutoMarginsForComponentsEnabled(autoMarginsForComponents);
    QCOMPARE(m_subject->autoMarginsForComponentsEnabled(), autoMarginsForComponents);
    m_subject->setEscapeMode(escapeMode);
    QCOMPARE(m_subject->escapeMode(), escapeMode);
    m_subject->setRememberPosition(rememberPosition);
    QCOMPARE(m_subject->rememberPosition(), rememberPosition);
}

void Ut_MApplicationPage::testCentralWidget()
{
    QPointer<MWidget> widget = new MWidget;
    m_subject->setCentralWidget(widget);
    QCOMPARE(m_subject->centralWidget(), widget.data());

    // remove the current central widget and verify that it has been deleted
    m_subject->setCentralWidget(0);
    QCOMPARE(m_subject->centralWidget(), (MWidget *) 0);
    QVERIFY(widget.isNull());

    widget = new MWidget;
    m_subject->setCentralWidget(widget);
    QCOMPARE(m_subject->centralWidget(), widget.data());

    // delete the page to see if the central widget is deleted
    delete m_subject;
    m_subject = 0;
    QVERIFY(widget.isNull());
}

void Ut_MApplicationPage::testCreateContent()
{
    QVERIFY(!m_subject->isContentCreated());
    m_subject->createContent();
    QVERIFY(m_subject->isContentCreated());
}

void Ut_MApplicationPage::testPageTitleChanged()
{
    qRegisterMetaType< QList<const char *> >("QList<const char *>");

    QSignalSpy spy(m_subject->model(), SIGNAL(modified(QList<const char *>)));
    QString title("Title!");

    m_subject->setTitle(m_subject->title());
    QCOMPARE(spy.count(), 0);
    m_subject->setTitle(title);
    QCOMPARE(spy.count(), 1);
    QCOMPARE(m_subject->model()->title(), title);
    m_subject->setTitle(title);
    QCOMPARE(spy.count(), 1);
    m_subject->setTitle(QString());
    QCOMPARE(spy.count(), 2);
    QCOMPARE(m_subject->model()->title(), QString());
}

void Ut_MApplicationPage::testRememberPosition()
{
    m_subject->setRememberPosition(true);
    m_subject->d_func()->pannableViewPort->setPosition(QPointF(0, 10));
    appWin->sceneManager()->appearSceneWindowNow(m_subject);
    QCOMPARE(m_subject->d_func()->pannableViewPort->position() + QPointF(10, 10), QPointF(10, 20));
    QCOMPARE(m_subject->d_func()->pannableViewPort->physics()->position() + QPointF(10, 10),  QPointF(10, 20));
}

void Ut_MApplicationPage::testForgetPosition()
{
    m_subject->setRememberPosition(false);
    m_subject->d_func()->pannableViewPort->setPosition(QPointF(0, 10));
    appWin->sceneManager()->appearSceneWindowNow(m_subject);
    QCOMPARE(m_subject->d_func()->pannableViewPort->position() + QPointF(10, 10), QPointF(10, 10));
    QCOMPARE(m_subject->d_func()->pannableViewPort->physics()->position() + QPointF(10, 10),  QPointF(10, 10));
}

void Ut_MApplicationPage::testActionUpdated()
{
    m_subject->clearActions();
    QSignalSpy spy(m_subject, SIGNAL(actionUpdated(QActionEvent *)));
    QCOMPARE(spy.count(), 0);

    m_subject->addAction(new MAction("test application page", m_subject));
    QCOMPARE(spy.count(), 1);

    m_subject->clearActions();
    QCOMPARE(spy.count(), 2);
}

void Ut_MApplicationPage::testDefaultComponentDisplayModes()
{
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Show);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::Show);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::EscapeButton), MApplicationPageModel::Show);
}

void Ut_MApplicationPage::testSettingComponentsDisplayModes()
{
    MApplicationPageModel *model = m_subject->model();

    m_subject->setComponentsDisplayMode(MApplicationPage::NavigationBar, MApplicationPageModel::Hide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Hide);
    QCOMPARE(model->navigationBarDisplayMode(), MApplicationPageModel::Hide);

    m_subject->setComponentsDisplayMode(MApplicationPage::HomeButton, MApplicationPageModel::AutoHide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::AutoHide);
    QCOMPARE(model->homeButtonDisplayMode(), MApplicationPageModel::AutoHide);
}

void Ut_MApplicationPage::testSettingMultipleComponentsDisplayModes()
{
    MApplicationPageModel *model = m_subject->model();

    m_subject->setComponentsDisplayMode(MApplicationPage::NavigationBar | MApplicationPage::HomeButton,
                                        MApplicationPageModel::Hide);

    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Hide);
    QCOMPARE(model->navigationBarDisplayMode(), MApplicationPageModel::Hide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::Hide);
    QCOMPARE(model->homeButtonDisplayMode(), MApplicationPageModel::Hide);
}

void Ut_MApplicationPage::testSettingAllComponentsDisplayMode()
{
    m_subject->setComponentsDisplayMode(MApplicationPage::AllComponents, MApplicationPageModel::Hide);

    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Hide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::Hide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::EscapeButton), MApplicationPageModel::Hide);

    m_subject->setComponentsDisplayMode(MApplicationPage::AllComponents, MApplicationPageModel::Show);

    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Show);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::Show);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::EscapeButton), MApplicationPageModel::Show);
}

void Ut_MApplicationPage::testUpdatingWindowTitleWithChangingPageTitle()
{
    QString title("Test title");
    QString title2("Another test title");
    QString title3("Multiple length variants title\0x9cMult. length var. title");
    QString title3_longest("Multiple length variants title");
    QString title4;

    m_subject->appear();

    m_subject->setTitle(title);
    QCOMPARE(appWin->windowTitle(), title);
    m_subject->setTitle(title2);
    QCOMPARE(appWin->windowTitle(), title2);
    m_subject->setTitle(title3);
    QCOMPARE(appWin->windowTitle(), title3_longest);
    m_subject->setTitle(title4);
    QCOMPARE(appWin->windowTitle(), title4);
}

QTEST_APPLESS_MAIN(Ut_MApplicationPage)
<commit_msg>Fixes: failing ut_mapplicationpage unittest<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "ut_mapplicationpage.h"

#include <MApplicationWindow>
#include <MApplication>
#include "mapplicationpage_p.h"
#include <MSceneManager>

#include <MPannableViewport>
#include <MAction>
#include <MButton>
#include <MLayout>
#include <MGridLayoutPolicy>

#include "mondisplaychangeevent.h"

void Ut_MApplicationPage::initTestCase()
{
    static int argc = 1;
    static char *app_name[1] = { (char *) "./ut_mapplicationpage" };
    app = new MApplication(argc, app_name);
    appWin = new MApplicationWindow;

    qRegisterMetaType<MApplicationPage *>();
    qRegisterMetaType<MEscapeButtonPanelModel::EscapeMode>();
}

void Ut_MApplicationPage::cleanupTestCase()
{
    delete appWin;
    delete app;
}

void Ut_MApplicationPage::init()
{
    m_subject = new MApplicationPage;
}

void Ut_MApplicationPage::cleanup()
{
    // important: testCentralWidget deletes m_subject on its own
    if (m_subject) {
        delete m_subject;
        m_subject = 0;
    }
}

void Ut_MApplicationPage::testInitialValues()
{
    QCOMPARE(m_subject->title(), QString());
    QCOMPARE(m_subject->isContentCreated(), false);
    QVERIFY(m_subject->centralWidget());

    QCOMPARE(m_subject->isPannable(), true);
    QCOMPARE(m_subject->escapeMode(), MApplicationPageModel::EscapeAuto);
    QCOMPARE(m_subject->rememberPosition(), true);
}

void Ut_MApplicationPage::testProperties()
{
    QString title("Title of the page");
    bool pannable = true;
    Qt::Orientations panningDirection = Qt::Horizontal | Qt::Vertical;
    bool autoMarginsForComponents = true;
    MApplicationPageModel::PageEscapeMode escapeMode = MApplicationPageModel::EscapeManualBack;
    bool rememberPosition = false;

    m_subject->setTitle(title);
    QCOMPARE(m_subject->title(), title);
    m_subject->setPannable(pannable);
    QCOMPARE(m_subject->isPannable(), pannable);
    m_subject->setPanningDirection(panningDirection);
    QCOMPARE(m_subject->panningDirection(), panningDirection);
    m_subject->setAutoMarginsForComponentsEnabled(autoMarginsForComponents);
    QCOMPARE(m_subject->autoMarginsForComponentsEnabled(), autoMarginsForComponents);
    m_subject->setEscapeMode(escapeMode);
    QCOMPARE(m_subject->escapeMode(), escapeMode);
    m_subject->setRememberPosition(rememberPosition);
    QCOMPARE(m_subject->rememberPosition(), rememberPosition);
}

void Ut_MApplicationPage::testCentralWidget()
{
    QPointer<MWidget> widget = new MWidget;
    m_subject->setCentralWidget(widget);
    QCOMPARE(m_subject->centralWidget(), widget.data());

    // remove the current central widget and verify that it has been deleted
    m_subject->setCentralWidget(0);
    QCOMPARE(m_subject->centralWidget(), (MWidget *) 0);
    QVERIFY(widget.isNull());

    widget = new MWidget;
    m_subject->setCentralWidget(widget);
    QCOMPARE(m_subject->centralWidget(), widget.data());

    // delete the page to see if the central widget is deleted
    delete m_subject;
    m_subject = 0;
    QVERIFY(widget.isNull());
}

void Ut_MApplicationPage::testCreateContent()
{
    QVERIFY(!m_subject->isContentCreated());
    m_subject->createContent();
    QVERIFY(m_subject->isContentCreated());
}

void Ut_MApplicationPage::testPageTitleChanged()
{
    qRegisterMetaType< QList<const char *> >("QList<const char *>");

    QSignalSpy spy(m_subject->model(), SIGNAL(modified(QList<const char *>)));
    QString title("Title!");

    m_subject->setTitle(m_subject->title());
    QCOMPARE(spy.count(), 0);
    m_subject->setTitle(title);
    QCOMPARE(spy.count(), 1);
    QCOMPARE(m_subject->model()->title(), title);
    m_subject->setTitle(title);
    QCOMPARE(spy.count(), 1);
    m_subject->setTitle(QString());
    QCOMPARE(spy.count(), 2);
    QCOMPARE(m_subject->model()->title(), QString());
}

void Ut_MApplicationPage::testRememberPosition()
{
    m_subject->setRememberPosition(true);
    m_subject->d_func()->pannableViewPort->adjustSize();
    m_subject->d_func()->pannableViewPort->setPosition(QPointF(0, 10));
    appWin->sceneManager()->appearSceneWindowNow(m_subject);
    QCOMPARE(m_subject->d_func()->pannableViewPort->position() + QPointF(10, 10), QPointF(10, 20));
    QCOMPARE(m_subject->d_func()->pannableViewPort->physics()->position() + QPointF(10, 10),  QPointF(10, 20));
}

void Ut_MApplicationPage::testForgetPosition()
{
    m_subject->setRememberPosition(false);
    m_subject->d_func()->pannableViewPort->adjustSize();
    m_subject->d_func()->pannableViewPort->setPosition(QPointF(0, 10));
    appWin->sceneManager()->appearSceneWindowNow(m_subject);
    QCOMPARE(m_subject->d_func()->pannableViewPort->position() + QPointF(10, 10), QPointF(10, 10));
    QCOMPARE(m_subject->d_func()->pannableViewPort->physics()->position() + QPointF(10, 10),  QPointF(10, 10));
}

void Ut_MApplicationPage::testActionUpdated()
{
    m_subject->clearActions();
    QSignalSpy spy(m_subject, SIGNAL(actionUpdated(QActionEvent *)));
    QCOMPARE(spy.count(), 0);

    m_subject->addAction(new MAction("test application page", m_subject));
    QCOMPARE(spy.count(), 1);

    m_subject->clearActions();
    QCOMPARE(spy.count(), 2);
}

void Ut_MApplicationPage::testDefaultComponentDisplayModes()
{
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Show);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::Show);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::EscapeButton), MApplicationPageModel::Show);
}

void Ut_MApplicationPage::testSettingComponentsDisplayModes()
{
    MApplicationPageModel *model = m_subject->model();

    m_subject->setComponentsDisplayMode(MApplicationPage::NavigationBar, MApplicationPageModel::Hide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Hide);
    QCOMPARE(model->navigationBarDisplayMode(), MApplicationPageModel::Hide);

    m_subject->setComponentsDisplayMode(MApplicationPage::HomeButton, MApplicationPageModel::AutoHide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::AutoHide);
    QCOMPARE(model->homeButtonDisplayMode(), MApplicationPageModel::AutoHide);
}

void Ut_MApplicationPage::testSettingMultipleComponentsDisplayModes()
{
    MApplicationPageModel *model = m_subject->model();

    m_subject->setComponentsDisplayMode(MApplicationPage::NavigationBar | MApplicationPage::HomeButton,
                                        MApplicationPageModel::Hide);

    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Hide);
    QCOMPARE(model->navigationBarDisplayMode(), MApplicationPageModel::Hide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::Hide);
    QCOMPARE(model->homeButtonDisplayMode(), MApplicationPageModel::Hide);
}

void Ut_MApplicationPage::testSettingAllComponentsDisplayMode()
{
    m_subject->setComponentsDisplayMode(MApplicationPage::AllComponents, MApplicationPageModel::Hide);

    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Hide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::Hide);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::EscapeButton), MApplicationPageModel::Hide);

    m_subject->setComponentsDisplayMode(MApplicationPage::AllComponents, MApplicationPageModel::Show);

    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::NavigationBar), MApplicationPageModel::Show);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::HomeButton), MApplicationPageModel::Show);
    QCOMPARE(m_subject->componentDisplayMode(MApplicationPage::EscapeButton), MApplicationPageModel::Show);
}

void Ut_MApplicationPage::testUpdatingWindowTitleWithChangingPageTitle()
{
    QString title("Test title");
    QString title2("Another test title");
    QString title3("Multiple length variants title\0x9cMult. length var. title");
    QString title3_longest("Multiple length variants title");
    QString title4;

    m_subject->appear();

    m_subject->setTitle(title);
    QCOMPARE(appWin->windowTitle(), title);
    m_subject->setTitle(title2);
    QCOMPARE(appWin->windowTitle(), title2);
    m_subject->setTitle(title3);
    QCOMPARE(appWin->windowTitle(), title3_longest);
    m_subject->setTitle(title4);
    QCOMPARE(appWin->windowTitle(), title4);
}

QTEST_APPLESS_MAIN(Ut_MApplicationPage)
<|endoftext|>


<commit_before>#include <socket.h>
#include <utils/logger.h>

using meshy::Socket;
using meshy::NativeSocket;
using meshy::SocketAddress;

#ifdef OS_WIN32
#pragma comment(lib, "Ws2_32.lib")	// closesocket
#endif // OS_WIN32

NativeSocket Socket::CreateNativeSocket() {
	NativeSocket fd = socket(PF_INET, SOCK_STREAM, 0);
	if (INVALID_SOCKET == fd)
	{
#ifdef OS_WIN32
		TRACE_ERROR("Create socket failed! errorno={0}", WSAGetLastError());
#else
		TRACE_ERROR("Create socket failed! errorno={0}", errno);
#endif
		exit(1);
	}
	return fd;
}

Socket::Socket(NativeSocket nativeSocket, SocketAddress const& address)
	: m_nativeSocket(nativeSocket), m_socketAddress(address)
{

}

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

void Socket::close() {
	TRACE_ERROR("关闭连接socket={}", m_nativeSocket);
#ifdef OS_WIN32
	closesocket(m_nativeSocket);
#else
	close(m_nativeSocket);
#endif // OS_WIN32
	m_nativeSocket = -1;
}

NativeSocket Socket::GetNativeSocket()const {
	return m_nativeSocket;
}

void Socket::SetNativeSocket(NativeSocket nativeSocket) {
	m_nativeSocket = nativeSocket;
}

SocketAddress const& Socket::GetSocketAddress()const {
	return m_socketAddress;
}

int Socket::type()const {
	return getsockopt(SOL_SOCKET, SO_TYPE);
}

int Socket::getsockopt(int level, int optname)const {
	int optval = 0, optlen = 0;
	int state = ::getsockopt(m_nativeSocket, level, optname, (char*)&optval, &optlen);
	if (state)
	{
		// 发生了错误
		return -1;
	}
	return optval;
}
int Socket::setsockopt(int level, int optname, int optval) {
	int optlen = sizeof(optval);
	int state = ::setsockopt(m_nativeSocket, level, optname, (char const*)&optval, optlen);
	assert(SOCKET_ERROR != state);
	return state;
}

int Socket::sendbuf()const {
	return getsockopt(SOL_SOCKET, SO_SNDBUF);
}
int Socket::recvbuf()const {
	return getsockopt(SOL_SOCKET, SO_RCVBUF);
}

int Socket::sendbuf(int new_size) {
	return setsockopt(SOL_SOCKET, SO_SNDBUF, new_size);
}
int Socket::recvbuf(int new_size) {
	return setsockopt(SOL_SOCKET, SO_RCVBUF, new_size);
}

int Socket::nodelay(bool value) {
	int new_value = value;
	return setsockopt(IPPROTO_TCP, TCP_NODELAY, new_value);
}

int Socket::ReuseAddr() {
	return setsockopt(SOL_SOCKET, SO_REUSEADDR, 1);
}
<commit_msg>IOCP 995<commit_after>#include <socket.h>
#include <utils/logger.h>

using meshy::Socket;
using meshy::NativeSocket;
using meshy::SocketAddress;

#ifdef OS_WIN32
#pragma comment(lib, "Ws2_32.lib")	// closesocket
#endif // OS_WIN32

NativeSocket Socket::CreateNativeSocket() {
	NativeSocket fd = socket(PF_INET, SOCK_STREAM, 0);
	if (INVALID_SOCKET == fd)
	{
#ifdef OS_WIN32
		TRACE_ERROR("Create socket failed! errorno={0}", WSAGetLastError());
#else
		TRACE_ERROR("Create socket failed! errorno={0}", errno);
#endif
		exit(1);
	}
	return fd;
}

Socket::Socket(NativeSocket nativeSocket, SocketAddress const& address)
	: m_nativeSocket(nativeSocket), m_socketAddress(address)
{

}

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

void Socket::close() {
	TRACE_ERROR("关闭连接socket={}", m_nativeSocket);
#ifdef OS_WIN32
	shutdown(m_nativeSocket, SD_BOTH);
	// closesocket(m_nativeSocket);	// 会报995 IocpLoop.cpp(148):GetQueuedCompletionStatus errno=0,Error: 995,fd=176
#else
	close(m_nativeSocket);
#endif // OS_WIN32
	m_nativeSocket = INVALID_SOCKET;	// 不知道哪里把它当作指针使用了
}

NativeSocket Socket::GetNativeSocket()const {
	return m_nativeSocket;
}

void Socket::SetNativeSocket(NativeSocket nativeSocket) {
	m_nativeSocket = nativeSocket;
}

SocketAddress const& Socket::GetSocketAddress()const {
	return m_socketAddress;
}

int Socket::type()const {
	return getsockopt(SOL_SOCKET, SO_TYPE);
}

int Socket::getsockopt(int level, int optname)const {
	int optval = 0, optlen = 0;
	int state = ::getsockopt(m_nativeSocket, level, optname, (char*)&optval, &optlen);
	if (state)
	{
		// 发生了错误
		return -1;
	}
	return optval;
}
int Socket::setsockopt(int level, int optname, int optval) {
	int optlen = sizeof(optval);
	int state = ::setsockopt(m_nativeSocket, level, optname, (char const*)&optval, optlen);
	assert(SOCKET_ERROR != state);
	return state;
}

int Socket::sendbuf()const {
	return getsockopt(SOL_SOCKET, SO_SNDBUF);
}
int Socket::recvbuf()const {
	return getsockopt(SOL_SOCKET, SO_RCVBUF);
}

int Socket::sendbuf(int new_size) {
	return setsockopt(SOL_SOCKET, SO_SNDBUF, new_size);
}
int Socket::recvbuf(int new_size) {
	return setsockopt(SOL_SOCKET, SO_RCVBUF, new_size);
}

int Socket::nodelay(bool value) {
	int new_value = value;
	return setsockopt(IPPROTO_TCP, TCP_NODELAY, new_value);
}

int Socket::ReuseAddr() {
	return setsockopt(SOL_SOCKET, SO_REUSEADDR, 1);
}
<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include "BVshared.h"
#include "BVgene.h"

std::vector<gene_expression>
gene_expression_vector(std::vector<std::vector<std::string>> raw_data) {
  int current_row, current_col;
  double current_element;
  bool process = true;
  std::vector<gene_expression> gene_data;
  for (current_row = 1; current_row < raw_data.size(); current_row++) {
    gene_expression ge_row;
    ge_row.gene_name = raw_data[current_row][0];
    ////std::cout << "Processing gene: " << ge_row.gene_name << std::endl;
    for (current_col = 0; current_col < raw_data[current_row].size();
         current_col++) {
      try {
        current_element = std::stod(raw_data[current_row][current_col]);
      } catch (std::exception &e) {
        process = false;
      }

      if (process) {
        if (current_col > 0 && current_col < 9) {
          /*std::cout << "Processing element (type, value): "
                    << "renal, " << current_element << std::endl; */
          ge_row.renal_disease.push_back(current_element);
        }
        if (current_col >= 9) {
          /*std::cout << "Processing element (type, value): "
                    << "control, " << current_element << std::endl; */
          ge_row.control.push_back(current_element);
        }
      }
      process = true;
    }
    gene_data.push_back(ge_row);
  }
  return gene_data;
}

gene_result process(gene_expression data_row) {
  int i;
  // combine vectors to do t-stat permutations
  std::vector<double> all_gene_data;
  all_gene_data.reserve(data_row.renal_disease.size() +
                        data_row.control.size()); // preallocate memory
  all_gene_data.insert(all_gene_data.end(), data_row.renal_disease.begin(),
                       data_row.renal_disease.end());
  all_gene_data.insert(all_gene_data.end(), data_row.control.begin(),
                       data_row.control.end());
  std::vector<double> permutation_t_stats;
  for (i = 0; i < 1000; i++) {
    // shuffle the order
    std::random_shuffle(all_gene_data.begin(), all_gene_data.end());
    // split the vector into 2
    std::vector<double> all_gene_data1(all_gene_data.begin(),
                                       all_gene_data.begin() +
                                           data_row.renal_disease.size()),
        all_gene_data2(all_gene_data.begin() + data_row.renal_disease.size(),
                       all_gene_data.end());
    // add the random t-stat to the t-stat list
    double random_t_stat = students_t_stat(all_gene_data1, all_gene_data2);
    /*if (std::isinf(random_t_stat)) {
      std::cout << "This data set is infinite: ";
      print_1d_vector(all_gene_data1);
      print_1d_vector(all_gene_data2);
    }*/
    permutation_t_stats.push_back(random_t_stat);
  }

  // find the d-score
  double t_stat = students_t_stat(data_row.renal_disease, data_row.control);
  double random_t_stat_mean = mean(permutation_t_stats);
  double random_standard_deviation = standard_deviation(permutation_t_stats);
  double absolute_value = std::abs(t_stat - random_t_stat_mean);
  double d_score = absolute_value / random_standard_deviation;
  return gene_result(data_row.gene_name, d_score);
}
<commit_msg>remove ugly comments<commit_after>#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include "BVshared.h"
#include "BVgene.h"

std::vector<gene_expression>
gene_expression_vector(std::vector<std::vector<std::string>> raw_data) {
  int current_row, current_col;
  double current_element;
  bool process = true;
  std::vector<gene_expression> gene_data;
  for (current_row = 1; current_row < raw_data.size(); current_row++) {
    gene_expression ge_row;
    ge_row.gene_name = raw_data[current_row][0];
    for (current_col = 0; current_col < raw_data[current_row].size();
         current_col++) {
      try {
        current_element = std::stod(raw_data[current_row][current_col]);
      } catch (std::exception &e) {
        process = false;
      }

      if (process) {
        if (current_col > 0 && current_col < 9) {
          ge_row.renal_disease.push_back(current_element);
        }
        if (current_col >= 9) {
          ge_row.control.push_back(current_element);
        }
      }
      process = true;
    }
    gene_data.push_back(ge_row);
  }
  return gene_data;
}

gene_result process(gene_expression data_row) {
  int i;
  // combine vectors to do t-stat permutations
  std::vector<double> all_gene_data;
  all_gene_data.reserve(data_row.renal_disease.size() +
                        data_row.control.size()); // preallocate memory
  all_gene_data.insert(all_gene_data.end(), data_row.renal_disease.begin(),
                       data_row.renal_disease.end());
  all_gene_data.insert(all_gene_data.end(), data_row.control.begin(),
                       data_row.control.end());
  std::vector<double> permutation_t_stats;
  for (i = 0; i < 1000; i++) {
    // shuffle the order
    std::random_shuffle(all_gene_data.begin(), all_gene_data.end());
    // split the vector into 2
    std::vector<double> all_gene_data1(all_gene_data.begin(),
                                       all_gene_data.begin() +
                                           data_row.renal_disease.size()),
        all_gene_data2(all_gene_data.begin() + data_row.renal_disease.size(),
                       all_gene_data.end());
    // add the random t-stat to the t-stat list
    double random_t_stat = students_t_stat(all_gene_data1, all_gene_data2);
    permutation_t_stats.push_back(random_t_stat);
  }

  // find the d-score
  double t_stat = students_t_stat(data_row.renal_disease, data_row.control);
  double random_t_stat_mean = mean(permutation_t_stats);
  double random_standard_deviation = standard_deviation(permutation_t_stats);
  double absolute_value = std::abs(t_stat - random_t_stat_mean);
  double d_score = absolute_value / random_standard_deviation;
  return gene_result(data_row.gene_name, d_score);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 New Designs Unlimited, LLC
 * Opensource Automated License Plate Recognition [http://www.openalpr.com]
 *
 * This file is part of OpenAlpr.
 *
 * OpenAlpr is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License
 * version 3 as published by the Free Software Foundation
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <sys/stat.h>
#include "support/filesystem.h"
#include "../tclap/CmdLine.h"

using namespace std;
using namespace cv;
using namespace alpr;

// Takes a directory full of single char images, and plops them on a big tif files
// Also creates a box file so Tesseract can recognize it
int main( int argc, const char** argv )
{
  string inDir;
  int tile_width;
  int tile_height;

  TCLAP::CmdLine cmd("OpenAlpr OCR Training Prep Utility", ' ', "1.0.0");

  TCLAP::UnlabeledValueArg<std::string>  inputDirArg( "input_dir", "Folder containing individual character images", true, "", "input_dir_path"  );

  TCLAP::ValueArg<int> tileWidthArg("","tile_width","Width (in pixels) for each character tile.  Default=50",false, 50 ,"tile_width_px");
  TCLAP::ValueArg<int> tileHeightArg("","tile_height","Height (in pixels) for each character tile.  Default=60",false, 60 ,"tile_height_px");

  try
  {
    cmd.add( inputDirArg );
    cmd.add( tileWidthArg );
    cmd.add( tileHeightArg );

    if (cmd.parse( argc, argv ) == false)
    {
      // Error occured while parsing.  Exit now.
      return 1;
    }

    inDir = inputDirArg.getValue();
    tile_width = tileWidthArg.getValue();
    tile_height = tileHeightArg.getValue();

  }
  catch (TCLAP::ArgException &e)    // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return 1;
  }

  if (DirectoryExists(inDir.c_str()) == false)
  {
    printf("Output dir does not exist\n");
    return 0;
  }

  if (DirectoryExists(inDir.c_str()))
  {
    const int CHAR_PADDING_HORIZONTAL = 0;
    const int CHAR_PADDING_VERTICAL = 0;

    const int X_OFFSET = 5;
    const int Y_OFFSET = 5;

    const int PAGE_MARGIN_X = 70;
    const int PAGE_MARGIN_Y = 70;
    const int HORIZONTAL_RESOLUTION = 3500;
    const int MAX_VERTICAL_RESOLUTION = 6000; // Maximum vertical size before chopping into additional pages.

    const int TILE_WIDTH = tile_width;
    const int TILE_HEIGHT = tile_height;
    const int CHAR_HORIZ_OFFSET = 40;
    const int CHAR_VERT_OFFSET = 48;

    const int FIXED_CHAR_HEIGHT = 40; // RESIZE all characters to this height

    vector<string> files = getFilesInDir(inDir.c_str());

    sort( files.begin(), files.end(), stringCompare );

    for (int i = 0; i< files.size(); i++)
    {
      if (hasEnding(files[i], ".png") || hasEnding(files[i], ".jpg"))
      {

      }
      else
      {
	std::cerr << "Non-image file detected in this directory.  This must be removed first" << std::endl;
	return 1;
      }
    }

    int tiles_per_row = ((float) (HORIZONTAL_RESOLUTION - (PAGE_MARGIN_X * 2))) / ((float) TILE_WIDTH);
    int lines = files.size() / (tiles_per_row);
    int vertical_resolution = (lines * TILE_HEIGHT) + (PAGE_MARGIN_Y * 3) ;
    cout << tiles_per_row <<   " : " << vertical_resolution << endl;

    Mat bigTif = Mat::zeros(Size(HORIZONTAL_RESOLUTION, vertical_resolution), CV_8U);
    bitwise_not(bigTif, bigTif);

    stringstream boxFileOut;

    for (int i = 0; i< files.size(); i++)
    {
      int col = i % tiles_per_row;
      int line = i / tiles_per_row;

      int xPos = (col * TILE_WIDTH) + PAGE_MARGIN_X;
      int yPos = (line * TILE_HEIGHT) + PAGE_MARGIN_Y;

      if (hasEnding(files[i], ".png") || hasEnding(files[i], ".jpg"))
      {
        string fullpath = inDir + "/" + files[i];

        cout << "Processing file: " << (i + 1) << " of " << files.size() << endl;

        char charcode = files[i][0];

        Mat characterImg = imread(fullpath);

        Mat charImgCopy = Mat::zeros(Size(150, 150), characterImg.type());
        bitwise_not(charImgCopy, charImgCopy);

        characterImg.copyTo(charImgCopy(Rect(X_OFFSET, Y_OFFSET, characterImg.cols, characterImg.rows)));
        cvtColor(charImgCopy, charImgCopy, CV_BGR2GRAY);
        bitwise_not(charImgCopy, charImgCopy);

        vector<vector<Point> > contours;

        //imshow("copy", charImgCopy);
        findContours(charImgCopy, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

	float minHeightPercent = 0.35;
	int minHeight = (int) (((float) characterImg.rows) * minHeightPercent);

	vector<Rect> tallEnoughRects;
        for (int c = 0; c < contours.size(); c++)
        {
          Rect tmpRect = boundingRect(contours[c]);
          if (tmpRect.height > minHeight)
            tallEnoughRects.push_back( tmpRect );
        }

	int xMin = 9999999, xMax = 0, yMin = 9999999, yMax = 0;
        // Combine all the "tall enough" rectangles into one super rectangle
        for (int r = 0; r < tallEnoughRects.size(); r++)
	{
	  if (tallEnoughRects[r].x < xMin)
	    xMin = tallEnoughRects[r].x;
	  if (tallEnoughRects[r].y < yMin)
	    yMin = tallEnoughRects[r].y;
	  if (tallEnoughRects[r].x + tallEnoughRects[r].width > xMax)
	    xMax = tallEnoughRects[r].x + tallEnoughRects[r].width;
	  if (tallEnoughRects[r].y + tallEnoughRects[r].height > yMax)
	    yMax = tallEnoughRects[r].y + tallEnoughRects[r].height;
	}

        Rect tallestRect(xMin, yMin, xMax - xMin, yMax - yMin);

        //cout << tallestRect.x << ":" << tallestRect.y << " -- " << tallestRect.width << ":" << tallestRect.height << endl;

        Rect cropRect(0, tallestRect.y - Y_OFFSET, tallestRect.width, tallestRect.height);

        //cout << "Cropped: " << cropRect.x << ":" << cropRect.y << " -- " << cropRect.width << ":" << cropRect.height << endl;
        Mat cropped(characterImg, cropRect);
        cvtColor(cropped, cropped, CV_BGR2GRAY);

        Rect destinationRect(xPos + (CHAR_HORIZ_OFFSET - TILE_WIDTH), yPos + (CHAR_VERT_OFFSET - TILE_HEIGHT + (TILE_HEIGHT - tallestRect.height)), tallestRect.width, tallestRect.height);

        //cout << "1" << endl;

        cropped.copyTo(bigTif(destinationRect));

        int x1 = destinationRect.x - CHAR_PADDING_HORIZONTAL;
        int y1 = (vertical_resolution - destinationRect.y - destinationRect.height) - CHAR_PADDING_VERTICAL;
        int x2 = (destinationRect.x + destinationRect.width) + CHAR_PADDING_HORIZONTAL;
        int y2 = (vertical_resolution - destinationRect.y) + CHAR_PADDING_VERTICAL;
        //0 70 5602 85 5636 0
        boxFileOut << charcode << " " << x1 << " " << y1 << " ";
        boxFileOut << x2 << " " << y2 ;
        boxFileOut << " 0" << endl;

        //rectangle(characterImg, tallestRect, Scalar(0, 255, 0));
        //imshow("characterImg", cropped);

        waitKey(2);
      }
    }

    imwrite("combined.tif", bigTif);
    ofstream boxFile("combined.box", std::ios::out);
    boxFile << boxFileOut.str();
  }
}
<commit_msg>Removed unnecessary if statement<commit_after>/*
 * Copyright (c) 2015 New Designs Unlimited, LLC
 * Opensource Automated License Plate Recognition [http://www.openalpr.com]
 *
 * This file is part of OpenAlpr.
 *
 * OpenAlpr is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License
 * version 3 as published by the Free Software Foundation
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <sys/stat.h>
#include "support/filesystem.h"
#include "../tclap/CmdLine.h"

using namespace std;
using namespace cv;
using namespace alpr;

// Takes a directory full of single char images, and plops them on a big tif files
// Also creates a box file so Tesseract can recognize it
int main( int argc, const char** argv )
{
  string inDir;
  int tile_width;
  int tile_height;

  TCLAP::CmdLine cmd("OpenAlpr OCR Training Prep Utility", ' ', "1.0.0");

  TCLAP::UnlabeledValueArg<std::string>  inputDirArg( "input_dir", "Folder containing individual character images", true, "", "input_dir_path"  );

  TCLAP::ValueArg<int> tileWidthArg("","tile_width","Width (in pixels) for each character tile.  Default=50",false, 50 ,"tile_width_px");
  TCLAP::ValueArg<int> tileHeightArg("","tile_height","Height (in pixels) for each character tile.  Default=60",false, 60 ,"tile_height_px");

  try
  {
    cmd.add( inputDirArg );
    cmd.add( tileWidthArg );
    cmd.add( tileHeightArg );

    if (cmd.parse( argc, argv ) == false)
    {
      // Error occured while parsing.  Exit now.
      return 1;
    }

    inDir = inputDirArg.getValue();
    tile_width = tileWidthArg.getValue();
    tile_height = tileHeightArg.getValue();

  }
  catch (TCLAP::ArgException &e)    // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return 1;
  }

  if (DirectoryExists(inDir.c_str()) == false)
  {
    printf("Output dir does not exist\n");
    return 0;
  }

  const int CHAR_PADDING_HORIZONTAL = 0;
  const int CHAR_PADDING_VERTICAL = 0;

  const int X_OFFSET = 5;
  const int Y_OFFSET = 5;

  const int PAGE_MARGIN_X = 70;
  const int PAGE_MARGIN_Y = 70;
  const int HORIZONTAL_RESOLUTION = 3500;
  const int MAX_VERTICAL_RESOLUTION = 6000; // Maximum vertical size before chopping into additional pages.

  const int TILE_WIDTH = tile_width;
  const int TILE_HEIGHT = tile_height;
  const int CHAR_HORIZ_OFFSET = 40;
  const int CHAR_VERT_OFFSET = 48;

  const int FIXED_CHAR_HEIGHT = 40; // RESIZE all characters to this height

  vector<string> files = getFilesInDir(inDir.c_str());

  sort( files.begin(), files.end(), stringCompare );

  for (int i = 0; i< files.size(); i++)
  {
    if (hasEnding(files[i], ".png") || hasEnding(files[i], ".jpg"))
    {

    }
    else
    {
      std::cerr << "Non-image file detected in this directory.  This must be removed first" << std::endl;
      return 1;
    }
  }

  int tiles_per_row = ((float) (HORIZONTAL_RESOLUTION - (PAGE_MARGIN_X * 2))) / ((float) TILE_WIDTH);
  int lines = files.size() / (tiles_per_row);
  int vertical_resolution = (lines * TILE_HEIGHT) + (PAGE_MARGIN_Y * 3) ;
  cout << tiles_per_row <<   " : " << vertical_resolution << endl;

  Mat bigTif = Mat::zeros(Size(HORIZONTAL_RESOLUTION, vertical_resolution), CV_8U);
  bitwise_not(bigTif, bigTif);

  stringstream boxFileOut;

  for (int i = 0; i< files.size(); i++)
  {
    int col = i % tiles_per_row;
    int line = i / tiles_per_row;

    int xPos = (col * TILE_WIDTH) + PAGE_MARGIN_X;
    int yPos = (line * TILE_HEIGHT) + PAGE_MARGIN_Y;

    if (hasEnding(files[i], ".png") || hasEnding(files[i], ".jpg"))
    {
      string fullpath = inDir + "/" + files[i];

      cout << "Processing file: " << (i + 1) << " of " << files.size() << endl;

      char charcode = files[i][0];

      Mat characterImg = imread(fullpath);

      Mat charImgCopy = Mat::zeros(Size(150, 150), characterImg.type());
      bitwise_not(charImgCopy, charImgCopy);

      characterImg.copyTo(charImgCopy(Rect(X_OFFSET, Y_OFFSET, characterImg.cols, characterImg.rows)));
      cvtColor(charImgCopy, charImgCopy, CV_BGR2GRAY);
      bitwise_not(charImgCopy, charImgCopy);

      vector<vector<Point> > contours;

      //imshow("copy", charImgCopy);
      findContours(charImgCopy, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

      float minHeightPercent = 0.35;
      int minHeight = (int) (((float) characterImg.rows) * minHeightPercent);

      vector<Rect> tallEnoughRects;
      for (int c = 0; c < contours.size(); c++)
      {
        Rect tmpRect = boundingRect(contours[c]);
        if (tmpRect.height > minHeight)
          tallEnoughRects.push_back( tmpRect );
      }

      int xMin = 9999999, xMax = 0, yMin = 9999999, yMax = 0;
      // Combine all the "tall enough" rectangles into one super rectangle
      for (int r = 0; r < tallEnoughRects.size(); r++)
      {
        if (tallEnoughRects[r].x < xMin)
          xMin = tallEnoughRects[r].x;
        if (tallEnoughRects[r].y < yMin)
          yMin = tallEnoughRects[r].y;
        if (tallEnoughRects[r].x + tallEnoughRects[r].width > xMax)
          xMax = tallEnoughRects[r].x + tallEnoughRects[r].width;
        if (tallEnoughRects[r].y + tallEnoughRects[r].height > yMax)
          yMax = tallEnoughRects[r].y + tallEnoughRects[r].height;
      }

      Rect tallestRect(xMin, yMin, xMax - xMin, yMax - yMin);

      //cout << tallestRect.x << ":" << tallestRect.y << " -- " << tallestRect.width << ":" << tallestRect.height << endl;

      Rect cropRect(0, tallestRect.y - Y_OFFSET, tallestRect.width, tallestRect.height);

      //cout << "Cropped: " << cropRect.x << ":" << cropRect.y << " -- " << cropRect.width << ":" << cropRect.height << endl;
      Mat cropped(characterImg, cropRect);
      cvtColor(cropped, cropped, CV_BGR2GRAY);

      Rect destinationRect(xPos + (CHAR_HORIZ_OFFSET - TILE_WIDTH), yPos + (CHAR_VERT_OFFSET - TILE_HEIGHT + (TILE_HEIGHT - tallestRect.height)), tallestRect.width, tallestRect.height);

      //cout << "1" << endl;

      cropped.copyTo(bigTif(destinationRect));

      int x1 = destinationRect.x - CHAR_PADDING_HORIZONTAL;
      int y1 = (vertical_resolution - destinationRect.y - destinationRect.height) - CHAR_PADDING_VERTICAL;
      int x2 = (destinationRect.x + destinationRect.width) + CHAR_PADDING_HORIZONTAL;
      int y2 = (vertical_resolution - destinationRect.y) + CHAR_PADDING_VERTICAL;
      //0 70 5602 85 5636 0
      boxFileOut << charcode << " " << x1 << " " << y1 << " ";
      boxFileOut << x2 << " " << y2 ;
      boxFileOut << " 0" << endl;

      //rectangle(characterImg, tallestRect, Scalar(0, 255, 0));
      //imshow("characterImg", cropped);

      waitKey(2);
    }
  }

  imwrite("combined.tif", bigTif);
  ofstream boxFile("combined.box", std::ios::out);
  boxFile << boxFileOut.str();

}
<|endoftext|>


<commit_before>// Copyright  2010-2013 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

#include "Stdafx.h"
#include "CookieVisitor.h"

namespace CefSharp
{
    bool CookieVisitor::Visit(const CefCookie& cefCookie, int count, int total, bool& deleteCookie)
    {
        Cookie^ cookie = gcnew Cookie();
        cookie->Name = toClr(cefCookie.name);
        cookie->Value = toClr(cefCookie.value);
        cookie->Domain = toClr(cefCookie.domain);
        cookie->Path = toClr(cefCookie.path);
        cookie->Secure = cefCookie.secure;
        cookie->HttpOnly = cefCookie.httponly;

        try
        {
            cookie->Expires = DateTime(cefCookie.expires.year,
                cefCookie.expires.month, cefCookie.expires.day_of_month);
        }
        catch (Exception^ ex)
        {

        }

        return _visitor->Visit(cookie, count, total, deleteCookie);
    }
}<commit_msg>Updated to work w/ changes in StringUtils.<commit_after>// Copyright  2010-2013 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

#include "Stdafx.h"
#include "CookieVisitor.h"

namespace CefSharp
{
    bool CookieVisitor::Visit(const CefCookie& cefCookie, int count, int total, bool& deleteCookie)
    {
        Cookie^ cookie = gcnew Cookie();
        cookie->Name = StringUtils::ToClr(cefCookie.name);
        cookie->Value = StringUtils::ToClr(cefCookie.value);
        cookie->Domain = StringUtils::ToClr(cefCookie.domain);
        cookie->Path = StringUtils::ToClr(cefCookie.path);
        cookie->Secure = cefCookie.secure;
        cookie->HttpOnly = cefCookie.httponly;

        try
        {
            cookie->Expires = DateTime(cefCookie.expires.year,
                cefCookie.expires.month, cefCookie.expires.day_of_month);
        }
        catch (Exception^)
        {
            // TODO: Why should we just ignore exceptions here...?
        }

        return _visitor->Visit(cookie, count, total, deleteCookie);
    }
}<|endoftext|>


<commit_before>/*
 * paged_grid.cpp
 *
 *  Created on: 06.05.2010
 *      Author: gmueller
 */

#include "arguments.hpp"

#include "gadget/Grid.hpp"
#include "gadget/Index3.hpp"
#include "gadget/SmoothParticle.hpp"
#include "gadget/GadgetFile.hpp"
#include "gadget/Vector3.hpp"

#include <ctime>
#include <limits>
#include <algorithm>
#include <omp.h>
#include <sstream>
#include <fstream>

void updateRho(std::vector<SmoothParticle> &sph) {
	const size_t s = sph.size();
#pragma omp parallel for
	for (size_t i = 0; i < s; i++) {
		sph[i].updateRho(sph);
	}
}

int sph(Arguments &arguments) {

	int size = arguments.getInt("-size", 240000);
	std::cout << "Size:           " << size << " kpc" << std::endl;

	Vector3f offset;
	offset.x = arguments.getFloat("-ox", 0);
	offset.y = arguments.getFloat("-oy", 0);
	offset.z = arguments.getFloat("-oz", 0);
	std::cout << "Offset:         " << offset << " kpc" << std::endl;

	float h = arguments.getFloat("-h", 0.7);
	std::cout << "h:              " << h << std::endl;

	size_t fileSizeKpc = arguments.getInt("-fileSize", 20000);
	std::cout << "FileSize:       " << fileSizeKpc << " kpc " << std::endl;

	size_t marginKpc = arguments.getInt("-margin", 1000);
	std::cout << "Margin:         " << marginKpc << " kpc " << std::endl;

	std::string prefix = arguments.getString("-prefix", "sph");
	std::cout << "Prefix:         " << prefix << std::endl;

	bool verbose = arguments.hasFlag("-v");

	size_t bins = size / fileSizeKpc;
	Grid<std::vector<SmoothParticle> > grid(bins, size);

	std::vector<std::string> files;
	arguments.getVector("-f", files);
	for (size_t iArg = 0; iArg < files.size(); iArg++) {
		std::cout << "Open " << files[iArg] << " (" << (iArg + 1) << "/"
				<< files.size() << ")" << std::endl;

		GadgetFile file;
		file.open(files[iArg]);
		if (file.good() == false) {
			std::cerr << "Failed to open file " << files[iArg] << std::endl;
			return 1;
		}

		file.readHeader();
		int pn = file.getHeader().particleNumberList[0];
		std::cout << "  Number of SmoothParticles: " << pn << std::endl;

		std::cout << "  Read POS block" << std::endl;
		std::vector<float> pos;
		if (file.readFloatBlock("POS ", pos) == false) {
			std::cerr << "Failed to read POS block" << std::endl;
			return 1;
		}

		std::cout << "  Read BFLD block" << std::endl;
		std::vector<float> bfld;
		if (file.readFloatBlock("BFLD", bfld) == false) {
			std::cerr << "Failed to read BFLD block" << std::endl;
			return 1;
		}

		std::cout << "  Read HSML block" << std::endl;
		std::vector<float> hsml;
		if (file.readFloatBlock("HSML", hsml) == false) {
			std::cerr << "Failed to read HSML block" << std::endl;
			return 1;
		}

		std::cout << "  Read RHO block" << std::endl;
		std::vector<float> rho;
		if (file.readFloatBlock("RHO ", rho) == false) {
			std::cerr << "Failed to read RHO block" << std::endl;
			return 1;
		}

		for (int iP = 0; iP < pn; iP++) {
			SmoothParticle particle;
			particle.smoothingLength = hsml[iP] / h;
			particle.position.x = (pos[iP * 3] - size / 2) / h + size / 2;
			particle.position.y = (pos[iP * 3 + 1] - size / 2) / h + size / 2;
			particle.position.z = (pos[iP * 3 + 2] - size / 2) / h + size / 2;

			particle.bfield.x = bfld[iP * 3];
			particle.bfield.y = bfld[iP * 3 + 1];
			particle.bfield.z = bfld[iP * 3 + 2];

			particle.mass = rho[iP];

			Vector3f l = particle.position
					- Vector3f(particle.smoothingLength + marginKpc) - offset;
			l.clamp(0.0, size);

			Vector3f u = particle.position
					+ Vector3f(particle.smoothingLength + marginKpc) - offset;
			u.clamp(0.0, size);

			Index3 lower, upper;
			lower.x = (uint32_t) std::floor(l.x / fileSizeKpc);
			lower.y = (uint32_t) std::floor(l.y / fileSizeKpc);
			lower.z = (uint32_t) std::floor(l.z / fileSizeKpc);

			upper.x = (uint32_t) std::ceil(u.x / fileSizeKpc);
			upper.y = (uint32_t) std::ceil(u.y / fileSizeKpc);
			upper.z = (uint32_t) std::ceil(u.z / fileSizeKpc);

			if (verbose && (iP % 100000 == 0)) {
				std::cout << "position:         " << particle.position
						<< std::endl;
				std::cout << "magnetic field:   " << particle.bfield
						<< std::endl;
				std::cout << "mass:             " << particle.mass << std::endl;
				std::cout << "smoothing length: " << particle.smoothingLength
						<< std::endl;
				std::cout << "lower:            " << lower << std::endl;
				std::cout << "upper:            " << upper << std::endl;
			}

			for (size_t x = lower.x; x < upper.x; x++)
				for (size_t y = lower.y; y < upper.y; y++)
					for (size_t z = lower.z; z < upper.z; z++)
						grid.get(x, y, z).push_back(particle);
		}
	}

	std::cout << "Write output" << std::endl;

	for (size_t x = 0; x < bins; x++) {
		if (verbose) {
			std::cout << "x = " << x << std::endl;
		}

		for (size_t y = 0; y < bins; y++)
			for (size_t z = 0; z < bins; z++) {
				std::stringstream sstr;
				sstr << prefix << "-" << x << "-" << y << "-" << z << ".raw";
				std::ofstream out(sstr.str().c_str(), std::ofstream::binary);
				updateRho(grid.get(x, y, z));
				uint32_t s = grid.get(x, y, z).size();
				if (verbose)
					std::cout << s << std::endl;
				out.write((const char *) &s, sizeof(uint32_t));
				out.write((const char *) &grid.get(x, y, z)[0],
						sizeof(SmoothParticle) * s);
			}

	}

	return 0;
}

<commit_msg>add veryverbose -vv flag<commit_after>/*
 * paged_grid.cpp
 *
 *  Created on: 06.05.2010
 *      Author: gmueller
 */

#include "arguments.hpp"

#include "gadget/Grid.hpp"
#include "gadget/Index3.hpp"
#include "gadget/SmoothParticle.hpp"
#include "gadget/GadgetFile.hpp"
#include "gadget/Vector3.hpp"

#include <ctime>
#include <limits>
#include <algorithm>
#include <omp.h>
#include <sstream>
#include <fstream>

void updateRho(std::vector<SmoothParticle> &sph) {
	const size_t s = sph.size();
#pragma omp parallel for
	for (size_t i = 0; i < s; i++) {
		sph[i].updateRho(sph);
	}
}

int sph(Arguments &arguments) {

	int size = arguments.getInt("-size", 240000);
	std::cout << "Size:           " << size << " kpc" << std::endl;

	Vector3f offset;
	offset.x = arguments.getFloat("-ox", 0);
	offset.y = arguments.getFloat("-oy", 0);
	offset.z = arguments.getFloat("-oz", 0);
	std::cout << "Offset:         " << offset << " kpc" << std::endl;

	float h = arguments.getFloat("-h", 0.7);
	std::cout << "h:              " << h << std::endl;

	size_t fileSizeKpc = arguments.getInt("-fileSize", 20000);
	std::cout << "FileSize:       " << fileSizeKpc << " kpc " << std::endl;

	size_t marginKpc = arguments.getInt("-margin", 1000);
	std::cout << "Margin:         " << marginKpc << " kpc " << std::endl;

	std::string prefix = arguments.getString("-prefix", "sph");
	std::cout << "Prefix:         " << prefix << std::endl;

	bool verbose = arguments.hasFlag("-v");
	bool veryverbose = arguments.hasFlag("-vv");
	if (veryverbose)
		verbose = true;

	size_t bins = size / fileSizeKpc;
	Grid<std::vector<SmoothParticle> > grid(bins, size);

	std::vector<std::string> files;
	arguments.getVector("-f", files);
	for (size_t iArg = 0; iArg < files.size(); iArg++) {
		std::cout << "Open " << files[iArg] << " (" << (iArg + 1) << "/"
				<< files.size() << ")" << std::endl;

		GadgetFile file;
		file.open(files[iArg]);
		if (file.good() == false) {
			std::cerr << "Failed to open file " << files[iArg] << std::endl;
			return 1;
		}

		file.readHeader();
		int pn = file.getHeader().particleNumberList[0];
		std::cout << "  Number of SmoothParticles: " << pn << std::endl;

		std::cout << "  Read POS block" << std::endl;
		std::vector<float> pos;
		if (file.readFloatBlock("POS ", pos) == false) {
			std::cerr << "Failed to read POS block" << std::endl;
			return 1;
		}

		std::cout << "  Read BFLD block" << std::endl;
		std::vector<float> bfld;
		if (file.readFloatBlock("BFLD", bfld) == false) {
			std::cerr << "Failed to read BFLD block" << std::endl;
			return 1;
		}

		std::cout << "  Read HSML block" << std::endl;
		std::vector<float> hsml;
		if (file.readFloatBlock("HSML", hsml) == false) {
			std::cerr << "Failed to read HSML block" << std::endl;
			return 1;
		}

		std::cout << "  Read RHO block" << std::endl;
		std::vector<float> rho;
		if (file.readFloatBlock("RHO ", rho) == false) {
			std::cerr << "Failed to read RHO block" << std::endl;
			return 1;
		}

		for (int iP = 0; iP < pn; iP++) {
			SmoothParticle particle;
			particle.smoothingLength = hsml[iP] / h;
			particle.position.x = (pos[iP * 3] - size / 2) / h + size / 2;
			particle.position.y = (pos[iP * 3 + 1] - size / 2) / h + size / 2;
			particle.position.z = (pos[iP * 3 + 2] - size / 2) / h + size / 2;

			particle.bfield.x = bfld[iP * 3];
			particle.bfield.y = bfld[iP * 3 + 1];
			particle.bfield.z = bfld[iP * 3 + 2];

			particle.mass = rho[iP];

			Vector3f relativePosition = particle.position - offset;
			Vector3f radius = Vector3f(particle.smoothingLength + marginKpc);
			Vector3f l = relativePosition - radius;
			l.clamp(0.0, size);

			Vector3f u = relativePosition + radius;
			u.clamp(0.0, size);

			Index3 lower, upper;
			lower.x = (uint32_t) std::floor(l.x / fileSizeKpc);
			lower.y = (uint32_t) std::floor(l.y / fileSizeKpc);
			lower.z = (uint32_t) std::floor(l.z / fileSizeKpc);

			upper.x = (uint32_t) std::ceil(u.x / fileSizeKpc);
			upper.y = (uint32_t) std::ceil(u.y / fileSizeKpc);
			upper.z = (uint32_t) std::ceil(u.z / fileSizeKpc);

			if ((verbose && (iP % 100000 == 0)) || veryverbose) {
				std::cout << "position:         " << particle.position
						<< std::endl;
				std::cout << "magnetic field:   " << particle.bfield
						<< std::endl;
				std::cout << "mass:             " << particle.mass << std::endl;
				std::cout << "smoothing length: " << particle.smoothingLength
						<< std::endl;
				std::cout << "lower:            " << lower << std::endl;
				std::cout << "upper:            " << upper << std::endl;
			}

			for (size_t x = lower.x; x < upper.x; x++)
				for (size_t y = lower.y; y < upper.y; y++)
					for (size_t z = lower.z; z < upper.z; z++)
						grid.get(x, y, z).push_back(particle);
		}
	}

	std::cout << "Write output" << std::endl;

	for (size_t x = 0; x < bins; x++) {
		if (verbose) {
			std::cout << "x = " << x << std::endl;
		}

		for (size_t y = 0; y < bins; y++)
			for (size_t z = 0; z < bins; z++) {
				std::stringstream sstr;
				sstr << prefix << "-" << x << "-" << y << "-" << z << ".raw";
				std::ofstream out(sstr.str().c_str(), std::ofstream::binary);
				updateRho(grid.get(x, y, z));
				uint32_t s = grid.get(x, y, z).size();
				if (verbose)
					std::cout << s << std::endl;
				out.write((const char *) &s, sizeof(uint32_t));
				out.write((const char *) &grid.get(x, y, z)[0],
						sizeof(SmoothParticle) * s);
			}

	}

	return 0;
}

<|endoftext|>


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

#include "dmlab2d/lib/env_lua_api/env_lua_api.h"

#include <cstdint>
#include <filesystem>
#include <istream>
#include <string>
#include <utility>

#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "dmlab2d/lib/env_lua_api/properties.h"
#include "dmlab2d/lib/lua/bind.h"
#include "dmlab2d/lib/lua/call.h"
#include "dmlab2d/lib/lua/lua.h"
#include "dmlab2d/lib/lua/n_results_or.h"
#include "dmlab2d/lib/lua/push.h"
#include "dmlab2d/lib/lua/push_script.h"
#include "dmlab2d/lib/lua/read.h"
#include "dmlab2d/lib/lua/stack_resetter.h"
#include "dmlab2d/lib/lua/vm.h"
#include "dmlab2d/lib/system/image/lua_image.h"
#include "dmlab2d/lib/system/random/lua/random.h"
#include "dmlab2d/lib/system/tensor/lua/tensor.h"
#include "dmlab2d/lib/util/default_read_only_file_system.h"
#include "dmlab2d/lib/util/file_reader_types.h"
#include "third_party/rl_api/env_c_api.h"

namespace deepmind::lab2d {

constexpr char kGameScriptPath[] =
    "/org_deepmind_lab2d/dmlab2d/lib/game_scripts";
constexpr char kLevelDirectory[] = "levels";
constexpr char kScriptFromSetting[] = "<script from setting>";

EnvLuaApi::EnvLuaApi(std::string executable_runfiles)
    : lua_vm_(lua::CreateVm()),
      executable_runfiles_(std::move(executable_runfiles)),
      file_system_(executable_runfiles_, util::DefaultReadOnlyFileSystem()),
      mixer_seed_(0) {}

int EnvLuaApi::AddSetting(absl::string_view key, absl::string_view value) {
  if (key == "levelName") {
    SetLevelName(std::string(value));
    return 0;
  }
  if (key == "mixerSeed") {
    std::uint32_t mixer_seed;
    if (absl::SimpleAtoi(value, &mixer_seed)) {
      SetMixerSeed(mixer_seed);
      return 0;
    } else {
      SetErrorMessage(absl::StrCat("Invalid settings 'mixerSeed' : ", value));
      return 1;
    }
  }
  if (key == "levelDirectory") {
    SetLevelDirectory(std::string(value));
    return 0;
  }
  settings_.emplace(key, value);
  return 0;
}

void EnvLuaApi::SetLevelName(absl::string_view level_name) {
  if (!level_name.empty() && level_name.front() == '=') {
    level_script_content_ = level_name.substr(1);
  }
  if (auto sep = level_name.find_last_of(':'); sep != absl::string_view::npos) {
    level_name_ = level_name.substr(0, sep);
    sub_level_name_ = level_name.substr(sep + 1);
  } else {
    level_name_ = level_name;
    sub_level_name_.clear();
  }
}

void EnvLuaApi::SetLevelDirectory(std::string level_directory) {
  level_directory_ = std::move(level_directory);
}

std::string EnvLuaApi::GetLevelDirectory() {
  if (!level_directory_.empty()) {
    if (level_directory_[0] == '/') {
      return level_directory_;
    } else {
      return absl::StrCat(ExecutableRunfiles(), "/", level_directory_);
    }
  }
  return absl::StrCat(ExecutableRunfiles(), kGameScriptPath, "/",
                      kLevelDirectory);
}

lua::NResultsOr EnvLuaApi::PushLevelScriptAndName() {
  lua_State* L = lua_vm_.get();
  if (!level_script_content_.empty()) {
    if (!level_directory_.empty()) {
      lua_vm_.AddPathToSearchers(level_directory_);
    }
    if (auto result =
            lua::PushScript(L, level_script_content_, kScriptFromSetting);
        !result.ok()) {
      return result;
    }
    lua::Push(L, kGameScriptPath);
    return 2;
  }
  if (absl::EndsWith(level_name_, ".lua")) {
    if (auto pos = level_name_.find_last_of('/'); pos != std::string::npos) {
      lua_vm_.AddPathToSearchers(level_name_.substr(0, pos));
    }
    if (!level_directory_.empty()) {
      lua_vm_.AddPathToSearchers(level_directory_);
    }
    if (auto result = lua::PushScriptFile(L, level_name_); !result.ok()) {
      return result;
    }
    lua::Push(L, level_name_);
    return 2;
  }
  if (level_name_.empty()) {
    return "Missing level script! Must set setting 'levelName'!";
  }

  auto level_directory = GetLevelDirectory();
  auto level_path = absl::StrCat(level_directory, "/", level_name_, ".lua");
  if (std::ifstream f(level_path.c_str()); f.good()) {
    auto last_sep = level_path.find_last_of('/');
    auto level_root = level_path.substr(0, last_sep);
    if (level_root != level_directory) {
      lua_vm_.AddPathToSearchers(level_root);
    }
  } else {
    auto level_root = absl::StrCat(level_directory, "/", level_name_);
    level_path = absl::StrCat(level_root, "/init.lua");
    lua_vm_.AddPathToSearchers(level_root);
  }
  lua_vm_.AddPathToSearchers(level_directory);
  lua_vm_.AddPathToSearchers(ExecutableRunfiles());

  if (auto result = lua::PushScriptFile(L, level_path); !result.ok()) {
    return result;
  }
  lua::Push(L, level_path);
  return 2;
}

int EnvLuaApi::Init() {
  lua_State* L = lua_vm_.get();
  lua::StackResetter stack_resetter(L);
  tensor::LuaTensorRegister(L);
  LuaRandom::Register(L);
  if (StoreError(PushLevelScriptAndName())) {
    return 1;
  }

  lua_vm_.AddPathToSearchers(
      absl::StrCat(ExecutableRunfiles(), kGameScriptPath));

  void* readonly_fs = const_cast<DeepMindReadOnlyFileSystem*>(
      GetFileSystem().ReadOnlyFileSystem());
  lua_vm_.AddCModuleToSearchers("system.image", LuaImageRequire, {readonly_fs});
  lua_vm_.AddCModuleToSearchers("system.tensor", tensor::LuaTensorConstructors,
                                {readonly_fs});

  lua_vm_.AddCModuleToSearchers("system.events", &lua::Bind<Events::Module>,
                                {MutableEvents()});
  lua_vm_.AddCModuleToSearchers(
      "system.random", &lua::Bind<LuaRandom::Require>,
      {UserPrbg(),
       reinterpret_cast<void*>(static_cast<std::uintptr_t>(mixer_seed_))});

  lua_vm_.AddCModuleToSearchers("system.properties",
                                &lua::Bind<Properties::Module>);

  if (auto result = lua::Call(L, 1); StoreError(result)) {
    return 1;
  } else if (result.n_results() != 1) {
    error_message_ = "Lua script function must return a table.";
    return 1;
  }

  if (lua_isfunction(L, -1)) {
    lua::Push(L, sub_level_name_);
    if (auto result = lua::Call(L, 1); StoreError(result)) {
      return 1;
    } else if (result.n_results() != 1) {
      error_message_ = "Lua script must return only a table or function.";
      return 1;
    }
  }

  if (!IsFound(lua::Read(L, -1, &script_table_ref_))) {
    error_message_ = absl::StrCat(
        "Lua script must return a table or function, Actually returned : '",
        lua::ToString(L, -1), "'");
    return 1;
  }

  lua_settop(L, 0);  // ApiInit expects an empty Lua stack.

  int error_value = 0;
  if (StoreError(ApiInit(&error_value)) ||
      StoreError(MutableObservations()->BindApi(script_table_ref_)) ||
      StoreError(MutableActions()->BindApi(script_table_ref_)) ||
      StoreError(MutableProperties()->BindApi(script_table_ref_)) ||
      StoreError(MutableEpisode()->BindApi(script_table_ref_))) {
    return error_value != 0 ? error_value : 1;
  }
  return 0;
}

int EnvLuaApi::MakeRandomSeed() {
  return std::uniform_int_distribution<int>(
      1, std::numeric_limits<int>::max())(*EnginePrbg());
}

int EnvLuaApi::Start(int episode, int seed) {
  MutableEvents()->Clear();
  EnginePrbg()->seed(static_cast<std::uint64_t>(seed) ^
                     (static_cast<std::uint64_t>(mixer_seed_) << 32));
  return StoreError(MutableEpisode()->Start(episode, MakeRandomSeed())) ? 1 : 0;
}

lua::NResultsOr EnvLuaApi::ApiInit(int* error_value) {
  lua_State* L = lua_vm_.get();
  lua::StackResetter stack_resetter(L);
  script_table_ref_.PushMemberFunction("init");
  if (lua_isnil(L, -2)) {
    return 0;
  }
  lua::Push(L, settings_);
  auto result = lua::Call(L, 2);
  if (!result.ok()) {
    return result;
  }

  bool correct_args =
      result.n_results() == 0 || (result.n_results() == 1 && lua_isnil(L, 1)) ||
      (result.n_results() <= 2 && IsFound(lua::Read(L, 1, error_value)));
  if (*error_value != 0) {
    if (result.n_results() == 2) {
      return lua::ToString(L, 2);
    } else {
      return "[init] - Script returned non zero.";
    }
  }
  if (!correct_args) {
    return "[init] - Must return none, nil, or integer and message";
  }
  return 0;
}

EnvCApi_EnvironmentStatus EnvLuaApi::Advance(int number_of_steps,
                                             double* reward) {
  if (number_of_steps != 1) {
    SetErrorMessage("DeepMind Lab2d does not support frame skip.");
    return EnvCApi_EnvironmentStatus_Error;
  }
  MutableEvents()->Clear();
  EnvCApi_EnvironmentStatus status;
  if (StoreError(MutableEpisode()->Advance(&status, reward))) {
    return EnvCApi_EnvironmentStatus_Error;
  }
  return status;
}

}  // namespace deepmind::lab2d
<commit_msg>[lib/env_lua_api] Remove unused inclusion of <filesystem><commit_after>// Copyright (C) 2016-2019 The DMLab2D Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

#include "dmlab2d/lib/env_lua_api/env_lua_api.h"

#include <cstdint>
#include <istream>
#include <string>
#include <utility>

#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "dmlab2d/lib/env_lua_api/properties.h"
#include "dmlab2d/lib/lua/bind.h"
#include "dmlab2d/lib/lua/call.h"
#include "dmlab2d/lib/lua/lua.h"
#include "dmlab2d/lib/lua/n_results_or.h"
#include "dmlab2d/lib/lua/push.h"
#include "dmlab2d/lib/lua/push_script.h"
#include "dmlab2d/lib/lua/read.h"
#include "dmlab2d/lib/lua/stack_resetter.h"
#include "dmlab2d/lib/lua/vm.h"
#include "dmlab2d/lib/system/image/lua_image.h"
#include "dmlab2d/lib/system/random/lua/random.h"
#include "dmlab2d/lib/system/tensor/lua/tensor.h"
#include "dmlab2d/lib/util/default_read_only_file_system.h"
#include "dmlab2d/lib/util/file_reader_types.h"
#include "third_party/rl_api/env_c_api.h"

namespace deepmind::lab2d {

constexpr char kGameScriptPath[] =
    "/org_deepmind_lab2d/dmlab2d/lib/game_scripts";
constexpr char kLevelDirectory[] = "levels";
constexpr char kScriptFromSetting[] = "<script from setting>";

EnvLuaApi::EnvLuaApi(std::string executable_runfiles)
    : lua_vm_(lua::CreateVm()),
      executable_runfiles_(std::move(executable_runfiles)),
      file_system_(executable_runfiles_, util::DefaultReadOnlyFileSystem()),
      mixer_seed_(0) {}

int EnvLuaApi::AddSetting(absl::string_view key, absl::string_view value) {
  if (key == "levelName") {
    SetLevelName(std::string(value));
    return 0;
  }
  if (key == "mixerSeed") {
    std::uint32_t mixer_seed;
    if (absl::SimpleAtoi(value, &mixer_seed)) {
      SetMixerSeed(mixer_seed);
      return 0;
    } else {
      SetErrorMessage(absl::StrCat("Invalid settings 'mixerSeed' : ", value));
      return 1;
    }
  }
  if (key == "levelDirectory") {
    SetLevelDirectory(std::string(value));
    return 0;
  }
  settings_.emplace(key, value);
  return 0;
}

void EnvLuaApi::SetLevelName(absl::string_view level_name) {
  if (!level_name.empty() && level_name.front() == '=') {
    level_script_content_ = level_name.substr(1);
  }
  if (auto sep = level_name.find_last_of(':'); sep != absl::string_view::npos) {
    level_name_ = level_name.substr(0, sep);
    sub_level_name_ = level_name.substr(sep + 1);
  } else {
    level_name_ = level_name;
    sub_level_name_.clear();
  }
}

void EnvLuaApi::SetLevelDirectory(std::string level_directory) {
  level_directory_ = std::move(level_directory);
}

std::string EnvLuaApi::GetLevelDirectory() {
  if (!level_directory_.empty()) {
    if (level_directory_[0] == '/') {
      return level_directory_;
    } else {
      return absl::StrCat(ExecutableRunfiles(), "/", level_directory_);
    }
  }
  return absl::StrCat(ExecutableRunfiles(), kGameScriptPath, "/",
                      kLevelDirectory);
}

lua::NResultsOr EnvLuaApi::PushLevelScriptAndName() {
  lua_State* L = lua_vm_.get();
  if (!level_script_content_.empty()) {
    if (!level_directory_.empty()) {
      lua_vm_.AddPathToSearchers(level_directory_);
    }
    if (auto result =
            lua::PushScript(L, level_script_content_, kScriptFromSetting);
        !result.ok()) {
      return result;
    }
    lua::Push(L, kGameScriptPath);
    return 2;
  }
  if (absl::EndsWith(level_name_, ".lua")) {
    if (auto pos = level_name_.find_last_of('/'); pos != std::string::npos) {
      lua_vm_.AddPathToSearchers(level_name_.substr(0, pos));
    }
    if (!level_directory_.empty()) {
      lua_vm_.AddPathToSearchers(level_directory_);
    }
    if (auto result = lua::PushScriptFile(L, level_name_); !result.ok()) {
      return result;
    }
    lua::Push(L, level_name_);
    return 2;
  }
  if (level_name_.empty()) {
    return "Missing level script! Must set setting 'levelName'!";
  }

  auto level_directory = GetLevelDirectory();
  auto level_path = absl::StrCat(level_directory, "/", level_name_, ".lua");
  if (std::ifstream f(level_path.c_str()); f.good()) {
    auto last_sep = level_path.find_last_of('/');
    auto level_root = level_path.substr(0, last_sep);
    if (level_root != level_directory) {
      lua_vm_.AddPathToSearchers(level_root);
    }
  } else {
    auto level_root = absl::StrCat(level_directory, "/", level_name_);
    level_path = absl::StrCat(level_root, "/init.lua");
    lua_vm_.AddPathToSearchers(level_root);
  }
  lua_vm_.AddPathToSearchers(level_directory);
  lua_vm_.AddPathToSearchers(ExecutableRunfiles());

  if (auto result = lua::PushScriptFile(L, level_path); !result.ok()) {
    return result;
  }
  lua::Push(L, level_path);
  return 2;
}

int EnvLuaApi::Init() {
  lua_State* L = lua_vm_.get();
  lua::StackResetter stack_resetter(L);
  tensor::LuaTensorRegister(L);
  LuaRandom::Register(L);
  if (StoreError(PushLevelScriptAndName())) {
    return 1;
  }

  lua_vm_.AddPathToSearchers(
      absl::StrCat(ExecutableRunfiles(), kGameScriptPath));

  void* readonly_fs = const_cast<DeepMindReadOnlyFileSystem*>(
      GetFileSystem().ReadOnlyFileSystem());
  lua_vm_.AddCModuleToSearchers("system.image", LuaImageRequire, {readonly_fs});
  lua_vm_.AddCModuleToSearchers("system.tensor", tensor::LuaTensorConstructors,
                                {readonly_fs});

  lua_vm_.AddCModuleToSearchers("system.events", &lua::Bind<Events::Module>,
                                {MutableEvents()});
  lua_vm_.AddCModuleToSearchers(
      "system.random", &lua::Bind<LuaRandom::Require>,
      {UserPrbg(),
       reinterpret_cast<void*>(static_cast<std::uintptr_t>(mixer_seed_))});

  lua_vm_.AddCModuleToSearchers("system.properties",
                                &lua::Bind<Properties::Module>);

  if (auto result = lua::Call(L, 1); StoreError(result)) {
    return 1;
  } else if (result.n_results() != 1) {
    error_message_ = "Lua script function must return a table.";
    return 1;
  }

  if (lua_isfunction(L, -1)) {
    lua::Push(L, sub_level_name_);
    if (auto result = lua::Call(L, 1); StoreError(result)) {
      return 1;
    } else if (result.n_results() != 1) {
      error_message_ = "Lua script must return only a table or function.";
      return 1;
    }
  }

  if (!IsFound(lua::Read(L, -1, &script_table_ref_))) {
    error_message_ = absl::StrCat(
        "Lua script must return a table or function, Actually returned : '",
        lua::ToString(L, -1), "'");
    return 1;
  }

  lua_settop(L, 0);  // ApiInit expects an empty Lua stack.

  int error_value = 0;
  if (StoreError(ApiInit(&error_value)) ||
      StoreError(MutableObservations()->BindApi(script_table_ref_)) ||
      StoreError(MutableActions()->BindApi(script_table_ref_)) ||
      StoreError(MutableProperties()->BindApi(script_table_ref_)) ||
      StoreError(MutableEpisode()->BindApi(script_table_ref_))) {
    return error_value != 0 ? error_value : 1;
  }
  return 0;
}

int EnvLuaApi::MakeRandomSeed() {
  return std::uniform_int_distribution<int>(
      1, std::numeric_limits<int>::max())(*EnginePrbg());
}

int EnvLuaApi::Start(int episode, int seed) {
  MutableEvents()->Clear();
  EnginePrbg()->seed(static_cast<std::uint64_t>(seed) ^
                     (static_cast<std::uint64_t>(mixer_seed_) << 32));
  return StoreError(MutableEpisode()->Start(episode, MakeRandomSeed())) ? 1 : 0;
}

lua::NResultsOr EnvLuaApi::ApiInit(int* error_value) {
  lua_State* L = lua_vm_.get();
  lua::StackResetter stack_resetter(L);
  script_table_ref_.PushMemberFunction("init");
  if (lua_isnil(L, -2)) {
    return 0;
  }
  lua::Push(L, settings_);
  auto result = lua::Call(L, 2);
  if (!result.ok()) {
    return result;
  }

  bool correct_args =
      result.n_results() == 0 || (result.n_results() == 1 && lua_isnil(L, 1)) ||
      (result.n_results() <= 2 && IsFound(lua::Read(L, 1, error_value)));
  if (*error_value != 0) {
    if (result.n_results() == 2) {
      return lua::ToString(L, 2);
    } else {
      return "[init] - Script returned non zero.";
    }
  }
  if (!correct_args) {
    return "[init] - Must return none, nil, or integer and message";
  }
  return 0;
}

EnvCApi_EnvironmentStatus EnvLuaApi::Advance(int number_of_steps,
                                             double* reward) {
  if (number_of_steps != 1) {
    SetErrorMessage("DeepMind Lab2d does not support frame skip.");
    return EnvCApi_EnvironmentStatus_Error;
  }
  MutableEvents()->Clear();
  EnvCApi_EnvironmentStatus status;
  if (StoreError(MutableEpisode()->Advance(&status, reward))) {
    return EnvCApi_EnvironmentStatus_Error;
  }
  return status;
}

}  // namespace deepmind::lab2d
<|endoftext|>


<commit_before>//
// Realm C++ coding standard - by example
//

// Lines should never exceed 118 characters --------------------------------------------------------------------------

// Macro names use uppercase and have "REALM_" as prefix. Non-macro
// names never use all uppercase.

#define REALM_MY_MACRO 1

// A function name uses lowercase and its parts are separated by
// underscores.

my_type my_func()
{
    // Put the opening brace of a function body in the next line below
    // the function prototype. This also applies to class member
    // functions.

    // Put all other opening braces on the same line as the syntax
    // element to which the brace is subordinate.

    // Use 4 spaces per indentation level (no tabs please).

    if (...) {
        // ...
    }
    else {
        // ...
    }

    // Always put subordinate statements on a new line (to ease
    // debugging).

    if (...)
        return ...;

    // No space between type and '*' or '&'
    int* foo1 = ...;
    int& foo2 = ...;

    // 'const' goes before the type
    const int foo3 = ...;

    // ... but not when 'const' operates on a pointer type
    const int* foo3 = ...; // 'const' operates on 'int' not 'int*'
    int* const foo4 = ...; // 'const' operates on 'int*'
    int* const* const foo5 = ...;
}

void my_func_2()
{
    // This indentation and brace placement style agrees with K&R
    // style except for the 'extra' indentation of 'cases' in a switch
    // statement.

    switch (...) {
        case type_Foo: {
            // ...
            break;
        }
        case type_FooBar: {
            // ...
            break;
        }
    }

    try {
        // ...
    }
    catch (...) {
        // ...
    }
}

// A name space name uses lowercase and its parts are separated by
// underscores.

namespace my_namespace {

// No indentation inside name spaces.

// A Class name uses CamelCase with uppercase initial.

template<class T>
class MyClass: public Base {
public:
    MyClass(...):
        Base(...),
        m_bar(7),
        ...
    {
        // ...
    }

    // Public member variables do not have a 'm_' prefix.
    int baz;

private:
    // Static member variables have prefix 's_'.
    static int s_foo;

    // Regular member variables have prefix 'm_'.
    int m_bar;
};

} // namespace my_namespace

// Names of values of an enumeration are composed of two parts
// separated by an underscore. The first part is a common lowercase
// prefix. The second part identifies the value and uses CamelCase
// with uppercase initial.

enum mode {
    mode_Foo,
    mode_FooBar
};

// Order of class members (roughly):

class MyClass2 {
public:
    // Types

    // Static variables
    // Regular variables

    // Static functions
    // Regular functions

protected:
    // Same as 'public'

private:
    // Same as 'public'

    // Friends
};

// Use literals when possible

char* str = nullptr; // don't use 0, NULL
bool enable_feature = true;
bool is_last = false;

// Use of 'auto' keyword:
//
// 'auto' should *not* be used for trivial cases where the type declaration
// is short, non-templated, and non-derived (type_t, int64_t, std::string,
// etc.

// About FIXMEs:
//
// A FIXME conveys information about a known issue or shortcoming. It
// may also include information on how to fix the problem, and on
// possible conflicts with anticipated future features.
//
// A FIXME is often added in the following situations:
//
// - While working on, or studying a particular part of the code you
//   uncover an issue or a shortcoming. Additionally, you may have
//   gained an understanding of how to fix it.
//
// - While implementing a new feature, you are forced to cut a corner,
//   but you have some good ideas about how to continue later, and/or
//   you may have knowledge about a certain planned feature that would
//   require a more complete solution.
//
// A FIXME is generally not about a bug or an error, and is should
// generally not be considered a task either. Is is simply a memo to
// oneself or to some other developer who is going to work on the code
// at some later point in time.
//
// A FIXME should never be deleted unless by somebody who understands
// the mening of it and knows that the problem is fixed, or has
// otherwise diappeard.
<commit_msg>Move public member variable before public methods.<commit_after>//
// Realm C++ coding standard - by example
//

// Lines should never exceed 118 characters --------------------------------------------------------------------------

// Macro names use uppercase and have "REALM_" as prefix. Non-macro
// names never use all uppercase.

#define REALM_MY_MACRO 1

// A function name uses lowercase and its parts are separated by
// underscores.

my_type my_func()
{
    // Put the opening brace of a function body in the next line below
    // the function prototype. This also applies to class member
    // functions.

    // Put all other opening braces on the same line as the syntax
    // element to which the brace is subordinate.

    // Use 4 spaces per indentation level (no tabs please).

    if (...) {
        // ...
    }
    else {
        // ...
    }

    // Always put subordinate statements on a new line (to ease
    // debugging).

    if (...)
        return ...;

    // No space between type and '*' or '&'
    int* foo1 = ...;
    int& foo2 = ...;

    // 'const' goes before the type
    const int foo3 = ...;

    // ... but not when 'const' operates on a pointer type
    const int* foo3 = ...; // 'const' operates on 'int' not 'int*'
    int* const foo4 = ...; // 'const' operates on 'int*'
    int* const* const foo5 = ...;
}

void my_func_2()
{
    // This indentation and brace placement style agrees with K&R
    // style except for the 'extra' indentation of 'cases' in a switch
    // statement.

    switch (...) {
        case type_Foo: {
            // ...
            break;
        }
        case type_FooBar: {
            // ...
            break;
        }
    }

    try {
        // ...
    }
    catch (...) {
        // ...
    }
}

// A name space name uses lowercase and its parts are separated by
// underscores.

namespace my_namespace {

// No indentation inside name spaces.

// A Class name uses CamelCase with uppercase initial.

template<class T>
class MyClass: public Base {
public:

    // Public member variables do not have a 'm_' prefix.
    int baz;

    MyClass(...):
        Base(...),
        m_bar(7),
        ...
    {
        // ...
    }

private:
    // Static member variables have prefix 's_'.
    static int s_foo;

    // Regular member variables have prefix 'm_'.
    int m_bar;
};

} // namespace my_namespace

// Names of values of an enumeration are composed of two parts
// separated by an underscore. The first part is a common lowercase
// prefix. The second part identifies the value and uses CamelCase
// with uppercase initial.

enum mode {
    mode_Foo,
    mode_FooBar
};

// Order of class members (roughly):

class MyClass2 {
public:
    // Types

    // Static variables
    // Regular variables

    // Static functions
    // Regular functions

protected:
    // Same as 'public'

private:
    // Same as 'public'

    // Friends
};

// Use literals when possible

char* str = nullptr; // don't use 0, NULL
bool enable_feature = true;
bool is_last = false;

// Use of 'auto' keyword:
//
// 'auto' should *not* be used for trivial cases where the type declaration
// is short, non-templated, and non-derived (type_t, int64_t, std::string,
// etc.

// About FIXMEs:
//
// A FIXME conveys information about a known issue or shortcoming. It
// may also include information on how to fix the problem, and on
// possible conflicts with anticipated future features.
//
// A FIXME is often added in the following situations:
//
// - While working on, or studying a particular part of the code you
//   uncover an issue or a shortcoming. Additionally, you may have
//   gained an understanding of how to fix it.
//
// - While implementing a new feature, you are forced to cut a corner,
//   but you have some good ideas about how to continue later, and/or
//   you may have knowledge about a certain planned feature that would
//   require a more complete solution.
//
// A FIXME is generally not about a bug or an error, and is should
// generally not be considered a task either. Is is simply a memo to
// oneself or to some other developer who is going to work on the code
// at some later point in time.
//
// A FIXME should never be deleted unless by somebody who understands
// the mening of it and knows that the problem is fixed, or has
// otherwise diappeard.
<|endoftext|>