text:
/**********************************
*    = Header File Inclusion =
**********************************/

#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <Wt/WApplication>
#include <Wt/WContainerWidget>
#include <Wt/WDialog>
#include <Wt/WGridLayout>
#include <Wt/WLengthValidator>
#include <Wt/WLineEdit>
#include <Wt/WMessageBox>
#include <Wt/WPushButton>
#include <Wt/WText>
#include <Wt/WTextArea>
#include <Wt/WTextEdit>
#include <Wt/WTree>
#include <Wt/WTreeNode>
#include <Wt/WWidget>
#include "cmspages.hpp"
#include "base.hpp"
#include "cmspagespageeditor.hpp"
#include "cmspagestreenode.hpp"
#include "crypto.hpp"
#include "db.hpp"
#include "dbtables.hpp"

/**********************************
*    = PreProcessor Directives =
**********************************/

/**********************************
*    = Importing NameSpaces =
**********************************/

using namespace std;
using namespace boost;
using namespace Wt;
using namespace cppdb;
using namespace SamsungDForumIr;

/**********************************
*    = Constants =
**********************************/

/**********************************
*    = Enumerations =
**********************************/

/**********************************
*    = Properties =
**********************************/

/**********************************
*    = Fields =
**********************************/

/**********************************
*    = Constructos =
**********************************/

CmsPages::CmsPages(CgiRoot *cgi) : BaseWidget(cgi)
{
    this->clear();
    this->addWidget(Layout());
}

/**********************************
*    = Destructor =
**********************************/

/**********************************
*    = Public Methods =
**********************************/

/**********************************
*    = Event Handlers =
**********************************/

void CmsPages::OnCmsPagesTreeNodeEditContents(CmsPagesTreeNode *sender)
{
    m_currentNode = sender;

    result r = m_db->Sql() << "SELECT body FROM [" + m_dbTables->Table("PAGES")
                              + "] WHERE fullpath=?;" << sender->GetFullPath() << row;
    if (!r.empty()) {
        string body;
        r >> body;

        m_dvPagesTree->hide();
        m_dvPageEditor->show();
        m_contentsTextEdit->setText(WString::fromUTF8(Crypto::Decrypt(body)));
        m_contentsTextEdit->setFocus();

        sender->OnEditContentsCompleted();
    }
}

void CmsPages::OnCmsPagesTreeNodeInsert(CmsPagesTreeNode *sender)
{
    m_currentNode = sender;

    m_dlg = new WDialog(m_lang->GetString("ROOT_CMSPAGES_INSERT_DLG_TITLE"));
    m_dlg->setModal(true);
    m_dlg->contents()->addWidget(GetInsertNodeForm());
    m_dlg->rejectWhenEscapePressed();
    m_dlg->show();
    m_insertNodeTitleEdit->setFocus();

    // HACK for 3.2.3-rc1
    if (m_dlg->height().value() < 115)
        m_dlg->resize(WLength::Auto, 115);
}

void CmsPages::OnCmsPagesTreeNodeEdit(CmsPagesTreeNode *sender)
{
    m_currentNode = sender;

    m_dlg = new WDialog(m_lang->GetString("ROOT_CMSPAGES_EDIT_DLG_TITLE"));
    m_dlg->setModal(true);
    m_dlg->contents()->addWidget(GetEditNodeForm(m_currentNode));
    m_editNodeTitleEdit->setText(m_currentNode->label()->text());
    m_dlg->rejectWhenEscapePressed();
    m_dlg->show();
    m_editNodeTitleEdit->setFocus();

    // HACK for 3.2.3-rc1
    if (m_dlg->height().value() < 115)
        m_dlg->resize(WLength::Auto, 115);
}

void CmsPages::OnCmsPagesTreeNodeErase(CmsPagesTreeNode *sender)
{
    m_currentNode = sender;

    wstring question((wformat(m_lang->GetString("ROOT_CMSPAGES_ERASE_MSG_QUESTION"))
                  % m_currentNode->label()->text().value()).str());

    m_msg = new WMessageBox(m_lang->GetString("ROOT_CMSPAGES_ERASE_MSG_TITLE"),
                            question, Warning, NoButton);

    m_msg->addButton(m_lang->GetString("ROOT_CMSPAGES_ERASE_MSG_OK_BUTTON"), Ok);
    m_msg->addButton(m_lang->GetString("ROOT_CMSPAGES_ERASE_MSG_CANCEL_BUTTON"), Cancel);

    m_msg->buttonClicked().connect(this, &CmsPages::OnEraseNodeOK);

    m_msg->show();
}

void CmsPages::OnCmsPagesTreeNodeMoveUp(CmsPagesTreeNode *sender)
{
    CmsPagesTreeNode *parent = reinterpret_cast<CmsPagesTreeNode *>(sender->parentNode());

    int index = -1;
    bool found = false;
    const vector<CmsPagesTreeNode *> &childs = reinterpret_cast<const vector<CmsPagesTreeNode *> &>(parent->childNodes());
    for (vector<CmsPagesTreeNode *>::const_iterator it = childs.begin(); it != childs.end(); ++it) {
        ++index;
        if ((*it) == sender) {
            found = true;
            break;
        }
    }

    if (found && index > 0) {
        CmsPagesTreeNode *prevNode = reinterpret_cast<CmsPagesTreeNode *>(parent->childNodes()[index - 1]);

        parent->removeChildNode(sender);
        parent->insertChildNode(index - 1, sender);

        m_db->Update(m_dbTables->Table("PAGES"), "fullpath", sender->GetFullPath(),
                     "zindex=?", 1,
                     lexical_cast<string>(index - 1).c_str());
        m_db->Update(m_dbTables->Table("PAGES"), "fullpath", prevNode->GetFullPath(),
                     "zindex=?", 1,
                     lexical_cast<string>(index).c_str());

        sender->OnMoveUpCompleted();
    }
}

void CmsPages::OnCmsPagesTreeNodeMoveDown(CmsPagesTreeNode *sender)
{
    CmsPagesTreeNode *parent = reinterpret_cast<CmsPagesTreeNode *>(sender->parentNode());

    int index = -1;
    bool found = false;
    const vector<CmsPagesTreeNode *> &childs = reinterpret_cast<const vector<CmsPagesTreeNode *> &>(parent->childNodes());
    for (vector<CmsPagesTreeNode *>::const_iterator it = childs.begin(); it != childs.end(); ++it) {
        ++index;
        if ((*it) == sender) {
            found = true;
            break;
        }
    }

    if (found && (size_t)index < parent->childNodes().size() - 1) {
        CmsPagesTreeNode *nextNode = reinterpret_cast<CmsPagesTreeNode *>(parent->childNodes()[index + 1]);

        parent->removeChildNode(sender);
        parent->insertChildNode(index + 1, sender);

        m_db->Update(m_dbTables->Table("PAGES"), "fullpath", sender->GetFullPath(),
                     "zindex=?", 1,
                     lexical_cast<string>(index + 1).c_str());
        m_db->Update(m_dbTables->Table("PAGES"), "fullpath", nextNode->GetFullPath(),
                     "zindex=?", 1,
                     lexical_cast<string>(index).c_str());

        sender->OnMoveDownCompleted();
    }
}

void CmsPages::OnAddNodeOK()
{
    if (!Validate(m_insertNodeTitleEdit))
        return;

    WString label(algorithm::trim_copy(m_insertNodeTitleEdit->text().toUTF8()));

    if (label == "") {
        m_msg = new WMessageBox(m_lang->GetString("ROOT_CMSPAGES_INSERT_INVALID_TITLE"),
                                m_lang->GetString("ROOT_CMSPAGES_INSERT_INVALID_ERROR"),
                                Warning, NoButton);
        m_msg->addButton(m_lang->GetString("ROOT_CMSPAGES_INSERT_INVALID_ERR_OK_BUTTON"), Ok);
        m_msg->buttonClicked().connect(this, &CmsPages::OnAddNodeInvalidOK);
        m_msg->show();
        return;
    }

    bool duplicate = false;
    const vector<WTreeNode *> &childs = m_currentNode->childNodes();
    for (vector<WTreeNode *>::const_iterator it = childs.begin(); it != childs.end(); ++it) {
        if ((*it)->label()->text() == label) {
            duplicate = true;
            break;
        }
    }

    if (duplicate) {
        m_msg = new WMessageBox(m_lang->GetString("ROOT_CMSPAGES_INSERT_DUPLICATE_TITLE"),
                                m_lang->GetString("ROOT_CMSPAGES_INSERT_DUPLICATE_ERROR"),
                                Warning, NoButton);
        m_msg->addButton(m_lang->GetString("ROOT_CMSPAGES_INSERT_DUPLICATE_ERR_OK_BUTTON"), Ok);
        m_msg->buttonClicked().connect(this, &CmsPages::OnAddNodeDuplicateOK);
        m_msg->show();
        return;
    }

    CmsPagesTreeNode *node = new CmsPagesTreeNode(m_insertNodeTitleEdit->text(), CmsPagesTreeNode::EType_Target, m_lang);
    SetNodeContextEvents(node);
    m_currentNode->addChildNode(node);
    m_currentNode->expand();
    m_currentNode->OnInsertCompleted();

    m_db->Insert(m_dbTables->Table("PAGES"), "pg, parent, fullpath, zindex, body, viewcount, url",
                 7, algorithm::trim_copy(m_insertNodeTitleEdit->text().toUTF8()).c_str(),
                 m_currentNode->GetFullPath().c_str(),
                 node->GetFullPath().c_str(),
                 lexical_cast<string>(m_currentNode->childNodes().size() - 1).c_str(),
                 Crypto::Encrypt("").c_str(),
                 "0",
                 Crypto::GenHash(m_currentNode->GetFullPath()).c_str());

    delete m_insertNodeTitleEdit;
    delete m_dlg;
    m_dlg = NULL;
}

void CmsPages::OnAddNodeInvalidOK()
{
    delete m_msg;
    m_msg = NULL;
    m_insertNodeTitleEdit->setFocus();
}

void CmsPages::OnAddNodeDuplicateOK()
{
    delete m_msg;
    m_msg = NULL;
    m_insertNodeTitleEdit->setFocus();
}

void CmsPages::OnAddNodeReturn()
{
    delete m_dlg;
    m_dlg = NULL;
}

void CmsPages::OnEditNodeOK()
{
    if (!Validate(m_editNodeTitleEdit))
        return;

    WString label(algorithm::trim_copy(m_editNodeTitleEdit->text().toUTF8()));

    if (label == "") {
        m_msg = new WMessageBox(m_lang->GetString("ROOT_CMSPAGES_INSERT_INVALID_TITLE"),
                                m_lang->GetString("ROOT_CMSPAGES_INSERT_INVALID_ERROR"),
                                Warning, NoButton);
        m_msg->addButton(m_lang->GetString("ROOT_CMSPAGES_INSERT_INVALID_ERR_OK_BUTTON"), Ok);
        m_msg->buttonClicked().connect(this, &CmsPages::OnEditNodeInvalidOK);
        m_msg->show();
        return;
    }

    bool duplicate = false;
    const vector<WTreeNode *> &childs = m_currentNode->parentNode()->childNodes();
    for (vector<WTreeNode *>::const_iterator it = childs.begin(); it != childs.end(); ++it) {
        if ((*it) != m_currentNode && (*it)->label()->text() == label) {
            duplicate = true;
            break;
        }
    }

    if (duplicate) {
        m_msg = new WMessageBox(m_lang->GetString("ROOT_CMSPAGES_INSERT_DUPLICATE_TITLE"),
                                m_lang->GetString("ROOT_CMSPAGES_INSERT_DUPLICATE_ERROR"),
                                Warning, NoButton);
        m_msg->addButton(m_lang->GetString("ROOT_CMSPAGES_INSERT_DUPLICATE_ERR_OK_BUTTON"), Ok);
        m_msg->buttonClicked().connect(this, &CmsPages::OnEditNodeDuplicateOK);
        m_msg->show();
        return;
    }

    string oldFullPath(m_currentNode->GetFullPath());

    m_currentNode->label()->setText(m_editNodeTitleEdit->text());
    m_currentNode->OnEditCompleted();

    string fullPath(m_currentNode->GetFullPath());

    m_db->Sql() << (boost::format("UPDATE [%1%] SET "
                                  "parent = REPLACE(parent, ?, ?), "
                                  "fullpath = REPLACE(fullpath, ?, ?) "
                                  "WHERE parent LIKE ?;") % m_dbTables->Table("PAGES")).str()
                << oldFullPath << fullPath
                << oldFullPath << fullPath
                << oldFullPath + "%" << exec;
    m_db->Update(m_dbTables->Table("PAGES"), "fullpath", oldFullPath,
                 "pg=?, fullpath=?, url=?", 3,
                 algorithm::trim_copy(m_editNodeTitleEdit->text().toUTF8()).c_str(),
                 fullPath.c_str(),
                 Crypto::GenHash(fullPath).c_str());

    delete m_editNodeTitleEdit;
    delete m_dlg;
    m_dlg = NULL;
}

void CmsPages::OnEditNodeInvalidOK()
{
    delete m_msg;
    m_msg = NULL;
    m_editNodeTitleEdit->setFocus();
}

void CmsPages::OnEditNodeDuplicateOK()
{
    delete m_msg;
    m_msg = NULL;
    m_editNodeTitleEdit->setFocus();
}

void CmsPages::OnEditNodeReturn()
{
    delete m_dlg;
    m_dlg = NULL;
}

void CmsPages::OnEraseNodeOK(StandardButton result)
{
    if (result == Ok) {
        string fullPath(m_currentNode->GetFullPath());

        m_currentNode->parentNode()->removeChildNode(m_currentNode);
        m_currentNode->OnEraseCompleted();
        delete m_currentNode;
        m_currentNode = NULL;

        m_db->Sql() << (boost::format("DELETE FROM [%1%] "
                                      "WHERE (parent LIKE ? OR fullpath=?);") % m_dbTables->Table("PAGES")).str()
                    << fullPath + "%" << fullPath << exec;
    }

    delete m_msg;
    m_msg = NULL;
}

void CmsPages::OnCloseButtonOK()
{
    m_contentsTextEdit->setText("");
    m_dvPageEditor->hide();
    m_dvPagesTree->show();
}

void CmsPages::OnSaveButtonOK()
{
    m_db->Update(m_dbTables->Table("PAGES"), "fullpath", m_currentNode->GetFullPath(),
                 "body=?", 1,
                 Crypto::Encrypt(m_contentsTextEdit->text().toUTF8()).c_str());

    OnCloseButtonOK();
}

/**********************************
*    = Protected Methods =
**********************************/

/**********************************
*    = Private Methods =
**********************************/

void CmsPages::ExpandAllChildNodes(CmsPagesTreeNode *node)
{
    const vector<WTreeNode *> &childs = node->childNodes();
    for (vector<WTreeNode *>::const_iterator it = childs.begin(); it != childs.end(); ++it) {
        WTreeNode *child = (*it);
        child->expand();
        ExpandAllChildNodes(reinterpret_cast<CmsPagesTreeNode *>(child));
    }
}

void CmsPages::GetChildNodes(CmsPagesTreeNode *node)
{
    result r = m_db->Sql() << "SELECT pg FROM ["
                              + m_dbTables->Table("PAGES")
                              + "] WHERE parent=? "
                              "ORDER BY parent ASC, zindex ASC;" << node->GetFullPath();
    while (r.next()) {
        string pg;
        r >> pg;

        CmsPagesTreeNode *child = new CmsPagesTreeNode(WString::fromUTF8(pg),
                                                       CmsPagesTreeNode::EType_Target, m_lang);
        // 1: Add it to the tree.  2: Get its childs
        node->addChildNode(child);
        GetChildNodes(child);
    }

    // 3: Set context menu  4. Expand it
    SetNodeContextEvents(node);
    node->expand();
}

void CmsPages::SetNodeContextEvents(CmsPagesTreeNode *node)
{
    CmsPagesTreeNode::EType nodeType = node->GetNodeType();

    WSignalMapper<CmsPagesTreeNode *> *nodeSignalMapper;

    if (nodeType == CmsPagesTreeNode::EType_Root || nodeType == CmsPagesTreeNode::EType_Target) {
        nodeSignalMapper = new WSignalMapper<CmsPagesTreeNode *>(this);
        nodeSignalMapper->mapped().connect(this, &CmsPages::OnCmsPagesTreeNodeEditContents);
        nodeSignalMapper->mapConnect(node->EditContentsHandler(), node);
    }

    nodeSignalMapper = new WSignalMapper<CmsPagesTreeNode *>(this);
    nodeSignalMapper->mapped().connect(this, &CmsPages::OnCmsPagesTreeNodeInsert);
    nodeSignalMapper->mapConnect(node->InsertHandler(), node);

    if (nodeType == CmsPagesTreeNode::EType_Group || nodeType == CmsPagesTreeNode::EType_Target) {
        nodeSignalMapper = new WSignalMapper<CmsPagesTreeNode *>(this);
        nodeSignalMapper->mapped().connect(this, &CmsPages::OnCmsPagesTreeNodeEdit);
        nodeSignalMapper->mapConnect(node->EditHandler(), node);

        nodeSignalMapper = new WSignalMapper<CmsPagesTreeNode *>(this);
        nodeSignalMapper->mapped().connect(this, &CmsPages::OnCmsPagesTreeNodeErase);
        nodeSignalMapper->mapConnect(node->EraseHandler(), node);

        nodeSignalMapper = new WSignalMapper<CmsPagesTreeNode *>(this);
        nodeSignalMapper->mapped().connect(this, &CmsPages::OnCmsPagesTreeNodeMoveUp);
        nodeSignalMapper->mapConnect(node->MoveUpHandler(), node);

        nodeSignalMapper = new WSignalMapper<CmsPagesTreeNode *>(this);
        nodeSignalMapper->mapped().connect(this, &CmsPages::OnCmsPagesTreeNodeMoveDown);
        nodeSignalMapper->mapConnect(node->MoveDownHandler(), node);
    }
}

WWidget *CmsPages::GetInsertNodeForm()
{
    Div *root = new Div("InsertNodeForm");

    Div *dvForm = new Div(root);
    dvForm->setStyleClass("form");
    WGridLayout *dvFormLayout = new WGridLayout();

    dvFormLayout->addWidget(new WText(m_lang->GetString("ROOT_CMSPAGES_INSERT_DLG_PAGE_TITLE_TEXT")),
                                      0, 0, AlignLeft | AlignMiddle);

    m_insertNodeTitleEdit = new WLineEdit();

    WLengthValidator *titleValidator = new WLengthValidator(1, 255);
    titleValidator->setMandatory(true);
    m_insertNodeTitleEdit->setValidator(titleValidator);

    dvFormLayout->addWidget(m_insertNodeTitleEdit, 0, 1);

    dvFormLayout->setColumnStretch(0, 100);
    dvFormLayout->setColumnStretch(1, 200);
    dvFormLayout->setVerticalSpacing(11);
    dvForm->setLayout(dvFormLayout);

    Div *dvButtons = new Div(root);
    WPushButton *addButton = new WPushButton(m_lang->GetString("ROOT_CMSPAGES_INSERT_DLG_ADD_BUTTON"), dvButtons);
    WPushButton *returnButton = new WPushButton(m_lang->GetString("ROOT_CMSPAGES_INSERT_DLG_RETURN_BUTTON"), dvButtons);

    addButton->setStyleClass("dialogButton");
    returnButton->setStyleClass("dialogButton");

    m_insertNodeTitleEdit->enterPressed().connect(this, &CmsPages::OnAddNodeOK);
    addButton->clicked().connect(this, &CmsPages::OnAddNodeOK);
    returnButton->clicked().connect(this, &CmsPages::OnAddNodeReturn);

    return root;
}

WWidget *CmsPages::GetEditNodeForm(CmsPagesTreeNode *node)
{
    Div *root = new Div("InsertNodeForm");

    Div *dvForm = new Div(root);
    dvForm->setStyleClass("form");
    WGridLayout *dvFormLayout = new WGridLayout();

    dvFormLayout->addWidget(new WText(m_lang->GetString("ROOT_CMSPAGES_EDIT_DLG_PAGE_TITLE_TEXT")),
                                      0, 0, AlignLeft | AlignMiddle);

    m_editNodeTitleEdit = new WLineEdit();

    WLengthValidator *titleValidator = new WLengthValidator(1, 255);
    titleValidator->setMandatory(true);
    m_editNodeTitleEdit->setValidator(titleValidator);

    dvFormLayout->addWidget(m_editNodeTitleEdit, 0, 1);

    dvFormLayout->setColumnStretch(0, 100);
    dvFormLayout->setColumnStretch(1, 200);
    dvFormLayout->setVerticalSpacing(11);
    dvForm->setLayout(dvFormLayout);

    Div *dvButtons = new Div(root);
    WPushButton *saveButton = new WPushButton(m_lang->GetString("ROOT_CMSPAGES_EDIT_DLG_SAVE_BUTTON"), dvButtons);
    WPushButton *returnButton = new WPushButton(m_lang->GetString("ROOT_CMSPAGES_EDIT_DLG_RETURN_BUTTON"), dvButtons);

    saveButton->setStyleClass("dialogButton");
    returnButton->setStyleClass("dialogButton");

    m_editNodeTitleEdit->enterPressed().connect(this, &CmsPages::OnEditNodeOK);
    saveButton->clicked().connect(this, &CmsPages::OnEditNodeOK);
    returnButton->clicked().connect(this, &CmsPages::OnEditNodeReturn);

    return root;
}

/**********************************
*    = Base Class Overrides =
**********************************/

WWidget *CmsPages::Layout()
{
    Div *root = new Div("CmsPages");

    m_dvPagesTree = new Div(root, "dvPagesTree");
    m_dvPageEditor = new Div(root, "dvPageEditor");
    Div *dvPageEditorButtons = new Div(m_dvPageEditor, "dvPageEditorButtons");

    WTree *tree = new WTree(m_dvPagesTree);
    tree->setSelectionMode(SingleSelection);

    CmsPagesTreeNode *rootNode = new CmsPagesTreeNode(Base::DB_PAGE_ID_HOME,
                                                      CmsPagesTreeNode::EType_Root, m_lang);
    tree->setTreeRoot(rootNode);
    rootNode->label()->setTextFormat(PlainText);
    rootNode->setImagePack("resources/");
    rootNode->setLoadPolicy(WTreeNode::PreLoading);
    GetChildNodes(rootNode);
    ExpandAllChildNodes(rootNode);

    m_saveButton = new WPushButton(m_lang->GetString("ROOT_CMSPAGES_EDITOR_SAVE_BUTTON"), dvPageEditorButtons);
    m_closeButton = new WPushButton(m_lang->GetString("ROOT_CMSPAGES_EDITOR_CLOSE_BUTTON"), dvPageEditorButtons);
    m_saveButton->setStyleClass("editorButton");
    m_closeButton->setStyleClass("editorButton");

    m_contentsTextEdit = new WTextEdit("", m_dvPageEditor);

    // http://www.tinymce.com/wiki.php?title=Configuration
    m_contentsTextEdit->setConfigurationSetting("cleanup", false);
    m_contentsTextEdit->setConfigurationSetting("valid_elements", std::string("*[*]"));

    m_contentsTextEdit->setExtraPlugins("pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave");
    m_contentsTextEdit->setToolBar(0, "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect");
    m_contentsTextEdit->setToolBar(1, "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor");
    m_contentsTextEdit->setToolBar(2, "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen");
    m_contentsTextEdit->setToolBar(3, "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft");
    m_contentsTextEdit->resize(WLength::Auto, 550);

    m_advancedVideoTipTextArea = new WTextArea(L""
                "<!-- HTML5 Cross Browser Video Code -->"
                "\n"
                "<video controls=\"controls\" width=\"320\" height=\"240\">"
                "\n"
                "	<source src=\"***movie.webm***\" type=\"video/webm; codecs='vp8.0, vorbis'\" />"
                "\n"
                "	<source src=\"***movie.ogv***\" type=\"video/ogg; codecs='theora, vorbis'\" />"
                "\n"
                "	<source src=\"***movie.mp4***\" type=\"video/mp4; codecs='avc1.4D401E, mp4a.40.2'\" />"
                "\n"
                "</video>",
                m_dvPageEditor);
    m_advancedVideoTipTextArea->setStyleClass("tipsBox");
    m_advancedVideoTipTextArea->setReadOnly(true);

    m_dvPageEditor->hide();

    m_closeButton->clicked().connect(this, &CmsPages::OnCloseButtonOK);
    m_saveButton->clicked().connect(this, &CmsPages::OnSaveButtonOK);

    return root;
}

/**********************************
*    = Utility Methods =
**********************************/

/**********************************
*    = Debug Methods =
**********************************/

max_stars_repo_licenses: MIT Unlicense

max_issues_repo_licenses: MIT Unlicense

max_forks_repo_licenses: MIT Unlicense


text:
#include <chrono>
#include <fstream>
#include <iostream>
#include <regex>
#include <boost/regex.hpp>

void measure(const std::string& data, const std::string& pattern) {
  using clock = std::chrono::high_resolution_clock;
  const auto start = clock::now();

  const REGEX_NAMESPACE::regex re{pattern};
  unsigned count = 0;

  for (REGEX_NAMESPACE::sregex_token_iterator it{data.cbegin(), data.cend(), re}, end{}; it != end; ++it)
    count++;

  const auto end = clock::now();
  const double elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() * 1e-6;
  std::cout << elapsed << " - " << count << "\n";
}

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: benchmark <filename>\n";
    return 1;
  }

  std::ifstream file{argv[1]};
  if (!file) {
    std::cerr << "unable to open " << argv[1] << "\n";
    return 1;
  }

  const std::string data{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};

  // Email
  measure(data, "[\\w.+-]+@[\\w.-]+\\.[\\w.-]+");

  // URI
  measure(data, "[\\w]+:\\/\\/[^\\/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?");

  // IP
  measure(data, "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])");

  return 0;
}

ext: cpp

max_stars_repo_name: bstaletic/regex-benchmark

max_issues_repo_name: bstaletic/regex-benchmark

max_forks_repo_name: bstaletic/regex-benchmark


text:
/*
 * NotSingleValueConstraint.cpp
 * @brief NotSingleValueConstraint constraint
 * @date Mar 20, 2022
 * @author Yoonwoo Kim
 */

#include <gtsam/base/Testable.h>
#include <gtsam/discrete/DecisionTreeFactor.h>
#include <cpp/planning/NotSingleValueConstraint.h>

#include <boost/make_shared.hpp>
using namespace gtsam;
using namespace std;

namespace gtsam_planner {

/* ************************************************************************* */
void NotSingleValueConstraint::print(const string& s, const KeyFormatter& formatter) const {
  cout << s << "NotSingleValueConstraint on "
       << "j=" << formatter(keys_[0]) << " with value " << value_ << endl;
}

/* ************************************************************************* */
double NotSingleValueConstraint::operator()(const DiscreteValues& values) const {
  if (values.at(keys_[0]) != value_) return 1.0;
  return 0.0;
}

/* ************************************************************************* */
DecisionTreeFactor NotSingleValueConstraint::toDecisionTreeFactor() const {
  DiscreteKeys keys;
  keys += DiscreteKey(keys_[0], cardinality_);
  vector<double> table;
  for (size_t i1 = 0; i1 < cardinality_; i1++) {
    if (i1 == value_) table.push_back(0.0);
    else table.push_back(1.0);
  }
  DecisionTreeFactor converted(keys, table);
  return converted;
}

/* ************************************************************************* */
DecisionTreeFactor NotSingleValueConstraint::operator*(const DecisionTreeFactor& f) const {
  // TODO: can we do this more efficiently?
  return toDecisionTreeFactor() * f;
}

/* ************************************************************************* */
}  // namespace gtsam


text:
// Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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 <dlib/configfile.h>
#include <dlib/log.h>
#include <ddf/ddf.h>
#include <gameobject/gameobject.h>
#include <render/render.h>
#include <script/script.h>
#include <gameobject/script.h>
#include "gamesys.h"
#include <gamesys/tile_ddf.h>
#include <gamesys/physics_ddf.h>
#include "../gamesys_private.h"
#include "../resources/res_tilegrid.h"
#include "../components/comp_tilegrid.h"
#include "script_tilemap.h"

extern "C"
{
#include <lua/lauxlib.h>
#include <lua/lualib.h>
}

namespace dmGameSystem
{
    /*# Tilemap API documentation
     *
     * Functions and messages used to manipulate tile map components.
     *
     * @document
     * @name Tilemap
     * @namespace tilemap
     */

    /*# [type:hash] tile source
     *
     * The tile source used when rendering the tile map. The type of the property is hash.
     *
     * @name tile_source
     * @property
     *
     * @examples
     *
     * How to set tile source using a script property (see [ref:resource.tile_source])
     *
     * ```lua
     * go.property("my_tile_source", resource.tile_source("/tilesource.tilesource"))
     * function init(self)
     *   go.set("#tilemap", "tile_source", self.my_tile_source)
     * end
     * ```
     */

    /*# [type:hash] tile map material
     *
     * The material used when rendering the tile map. The type of the property is hash.
     *
     * @name material
     * @property
     *
     * @examples
     *
     * How to set material using a script property (see [ref:resource.material])
     *
     * ```lua
     * go.property("my_material", resource.material("/material.material"))
     * function init(self)
     *   go.set("#tilemap", "material", self.my_material)
     * end
     * ```
     */

    /** DEPRECATED! set a shader constant for a tile map
     * Sets a shader constant for a tile map component.
     * The constant must be defined in the material assigned to the tile map.
     * Setting a constant through this function will override the value set for that constant in the material.
     * The value will be overridden until tilemap.reset_constant is called.
     * Which tile map to set a constant for is identified by the URL.
     *
     * @name tilemap.set_constant
     * @param url [type:string|hash|url] the tile map that should have a constant set
     * @param constant [type:string|hash] name of the constant
     * @param value [type:vector4] value of the constant
     * @examples
     *
     * The following examples assumes that the tile map has id "tile map" and that the default-material in builtins is used, which defines the constant "tint".
     * If you assign a custom material to the tile map, you can set the constants defined there in the same manner.
     *
     * How to tint a tile map to red:
     *
     * ```lua
     * function init(self)
     *     tilemap.set_constant("#tilemap", "tint", vmath.vector4(1, 0, 0, 1))
     * end
     * ```
     */
    static int TileMap_SetConstant(lua_State* L)
    {
        int top = lua_gettop(L);

        dmGameObject::HInstance instance = CheckGoInstance(L);

        dmhash_t name_hash = dmScript::CheckHashOrString(L, 2);
        Vectormath::Aos::Vector4* value = dmScript::CheckVector4(L, 3);

        dmGameSystemDDF::SetConstantTileMap msg;
        msg.m_NameHash = name_hash;
        msg.m_Value = *value;

        dmMessage::URL receiver;
        dmMessage::URL sender;
        dmScript::ResolveURL(L, 1, &receiver, &sender);

        dmMessage::Post(&sender, &receiver, dmGameSystemDDF::SetConstantTileMap::m_DDFDescriptor->m_NameHash, (uintptr_t)instance, (uintptr_t)dmGameSystemDDF::SetConstantTileMap::m_DDFDescriptor, &msg, sizeof(msg), 0);
        assert(top == lua_gettop(L));
        return 0;
    }

    /** DEPRECATED! reset a shader constant for a tile map
     * Resets a shader constant for a tile map component.
     * The constant must be defined in the material assigned to the tile map.
     * Resetting a constant through this function implies that the value defined in the material will be used.
     * Which tile map to reset a constant for is identified by the URL.
     *
     * @name tilemap.reset_constant
     * @param url [type:string|hash|url] the tile map that should have a constant reset
     * @param constant [type:string|hash] name of the constant
     * @examples
     *
     * The following examples assumes that the tile map has id "tilemap" and that the default-material in builtins is used, which defines the constant "tint".
     * If you assign a custom material to the tile map, you can reset the constants defined there in the same manner.
     *
     * How to reset the tinting of a tile map:
     *
     * ```lua
     * function init(self)
     *     tilemap.reset_constant("#tilemap", "tint")
     * end
     * ```
     */
    static int TileMap_ResetConstant(lua_State* L)
    {
        int top = lua_gettop(L);

        dmGameObject::HInstance instance = CheckGoInstance(L);
        dmhash_t name_hash = dmScript::CheckHashOrString(L, 2);

        dmGameSystemDDF::ResetConstantTileMap msg;
        msg.m_NameHash = name_hash;

        dmMessage::URL receiver;
        dmMessage::URL sender;
        dmScript::ResolveURL(L, 1, &receiver, &sender);

        dmMessage::Post(&sender, &receiver, dmGameSystemDDF::ResetConstantTileMap::m_DDFDescriptor->m_NameHash, (uintptr_t)instance, (uintptr_t)dmGameSystemDDF::ResetConstantTileMap::m_DDFDescriptor, &msg, sizeof(msg), 0);
        assert(top == lua_gettop(L));
        return 0;
    }

    /*# set a tile in a tile map
     * Replace a tile in a tile map with a new tile.
     * The coordinates of the tiles are indexed so that the "first" tile just
     * above and to the right of origin has coordinates 1,1.
     * Tiles to the left of and below origin are indexed 0, -1, -2 and so forth.
     *
     * <pre>
     * +-------+-------+------+------+
     * |  0,3  |  1,3  | 2,3  | 3,3  |
     * +-------+-------+------+------+
     * |  0,2  |  1,2  | 2,2  | 3,2  |
     * +-------+-------+------+------+
     * |  0,1  |  1,1  | 2,1  | 3,1  |
     * +-------O-------+------+------+
     * |  0,0  |  1,0  | 2,0  | 3,0  |
     * +-------+-------+------+------+
     * </pre>
     *
     * The coordinates must be within the bounds of the tile map as it were created.
     * That is, it is not possible to extend the size of a tile map by setting tiles outside the edges.
     * To clear a tile, set the tile to number 0. Which tile map and layer to manipulate is identified by the URL and the layer name parameters.
     *
     * @name tilemap.set_tile
     * @param url [type:string|hash|url] the tile map
     * @param layer [type:string|hash] name of the layer for the tile
     * @param x [type:number] x-coordinate of the tile
     * @param y [type:number] y-coordinate of the tile
     * @param tile [type:number] index of new tile to set. 0 resets the cell
     * @param [h-flipped] [type:boolean] optional if the tile should be horizontally flipped
     * @param [v-flipped] [type:boolean] optional i the tile should be vertically flipped
     * @examples
     *
     * ```lua
     * -- Clear the tile under the player.
     * tilemap.set_tile("/level#tilemap", "foreground", self.player_x, self.player_y, 0)
     * ```
     */
    static int TileMap_SetTile(lua_State* L)
    {
        int top = lua_gettop(L);

        dmGameObject::HInstance sender_instance = CheckGoInstance(L);
        dmGameObject::HCollection collection = dmGameObject::GetCollection(sender_instance);

        uintptr_t user_data;
        dmMessage::URL receiver;
        dmGameObject::GetComponentUserDataFromLua(L, 1, collection, TILE_MAP_EXT, &user_data, &receiver, 0);
        TileGridComponent* component = (TileGridComponent*) user_data;

        dmhash_t layer_id = dmScript::CheckHashOrString(L, 2);

        uint32_t layer_index = GetLayerIndex(component, layer_id);
        if (layer_index == ~0u)
        {
            dmLogError("Could not find layer '%s'.", dmHashReverseSafe64(layer_id));
            lua_pushboolean(L, 0);
            assert(top + 1 == lua_gettop(L));
            return 1;
        }

        int x = luaL_checkinteger(L, 3) - 1;
        int y = luaL_checkinteger(L, 4) - 1;

        int lua_tile  = luaL_checkinteger(L, 5);

        /* Range check: tile indices that fall outside of the valid limits will crash the engine.
         *
         * Note that 0 resets the tile cell, so the valid range is [0...N]
         * where N is equal to the amount of tiles availabel in the tile source.
         */
        if (lua_tile < 0 || lua_tile > (int)GetTileCount(component))
        {
            return luaL_error(L, "tilemap.set_tile called with out-of-range tile index (%d)", lua_tile);
        }

        /*
         * NOTE AND BEWARE: Empty tile is encoded as 0xffffffff
         * That's why tile-index is subtracted by 1
         * See B2GRIDSHAPE_EMPTY_CELL in b2GridShape.h
         */
        uint32_t tile = lua_tile - 1;

        int min_x, min_y, grid_w, grid_h;
        GetTileGridBounds(component, &min_x, &min_y, &grid_w, &grid_h);

        int32_t cell_x, cell_y;
        GetTileGridCellCoord(component, x, y, cell_x, cell_y);

        if (cell_x < 0 || cell_x >= grid_w || cell_y < 0 || cell_y >= grid_h)
        {
            dmLogError("Could not set the tile since the supplied tile was out of range.");
            lua_pushboolean(L, 0);
            assert(top + 1 == lua_gettop(L));
            return 1;
        }

        bool flip_h = lua_toboolean(L, 6);
        bool flip_v = lua_toboolean(L, 7);
        SetTileGridTile(component, layer_index, cell_x, cell_y, tile, flip_h, flip_v);

        dmMessage::URL sender;
        if (dmScript::GetURL(L, &sender))
        {
            // Broadcast to any collision object components
            // TODO Filter broadcast to only collision objects
            dmPhysicsDDF::SetGridShapeHull set_hull_ddf;
            set_hull_ddf.m_Shape = layer_index;
            set_hull_ddf.m_Column = cell_x;
            set_hull_ddf.m_Row = cell_y;
            set_hull_ddf.m_Hull = tile;
            set_hull_ddf.m_FlipHorizontal = flip_h;
            set_hull_ddf.m_FlipVertical = flip_v;
            dmhash_t message_id = dmPhysicsDDF::SetGridShapeHull::m_DDFDescriptor->m_NameHash;
            uintptr_t descriptor = (uintptr_t)dmPhysicsDDF::SetGridShapeHull::m_DDFDescriptor;
            uint32_t data_size = sizeof(dmPhysicsDDF::SetGridShapeHull);
            receiver.m_Fragment = 0;
            dmMessage::Result result = dmMessage::Post(&sender, &receiver, message_id, 0, descriptor, &set_hull_ddf, data_size, 0);
            if (result != dmMessage::RESULT_OK)
            {
                dmLogError("Could not send %s to components, result: %d.", dmPhysicsDDF::SetGridShapeHull::m_DDFDescriptor->m_Name, result);
            }
        }
        else
        {
            return luaL_error(L, "tilemap.set_tile is not available from this script-type.");
        }

        lua_pushboolean(L, 1);
        assert(top + 1 == lua_gettop(L));
        return 1;
    }

    /*# get a tile from a tile map
     * Get the tile set at the specified position in the tilemap.
     * The position is identified by the tile index starting at origin
     * with index 1, 1. (see [ref:tilemap.set_tile()])
     * Which tile map and layer to query is identified by the URL and the
     * layer name parameters.
     *
     * @name tilemap.get_tile
     * @param url [type:string|hash|url] the tile map
     * @param layer [type:string|hash] name of the layer for the tile
     * @param x [type:number] x-coordinate of the tile
     * @param y [type:number] y-coordinate of the tile
     * @return tile [type:number] index of the tile
     * @examples
     *
     * ```lua
     * -- get the tile under the player.
     * local tileno = tilemap.get_tile("/level#tilemap", "foreground", self.player_x, self.player_y)
     * ```
     */
    static int TileMap_GetTile(lua_State* L)
    {
        int top = lua_gettop(L);

        dmGameObject::HInstance sender_instance = CheckGoInstance(L);
        dmGameObject::HCollection collection = dmGameObject::GetCollection(sender_instance);

        uintptr_t user_data;
        dmGameObject::GetComponentUserDataFromLua(L, 1, collection, TILE_MAP_EXT, &user_data, 0, 0);
        TileGridComponent* component = (TileGridComponent*) user_data;

        dmhash_t layer_id = dmScript::CheckHashOrString(L, 2);
        uint32_t layer_index = GetLayerIndex(component, layer_id);
        if (layer_index == ~0u)
        {
            dmLogError("Could not find layer '%s'.", dmHashReverseSafe64(layer_id));
            lua_pushnil(L);
            assert(top + 1 == lua_gettop(L));
            return 1;
        }

        int x = luaL_checkinteger(L, 3) - 1;
        int y = luaL_checkinteger(L, 4) - 1;

        int min_x, min_y, grid_w, grid_h;
        GetTileGridBounds(component, &min_x, &min_y, &grid_w, &grid_h);

        int32_t cell_x, cell_y;
        GetTileGridCellCoord(component, x, y, cell_x, cell_y);

        if (cell_x < 0 || cell_x >= grid_w || cell_y < 0 || cell_y >= grid_h)
        {
            dmLogError("Could not get the tile since the supplied tile was out of range.");
            lua_pushnil(L);
            assert(top + 1 == lua_gettop(L));
            return 1;
        }

        uint16_t cell = GetTileGridTile(component, layer_index, cell_x, cell_y);

        lua_pushinteger(L,  cell);
        assert(top + 1 == lua_gettop(L));
        return 1;
    }

    /*# get the bounds of a tile map
     * Get the bounds for a tile map. This function returns multiple values:
     * The lower left corner index x and y coordinates (1-indexed),
     * the tile map width and the tile map height.
     *
     * The resulting values take all tile map layers into account, meaning that
     * the bounds are calculated as if all layers were collapsed into one.
     *
     * @name tilemap.get_bounds
     * @param url [type:string|hash|url] the tile map
     * @return x [type:number] x coordinate of the bottom left corner
     * @return y [type:number] y coordinate of the bottom left corner
     * @return w [type:number] number of columns (width) in the tile map
     * @return h [type:number] number of rows (height) in the tile map
     * @examples
     *
     * ```lua
     * -- get the level bounds.
     * local x, y, w, h = tilemap.get_bounds("/level#tilemap")
     * ```
     */
    static int TileMap_GetBounds(lua_State* L)
    {
        int top = lua_gettop(L);

        dmGameObject::HInstance sender_instance = CheckGoInstance(L);
        dmGameObject::HCollection collection = dmGameObject::GetCollection(sender_instance);

        uintptr_t user_data;
        dmGameObject::GetComponentUserDataFromLua(L, 1, collection, TILE_MAP_EXT, &user_data, 0, 0);
        TileGridComponent* component = (TileGridComponent*) user_data;

        int x, y, w, h;
        GetTileGridBounds(component, &x, &y, &w, &h);

        lua_pushinteger(L, x + 1);
        lua_pushinteger(L, y + 1);
        lua_pushinteger(L, w);
        lua_pushinteger(L, h);

        assert(top + 4 == lua_gettop(L));
        return 4;
    }

    /*# set the visibility of a layer
     * Sets the visibility of the tilemap layer
     *
     * @name tilemap.set_visible
     * @param url [type:string|hash|url] the tile map
     * @param layer [type:string|hash] name of the layer for the tile
     * @param visible [type:boolean] should the layer be visible
     * @examples
     *
     * ```lua
     * -- Disable rendering of the layer
     * tilemap.set_visible("/level#tilemap", "foreground", false)
     * ```
     */
    static int TileMap_SetVisible(lua_State* L)
    {
        DM_LUA_STACK_CHECK(L, 0);

        dmGameObject::HInstance sender_instance = CheckGoInstance(L);
        dmGameObject::HCollection collection = dmGameObject::GetCollection(sender_instance);

        uintptr_t user_data;
        dmMessage::URL receiver;
        dmGameObject::GetComponentUserDataFromLua(L, 1, collection, TILE_MAP_EXT, &user_data, &receiver, 0);
        TileGridComponent* component = (TileGridComponent*) user_data;

        dmhash_t layer_id = dmScript::CheckHashOrString(L, 2);
        uint32_t layer_index = GetLayerIndex(component, layer_id);
        if (layer_index == ~0u)
        {
            return DM_LUA_ERROR("Could not find layer '%s'.", dmHashReverseSafe64(layer_id));
        }

        bool visible = lua_toboolean(L, 3);
        SetLayerVisible(component, layer_index, visible);

        dmMessage::URL sender;
        if (dmScript::GetURL(L, &sender))
        {
            // Broadcast to any collision object components under this game object
            // TODO Filter broadcast to only collision objects
            dmPhysicsDDF::EnableGridShapeLayer ddf;
            ddf.m_Shape = layer_index;
            ddf.m_Enable = visible;
            dmhash_t message_id = dmPhysicsDDF::EnableGridShapeLayer::m_DDFDescriptor->m_NameHash;
            uintptr_t descriptor = (uintptr_t)dmPhysicsDDF::EnableGridShapeLayer::m_DDFDescriptor;
            uint32_t data_size = sizeof(dmPhysicsDDF::EnableGridShapeLayer);
            receiver.m_Fragment = 0;
            dmMessage::Result result = dmMessage::Post(&sender, &receiver, message_id, 0, descriptor, &ddf, data_size, 0);
            if (result != dmMessage::RESULT_OK)
            {
                dmLogError("Could not send %s to components, result: %d.", dmPhysicsDDF::EnableGridShapeLayer::m_DDFDescriptor->m_Name, result);
            }
        }
        else
        {
            return luaL_error(L, "tilemap.set_tile is not available from this script-type.");
        }

        return 0;
    }

    static const luaL_reg TILEMAP_FUNCTIONS[] =
    {
        {"set_constant",    TileMap_SetConstant},
        {"reset_constant",  TileMap_ResetConstant},
        {"set_tile",        TileMap_SetTile},
        {"get_tile",        TileMap_GetTile},
        {"get_bounds",      TileMap_GetBounds},
        {"set_visible",     TileMap_SetVisible},
        {0, 0}
    };

    void ScriptTileMapRegister(const ScriptLibContext& context)
    {
        lua_State* L = context.m_LuaState;
        luaL_register(L, "tilemap", TILEMAP_FUNCTIONS);
        lua_pop(L, 1);
    }
}

max_stars_repo_name: hakoptak/defold

max_issues_repo_name: hakoptak/defold

max_forks_repo_name: hakoptak/defold


text:
#include <map>

#include "Common.h"
#include "XMLDataUtils.h"
#include "Elements/IElement.h"
#include "Elements/ElementsContainer.h"
#include "Problem.h"

#include "MaterialReader.h"
#include "NodeReader.h"
#include "ElementReader.h"
#include "Load.h"
#include "LoadReader.h"
#include <Eigen/Dense>

#include "IProblemTypeSpecific.h"
#include "Problem2DTypeSpecific.h"

struct ProblemImpl
{
	void GenerateGlobalKMatrix();
	void ApplyConstrints();
	void CreateLoadVector();

	template<typename Solver>
	void SolveSLI(int maxIterationCount, float expsilon);

	StrideDataArray					m_nodes;
	ElementsContainer				m_elements;
	MaterialsLibrary				m_matLib;
	IndexedStrideDataArray			m_nodalForceList;
	NodalConstraintList				m_nodalConstraintList;
	ProblemDescription				m_desc;

	Eigen::SparseMatrix<float> m_globalK;
	Eigen::VectorXf m_input;
	Eigen::VectorXf m_output;

	void ReadNodes(TiXmlHandle hRoot);
	void ReadMaterials(TiXmlHandle hRoot);
	void ReadElements(TiXmlHandle hRoot);
	void ReadNodalForces(TiXmlHandle hRoot);
	void ReadNodalConstraint(TiXmlHandle hRoot);

	IProblemTypeSpecific* m_typeSpecific;
};

void ProblemImpl::GenerateGlobalKMatrix()
{
	int elementsCount = m_elements.GetCount();

	std::vector<Eigen::Triplet<float> > triplets;
	for (int i = 0; i < elementsCount; ++i)
	{
		m_elements(i)->CalcK(m_nodes, m_matLib.begin()->second, triplets);
	}

	int problemDimension = m_typeSpecific->GetProblemDimension(m_nodes.GetCount());
	m_globalK = Eigen::SparseMatrix<float>(problemDimension, problemDimension);
	m_globalK.setFromTriplets(triplets.begin(), triplets.end());
}

void SetConstraints(Eigen::SparseMatrix<float>::InnerIterator& it, int index)
{
	if (it.row() == index || it.col() == index)
	{
		it.valueRef() = it.row() == it.col() ? 1.0f : 0.0f;
	}
}

void ProblemImpl::ApplyConstrints()
{
	std::vector<int> indicesToConstraint;

	for (NodalConstraintList::iterator itc = m_nodalConstraintList.begin(); itc != m_nodalConstraintList.end(); ++itc)
	{
		m_typeSpecific->GrabConstraintIndices(itc->node, itc->type, indicesToConstraint);
	}

	for (int k = 0; k < m_globalK.outerSize(); ++k)
	{
		for (Eigen::SparseMatrix<float>::InnerIterator it(m_globalK, k); it; ++it)
		{
			for (std::vector<int>::iterator idit = indicesToConstraint.begin(); idit != indicesToConstraint.end(); ++idit)
			{
				SetConstraints(it, *idit);
			}
		}
	}
}

void ProblemImpl::CreateLoadVector()
{
	m_input = Eigen::VectorXf(m_typeSpecific->GetProblemDimension(m_nodes.GetCount()));
	m_input.setZero();

	int dof = m_typeSpecific->GetDOFPerNode();

	for (int i = 0, l = m_nodalForceList.GetCount(); i < l; ++i)
	{
		for (int j = 0; j < dof; ++j)
		{
			m_input[dof * m_nodalForceList[i] + j] = m_nodalForceList(i, j);
		}
	}
}

template<>
void ProblemImpl::SolveSLI<Eigen::ConjugateGradient<Eigen::SparseMatrix<float> > >(int maxIterationCount, float expsilon)
{
	Eigen::ConjugateGradient<Eigen::SparseMatrix<float> > solver(m_globalK);
	solver.setMaxIterations(maxIterationCount);
	solver.setTolerance(expsilon);
	m_output = solver.solve(m_input);
}

template<typename Solver>
void ProblemImpl::SolveSLI(int maxIterationCount, float expsilon)
{
	Solver solver(m_globalK);
	m_output = solver.solve(m_input);
}

void Problem::OpenFromMemory(const std::string& memoryString)
{
	xmldata::TiXmlDocumentPtr hDoc(new TiXmlDocument());
	hDoc->Parse(memoryString.c_str(), 0, TIXML_ENCODING_UTF8);
	OpenDoc(hDoc.get());
}

void Problem::OpenFromFile(const std::string& filename)
{
	xmldata::TiXmlDocumentPtr hDoc = xmldata::OpenXMLDoc(filename);
	OpenDoc(hDoc.get());
}

void Problem::SolveSLI()
{
	switch (m_type)
	{
	case ST_CholeskyLDLT:
		m_impl->SolveSLI<Eigen::SimplicialLDLT<Eigen::SparseMatrix<float> > >(m_maxIterationCount, m_expsilon);
		break;
	case ST_CholeskyLLT:
		m_impl->SolveSLI<Eigen::SimplicialLLT<Eigen::SparseMatrix<float> > >(m_maxIterationCount, m_expsilon);
		break;
	case ST_IterativeCG:
		m_impl->SolveSLI<Eigen::ConjugateGradient<Eigen::SparseMatrix<float> > >(m_maxIterationCount, m_expsilon);
		break;
	}
}

void Problem::SetSolverOptions(SolverType type, int maxIterationCount, float expsilon)
{
	m_type = type;
	m_maxIterationCount = maxIterationCount;
	m_expsilon = expsilon;
}

void Problem::SolveProblem()
{
	m_impl->m_typeSpecific->SolveProblem(*this);
}

void Problem::Clear()
{
	m_impl->m_elements.Init(0);
	m_impl->m_nodes.Init(0, 0);
	m_impl->m_matLib.clear();
	m_impl->m_nodalConstraintList.clear();
	m_impl->m_nodalForceList.Init(0, 0);
	m_impl->m_globalK = Eigen::SparseMatrix<float>();
	m_impl->m_input = Eigen::VectorXf();
	m_impl->m_output = Eigen::VectorXf();
}

void Problem::OpenDoc(TiXmlDocument* hDoc)
{
	Clear();
	TiXmlHandle hRoot(NULL);
	{
		TiXmlElement* pElem;
		pElem = hDoc->FirstChildElement();
		if (pElem == NULL)
		{
			LOGE("Document does not have root");
		}
		LOGI("Doc type: \t\t%s", pElem->Value());
		hRoot = TiXmlHandle(pElem);
	}

	LOGI(" ");

	m_impl->m_typeSpecific = new Problem2DTypeSpecific;

	/* Materials */
	m_impl->ReadMaterials(hRoot);

	/* Nodes */
	m_impl->ReadNodes(hRoot);

	/* Elements */
	m_impl->ReadElements(hRoot);

	/* NodalForces */
	m_impl->ReadNodalForces(hRoot);

	/* NodalConstraints */
	m_impl->ReadNodalConstraint(hRoot);
}

void Problem::SaveToFile(const std::string& filename) const
{

}

const ProblemDescription& Problem::GetProblemDescription() const
{
	return m_impl->m_desc;
}

const StrideDataArray& Problem::GetNodes() const
{
	return m_impl->m_nodes;
}

const ElementsContainer& Problem::GetElements() const
{
	return m_impl->m_elements;
}

const Eigen::VectorXf& Problem::GetDeforms() const
{
	return m_impl->m_output;
}

const IndexedStrideDataArray& Problem::GetNodalForceList() const
{
	return m_impl->m_nodalForceList;
}

const NodalConstraintList& Problem::GetNodalConstraintList() const
{
	return m_impl->m_nodalConstraintList;
}

void Problem::UpdateNodes(MeshRenderer* meshRenderer) const
{
	if (m_impl->m_typeSpecific != NULL)
		m_impl->m_typeSpecific->UpdateNodes(*this, meshRenderer);
}

void Problem::SubmitMeshesToRender(MeshRenderer* meshRenderer) const
{
	if (m_impl->m_typeSpecific != NULL)
		m_impl->m_typeSpecific->SubmitMeshesToRender(*this, meshRenderer);
}

bool Problem::UpdateViewOption(MeshRenderer* meshRenderer)
{
	if (m_impl->m_typeSpecific != NULL)
		return m_impl->m_typeSpecific->UpdateView(meshRenderer);
	return false;
}

Problem::Problem() :m_impl(new ProblemImpl)
{
	m_impl->m_typeSpecific = NULL;
}

Problem::~Problem()
{
	delete m_impl;
}

void Problem::GenerateGlobalKMatrix()
{
	m_impl->GenerateGlobalKMatrix();
}

void Problem::ApplyConstrints()
{
	m_impl->ApplyConstrints();
}

void Problem::CreateLoadVector()
{
	m_impl->CreateLoadVector();
}

void ProblemImpl::ReadMaterials(TiXmlHandle hRoot)
{
	TiXmlNode* materialLibrary = xmldata::GetNodeByPath(hRoot.Node(), "materials");
	xmldata::foreachChild(materialLibrary->ToElement(), "material", ReadMaterialFunctor(m_matLib));
}

void ProblemImpl::ReadNodes(TiXmlHandle hRoot)
{
	TiXmlNode* nodeElementList = xmldata::GetNodeByPath(hRoot.Node(), "NodeList");
	int nodesCount = 0;
	xmldata::ParseValue(nodeElementList->ToElement(), "count", nodesCount);
	m_nodes.Init(m_typeSpecific->GetDOFPerNode(), nodesCount);
	xmldata::foreachChild(nodeElementList->ToElement(), "node", ReadNodeFunctor(m_nodes));
}

void ProblemImpl::ReadElements(TiXmlHandle hRoot)
{
	ElementFabric fabric;
	TiXmlNode* elemetsElementList = xmldata::GetNodeByPath(hRoot.Node(), "ElementList");
	int elementsCount = 0;
	std::string type;
	xmldata::ParseValue(elemetsElementList->ToElement(), "count", elementsCount);
	m_elements.Init(elementsCount);
	xmldata::foreachChild(elemetsElementList->ToElement(), "element", ReadElementFunctor(m_elements, fabric));
}

void ProblemImpl::ReadNodalForces(TiXmlHandle hRoot)
{
	TiXmlNode* nodalForcesElementList = xmldata::GetNodeByPath(hRoot.Node(), "NodalForceList");
	int loadsCount = 0;
	xmldata::ParseValue(nodalForcesElementList->ToElement(), "count", loadsCount);
	m_nodalForceList.Init(m_typeSpecific->GetDOFPerNode(), loadsCount);
	xmldata::foreachChild(nodalForcesElementList->ToElement(), "force", ReadNodalForceFunctor(m_nodalForceList));
}

void ProblemImpl::ReadNodalConstraint(TiXmlHandle hRoot)
{
	TiXmlNode* nodalConstraintElementList = xmldata::GetNodeByPath(hRoot.Node(), "NodalConstraintList");
	xmldata::foreachChild(nodalConstraintElementList->ToElement(), "const", ReadNodalConstraintFunctor(m_nodalConstraintList));
}

max_stars_repo_name: podgorskiy/TinyFEM

max_issues_repo_name: podgorskiy/TinyFEM

max_forks_repo_name: podgorskiy/TinyFEM


text:
/*! \file diffdata.cpp
    \brief 微分方程式のデータを集めた構造体の実装

    Copyright ©  2015 @dc1394 All Rights Reserved.
    This software is released under the BSD 2-Clause License.
*/

#include "diffdata.h"
#include <boost/cast.hpp>   // for boost::numeric_cast

namespace schrac {
    // #region コンストラクタ

    DiffData::DiffData(std::shared_ptr<Data> const & pdata) :
        node_(pdata->n_ - pdata->l_ - 1),
        pdata_(pdata),
        thisnode_(0),
        Z_(pdata->Z_)
    {
        auto const grid_num = pdata_->grid_num_;

        mp_o_ = boost::numeric_cast<std::int32_t>(std::round(static_cast<double>(grid_num) * pdata_->mat_po_ratio_));
        mp_i_ = grid_num - mp_o_;

        auto const osize = boost::numeric_cast<dvector::size_type>(mp_o_ + 1);
        auto const isize = boost::numeric_cast<dvector::size_type>(mp_i_ + 1);

        dx_ = (pdata_->xmax_ - pdata_->xmin_) / static_cast<double>(grid_num - 1);

        // メモリ確保
        x_o_.resize(osize);
        x_i_.resize(isize);
        r_mesh_i_.resize(isize);
        lo_.reserve(osize);
        li_.reserve(isize);
        mo_.reserve(osize);
        mi_.reserve(isize);

        auto const len = grid_num - boost::numeric_cast<std::int32_t>(isize);

        for (auto i = 0; i <= mp_o_; i++) {
            auto const x = pdata_->xmin_ + static_cast<double>(i) * dx_;
            x_o_[i] = x;
        }

        for (auto i = grid_num; i > len; i--) {
            auto const x = pdata_->xmin_ + static_cast<double>(i) * dx_;
            x_i_[grid_num - i] = x;
            r_mesh_i_[grid_num - i] = std::exp(x);
        }
    }
}


text:
// Ogonek
//
// Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

// Workaround for Boost.Hash's lack of support for char16_t and char32_t

#ifndef OGONEK_DETAIL_BOOST_HASH_UNICODE_HPP
#define OGONEK_DETAIL_BOOST_HASH_UNICODE_HPP

#include <boost/functional/hash.hpp>

// hack for char32_t and char16_t hashing
namespace boost {
    namespace hash_detail {
        template <> struct basic_numbers<char16_t>
        : boost::hash_detail::enable_hash_value {};
        template <> struct basic_numbers<char32_t>
        : boost::hash_detail::enable_hash_value {};
    } // namespace hash_detail
} // namespace boost

#endif // OGONEK_DETAIL_BOOST_HASH_UNICODE_HPP

max_stars_repo_name: libogonek/ogonek

max_issues_repo_name: libogonek/ogonek

max_forks_repo_name: libogonek/ogonek


text:
/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <boost/test/unit_test.hpp>

#include <vector>
#include <round/script/Lua.h>

#include "TestScript.h"
#include "TestNode.h"

using namespace std;
using namespace Round;

#if defined(ROUND_SUPPORT_LUA)

BOOST_AUTO_TEST_SUITE(script)

////////////////////////////////////////////////////////////
// Lua Engine
////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE(LuaEngineEchoTest) {
  Error err;
  ScriptManager scriptMgr;

  BOOST_CHECK(scriptMgr.setEngine(new LuaEngine()));
  BOOST_CHECK(scriptMgr.hasEngine(LuaEngine::LANGUAGE));

  BOOST_CHECK(scriptMgr.setScript(Test::SCRIPT_ECHO_NAME, LuaEngine::LANGUAGE, Round::Test::LUA_ECHO_CODE, Script::ENCODING_NONE, &err));
  BOOST_CHECK(scriptMgr.hasScript(Test::SCRIPT_ECHO_NAME));

  Test::ScriptTestController scriptTestController;
  scriptTestController.runEchoMethodTest(&scriptMgr);
}

BOOST_AUTO_TEST_CASE(LuaEngineSumTest) {

  ScriptManager scriptMgr;

  BOOST_CHECK(scriptMgr.setScript(new Script(LuaEngine::LANGUAGE, Test::SCRIPT_SUM_NAME, Test::LUA_SUM_CODE)));
  BOOST_CHECK(scriptMgr.hasScript(Test::SCRIPT_SUM_NAME));

  BOOST_CHECK(scriptMgr.setEngine(new LuaEngine()));
  BOOST_CHECK(scriptMgr.hasEngine(LuaEngine::LANGUAGE));

  Test::ScriptTestController scriptTestController;
  scriptTestController.runSumMethodTest(&scriptMgr);
}

////////////////////////////////////////////////////////////
// Lua Function
////////////////////////////////////////////////////////////

#define LUA_JOB_SCRIPT_BUF_SIZE 1024

#define LUA_TEST_JOB_HELLO "hello"
#define LUA_TEST_JOB_HELLO_SCRIPT \
  "return \"" LUA_TEST_JOB_HELLO "\""

BOOST_AUTO_TEST_CASE(LuaHelloTest) {

  TestLocalNode node;
  Error err;

  BOOST_CHECK(node.start(&err));

  std::string result;
  BOOST_CHECK(node.execJob(LuaEngine::LANGUAGE, LUA_TEST_JOB_HELLO_SCRIPT, Round::Script::ENCODING_NONE, &result, &err));
  BOOST_CHECK_EQUAL(result.compare(LUA_TEST_JOB_HELLO), 0);

  BOOST_CHECK(node.stop(&err));
}

#define LUA_TEST_JOB_GETNETWORKSTATE \
  "json = require(\"json\") -- JSON4Lua\n" \
  "result = " ROUNDCC_SYSTEM_METHOD_GET_NETWORK_STATE "()\n" \
  "-- print(result)\n" \
  "jsonResult = json.decode(result)" \
  "return #jsonResult[\"clusters\"]\n"

BOOST_AUTO_TEST_CASE(LuaGetNetworkStateMethodTest) {

  TestLocalNode node;
  Error err;

  BOOST_CHECK(node.start(&err));

  std::string result;
  BOOST_CHECK(node.execJob(LuaEngine::LANGUAGE, LUA_TEST_JOB_GETNETWORKSTATE, Round::Script::ENCODING_NONE, &result, &err));
  BOOST_CHECK_EQUAL(result.compare("1"), 0);

  BOOST_CHECK(node.stop(&err));
}

#define LUA_TEST_JOB_GETCLUSTERSTATE \
  "json = require(\"json\") -- JSON4Lua\n" \
  "result = " ROUNDCC_SYSTEM_METHOD_GET_CLUSTER_STATE "()\n" \
  "-- print(result)\n" \
  "jsonResult = json.decode(result)" \
  "return #jsonResult[\"cluster\"][\"nodes\"]\n"

BOOST_AUTO_TEST_CASE(LuaGetClusterStateMethodTest) {

  TestLocalNode node;
  Error err;

  BOOST_CHECK(node.start(&err));

  std::string result;
  BOOST_CHECK(node.execJob(LuaEngine::LANGUAGE, LUA_TEST_JOB_GETCLUSTERSTATE, Round::Script::ENCODING_NONE, &result, &err));
  BOOST_CHECK_EQUAL(result.compare("1"), 0);

  BOOST_CHECK(node.stop(&err));
}

#define LUA_TEST_JOB_GETNODESTATE \
  "json = require(\"json\") -- JSON4Lua\n" \
  "result = " ROUNDCC_SYSTEM_METHOD_GET_NODE_STATE "()\n" \
  "-- print(result)\n" \
  "jsonResult = json.decode(result)\n" \
  "return jsonResult[\"hash\"]\n"

BOOST_AUTO_TEST_CASE(LuaGetNodeMethodTest) {

  TestLocalNode node;
  Error err;

  BOOST_CHECK(node.start(&err));

  std::string result;
  BOOST_CHECK(node.execJob(LuaEngine::LANGUAGE, LUA_TEST_JOB_GETNODESTATE, Round::Script::ENCODING_NONE, &result, &err));

  std::string nodeHash;
  node.getHashCode(&nodeHash);

  BOOST_CHECK_EQUAL(result.compare(nodeHash), 0);

  BOOST_CHECK(node.stop(&err));
}

#define LUA_TEST_JOB_SETREGISTORY \
  "json = require(\"json\") -- JSON4Lua\n" \
  "key = \"%s\"\n" \
  "val = \"%s\"\n" \
  ROUNDCC_SYSTEM_METHOD_SET_REGISTRY "(key, val)\n" \
  "ok, result = " ROUNDCC_SYSTEM_METHOD_GET_REGISTRY "(key)\n" \
  "jsonResult = json.decode(result)\n" \
  "regVal = jsonResult[\"value\"]\n" \
  "return regVal\n"

BOOST_AUTO_TEST_CASE(LuaRegistryBasicMethodTest) {

  TestLocalNode node;
  Error err;

  BOOST_CHECK(node.start(&err));

  char script[LUA_JOB_SCRIPT_BUF_SIZE+1];
  for (int n=0; n<10; n++) {
    time_t ts;

    Registry inReg;

    std::stringstream ss;
    time(&ts); ts += rand(); ss << ts;
    std::string key = "key" + ss.str();
    std::string val = "val" + ss.str();

    snprintf(script,
             LUA_JOB_SCRIPT_BUF_SIZE,
             LUA_TEST_JOB_SETREGISTORY,
             key.c_str(),
             val.c_str());

    std::string result;
    BOOST_CHECK(node.execJob(LuaEngine::LANGUAGE, script, Round::Script::ENCODING_NONE, &result, &err));
    BOOST_CHECK_EQUAL(result.compare(val), 0);
  }

  BOOST_CHECK(node.stop(&err));
}

#define LUA_TEST_JOB_REMOVEREGISTORY \
  "json = require(\"json\") -- JSON4Lua\n" \
  "key = \"%s\"\n" \
  "val = \"%s\"\n" \
  ROUNDCC_SYSTEM_METHOD_SET_REGISTRY "(key, val)\n" \
  "result = " ROUNDCC_SYSTEM_METHOD_REMOVE_REGISTRY "(key)\n" \
  "-- print(result)\n" \
  "return result\n"

BOOST_AUTO_TEST_CASE(LuaRegistryRemoveMethodTest) {

  TestLocalNode node;
  Error err;

  BOOST_CHECK(node.start(&err));

  char script[LUA_JOB_SCRIPT_BUF_SIZE+1];
  for (int n=0; n<10; n++) {
    time_t ts;

    Registry inReg;

    std::stringstream ss;
    time(&ts); ts += rand(); ss << ts;
    std::string key = "key" + ss.str();
    std::string val = "val" + ss.str();

    snprintf(script,
             LUA_JOB_SCRIPT_BUF_SIZE,
             LUA_TEST_JOB_REMOVEREGISTORY,
             key.c_str(),
             val.c_str());

    std::string result;
    BOOST_CHECK(node.execJob(LuaEngine::LANGUAGE, script, Round::Script::ENCODING_NONE, &result, &err));
    BOOST_CHECK_EQUAL(result.compare("true"), 0);
  }

  BOOST_CHECK(node.stop(&err));
}

#define LUA_TEST_JOB_POSTMETHOD \
  "json = require(\"json\") -- JSON4Lua -- JSON4Lua\n" \
  "key = \"%s\"\n" \
  "val = \"%s\"\n" \
  ROUNDCC_SYSTEM_METHOD_SET_REGISTRY "(key, val)\n" \
  "ok, result = " ROUNDCC_SCRIPT_POST_METHOD "('" ROUNDCC_SYSTEM_METHOD_GET_REGISTRY "', '{\"key\": \"%s\"}', '')\n" \
  "jsonResult = json.decode(result)\n" \
  "regVal = jsonResult[\"value\"]\n" \
  "return regVal\n"

#define LUA_TEST_JOB_POSTMETHOD_PARAM \
""

BOOST_AUTO_TEST_CASE(LuaPostMethodTest) {
  TestLocalNode node;
  Error err;

  BOOST_CHECK(node.start(&err));

  char script[LUA_JOB_SCRIPT_BUF_SIZE+1];

  for (int n=0; n<10; n++) {
    time_t ts;

    Registry inReg;

    std::stringstream ss;
    time(&ts); ts += rand(); ss << ts;
    std::string key = "key" + ss.str();
    std::string val = "val" + ss.str();

    snprintf(script,
             LUA_JOB_SCRIPT_BUF_SIZE,
             LUA_TEST_JOB_POSTMETHOD,
             key.c_str(),
             val.c_str(),
             key.c_str());

    std::string result;
    BOOST_CHECK(node.execJob(LuaEngine::LANGUAGE, script, Round::Script::ENCODING_NONE, &result, &err));
    BOOST_CHECK_EQUAL(result.compare(val), 0);
  }

  BOOST_CHECK(node.stop(&err));
}

BOOST_AUTO_TEST_SUITE_END()

#endif

max_stars_repo_name: cybergarage/round-cc

max_issues_repo_name: cybergarage/round-cc

max_forks_repo_name: cybergarage/round-cc


text:
/**
 * @file test_policies.cpp
 * @brief This file defines the test cases for the policies.
 *
 * @copyright Copyright (c) 2022
 *
 */

#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <memory>
#include <string>

#include "proseco_planning/config/computeOptions.h"
#include "proseco_planning/config/configuration.h"
#include "proseco_planning/config/defaultConfiguration.h"
#include "proseco_planning/policies/selectionPolicy.h"

using namespace proseco_planning;

struct ConfigFixture {
  ConfigFixture() { Config::create(config::scenarioSimple, config::optionsSimple); }
  ~ConfigFixture() { Config::get()->reset(); }
};

BOOST_FIXTURE_TEST_SUITE(UCT, ConfigFixture)

BOOST_AUTO_TEST_CASE(instantiation) {
  std::string selectionPolicyName = "UCTProgressiveWidening";

  auto selectionPolicy = SelectionPolicy::createPolicy(selectionPolicyName);

  BOOST_REQUIRE_EQUAL(selectionPolicy->m_name, selectionPolicyName);
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include <slas/network/network.h>
#include <slas/network/detail/const_values.h>
#include <slas/network/detail/system.h>
#include <slas/network/exception/detail/cant_open_socket_exception.h>
#include <slas/network/exception/detail/bad_address_exception.h>
#include <slas/network/exception/detail/close_exception.h>
#include <slas/network/exception/detail/poll_exception.h>
#include <slas/network/exception/detail/accept_exception.h>
#include <slas/network/exception/detail/recv_exception.h>
#include <slas/network/exception/detail/timeout_exception.h>
#include <slas/network/exception/detail/message_too_long_exception.h>
#include <slas/network/exception/detail/connect_exception.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <poll.h>

#include <boost/log/trivial.hpp>
#include <cstring>
#include <regex>
#include <algorithm>
#include <iterator>
#include <cstring>
#include <cerrno>

using namespace std;

namespace network
{

Network::~Network() {
}

NetworkPtr Network::Create() {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Create: Function call";
  detail::SystemInterfacePtr system(new detail::System());
  return Create(system);
}

NetworkPtr Network::Create(detail::SystemInterfacePtr system) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Create(system): Function call";
  NetworkPtr network_ptr(new Network(system));
  return network_ptr;
}

int Network::Socket(int domain) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Socket: Function call with (domain=" << domain << ")";
  int socket_fd = system_->Socket(domain, SOCK_STREAM, 0);
  if (socket_fd < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::Socket: Error: " << strerror(errno);
    throw exception::detail::CantOpenSocketException();
  }

  return socket_fd;
}

int Network::OpenUnixSocket(const string &filesystem_path) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::OpenUnixSocket: Function call with (filesystem_path=" << filesystem_path << ")";
  if (filesystem_path.length() > 90) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::OpenUnixSocket: Error: Address too long";
    throw exception::detail::BadAddressException();
  }

  struct sockaddr_un addr;
  addr.sun_family = AF_UNIX;
  addr.sun_path[90] = '\0';
  strncpy(addr.sun_path, filesystem_path.c_str(), 91);

  return OpenSocket(PF_UNIX, (struct sockaddr *) &addr, sizeof (struct sockaddr_un));
}

int Network::OpenIpv4Socket(const string &address, int port) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::OpenIpv4Socket: Function call with (address=" << address << "; port=" << port << ")";
  regex pattern("\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}");

  if (!regex_match(address, pattern)) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::OpenIpv4Socket: Error: ipv4 address is not correct";
    throw exception::detail::BadAddressException();
  }

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(port);
  addr.sin_addr.s_addr = inet_addr(address.c_str());
  memset(addr.sin_zero, 0, sizeof (addr.sin_zero));

  return OpenSocket(PF_INET, (struct sockaddr *) &addr, sizeof (struct sockaddr_in));
}

void Network::ConnectUnix(int socket, const std::string &filesystem_path) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::ConnectUnix: Function call with (socket=" << socket << "; filesystem_path=" << filesystem_path << ")";
  if (filesystem_path.length() > 90) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::ConnectUnix: Error: Path too long";
    throw exception::detail::BadAddressException();
  }

  struct sockaddr_un addr;
  addr.sun_family = AF_UNIX;
  addr.sun_path[90] = '\0';
  strncpy(addr.sun_path, filesystem_path.c_str(), 91);

  int ret = system_->Connect(socket, (struct sockaddr *) &addr, sizeof (struct sockaddr_un));
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::ConnectUnix: Error: " << strerror(errno);
    throw exception::detail::ConnectException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::ConnectUnix: Done";
}

void Network::Close(int socket) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Close: Function call with (socket=" << socket << ")";
  int ret = system_->Close(socket);
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::Close: Error: " << strerror(errno);
    throw exception::detail::CloseException();
  }
}

void Network::SendText(int socket, const string &text) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::SendText: Function call with (socket=" << socket << "; text=" << text << ")";
  const char *ctext = text.c_str();
  NetworkMessage message;
  char *data = nullptr;
  char msg_type = 0;

  int to_copy = 0;
  for (size_t i = 0; i < text.length(); i += (detail::MaxMessageLength - 1)) {
    if (i + detail::MaxMessageLength <= text.length()) {
      to_copy = detail::MaxMessageLength - 1;
      msg_type = 'M';
    }
    else {
      to_copy = text.length() - i;
      msg_type = 'L';
    }

    message.resize(to_copy + 1);
    data = message.data();

    data[0] = msg_type;
    (void) strncpy(data + 1, ctext + i, to_copy);

    SendMessage(socket, message);
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::SendText: Done";
}

const string Network::ReceiveText(int socket) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::ReceiveText: Function call with (socket=" << socket << ")";
  NetworkMessage message;

  receive_text_buffer.clear();

  do {
    message = RecvMessage(socket);

    receive_text_buffer.reserve(receive_text_buffer.size() + message.size() + 1);
    copy(message.begin() + 1, message.end(), back_inserter(receive_text_buffer));

  }
  while (message.at(0) != 'L');

  receive_text_buffer.push_back('\0');

  string received(receive_text_buffer.data());
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::ReceiveText: Received: " << received << ")";
  return received;
}

NetworkMessage Network::RecvMessage(int socket) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::RecvMessage: Function call with (socket=" << socket << ")";
  WaitStatus wait_status;
  unsigned message_length = 0, total = 0, left_to_receive = 0;
  int received = 0;
  NetworkMessage message;

  wait_status = WaitForData(socket, detail::TimeoutSeconds);
  if (wait_status != WaitStatus::NEW_DATA) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::RecvMessage: Timeout";
    throw exception::detail::TimeoutException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::RecvMessage: Receiving first part";
  received = Recv(socket, buffer, 1);
  total = received;
  message_length = static_cast<unsigned char> (buffer[0]);
  message.resize(message_length);

  (void) memcpy(message.data(), buffer + 1, received - 1);

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::RecvMessage: Receiving message";
  while (total < message_length) {
    left_to_receive = message_length + 1 - total;

    wait_status = WaitForData(socket, detail::TimeoutSeconds);
    if (wait_status != WaitStatus::NEW_DATA) {
      BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::RecvMessage: Timeout";
      throw exception::detail::TimeoutException();
    }

    received = Recv(socket, buffer, (left_to_receive > detail::BufferLength) ? detail::BufferLength : left_to_receive);
    (void) memcpy(message.data() + total - 1, buffer, received);
    total += received;
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::RecvMessage: Received";
  return message;
}

void Network::SendMessage(int socket, const NetworkMessage &message) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::SendMessage: Function call with (socket=" << socket << "; message)";
  int sent = 0, left = 0;

  if (message.size() > detail::MaxMessageLength) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::SendMessage: Message too long (" << message.size() << ")";
    throw exception::detail::MessageTooLongException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::SendMessage: Sending first part";
  unsigned char message_length = static_cast<unsigned char> (message.size());
  do {
    sent = Send(socket, &message_length, 1);
  }
  while (sent == 0);

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::SendMessage: Sending message";
  const char *buffer = message.data();
  sent = 0;
  left = message_length - sent;
  while (left > 0) {
    sent += Send(socket, buffer + sent, left);
    left = message_length - sent;
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::SendMessage: Done";
}

WaitStatus Network::WaitForData(int socket, int timeout_seconds) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::WaitForData: Function call with (socket=" << socket << "; timeout_seconds=" << timeout_seconds << ")";
  struct pollfd descriptors = {socket, POLLIN, 0};
  int ret = system_->Poll(&descriptors, 1, timeout_seconds * 1000);

  if (ret == 0) {
    BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::WaitForData: Timeout";
    return WaitStatus::TIMEOUT;
  }
  else if (ret > 0) {
    BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::WaitForData: New data";
    return WaitStatus::NEW_DATA;
  }
  else {
    BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::WaitForData: Poll error: " << strerror(errno);
    throw exception::detail::PollException();
  }
}

ConnectionData Network::Accept(int socket) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Accept: Function call with (socket=" << socket << ")";
  ConnectionData data;
  data.socket = system_->Accept(socket, (struct sockaddr *) &data.addr, &data.addr_size);
  if (data.socket < 0) {
    BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Accept: Accept error: " << strerror(errno);
    throw exception::detail::AcceptException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Accept: Done";
  return data;
}

Network::Network(detail::SystemInterfacePtr system)
: system_(system) {
}

int Network::OpenSocket(int domain, struct sockaddr *saddr, int saddr_size) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::OpenSocket: Function call with (domain=" << domain << "; sockaddr*; saddr_size=" << saddr_size << ")";
  int ret, socket_fd;

  socket_fd = Socket(domain);

  int optval = 1;
  ret = system_->Setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::OpenSocket: Setsockopt error: " << strerror(errno);
    throw exception::detail::CantOpenSocketException();
  }

  ret = system_->Bind(socket_fd, saddr, saddr_size);
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::OpenSocket: Bind error: " << strerror(errno);
    throw exception::detail::CantOpenSocketException();
  }

  ret = system_->Listen(socket_fd, 20);
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::OpenSocket: Listen error: " << strerror(errno);
    throw exception::detail::CantOpenSocketException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::OpenSocket: Done";
  return socket_fd;
}

size_t Network::Recv(int socket, void *buffer, size_t length) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Recv: Functino call with (socket=" << socket << "; buffer*; length=" << length << ")";
  int received = system_->Recv(socket, buffer, length, 0);
  if (received == 0 || received < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::Recv: Recv error: " << strerror(errno);
    throw exception::detail::RecvException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Recv: Done";
  return received;
}

size_t Network::Send(int socket, const void *buffer, size_t length) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Send: Functino call with (socket=" << socket << "; buffer*; length=" << length << ")";
  int sent = system_->Send(socket, buffer, length, 0);
  if (sent < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::network::Network::Recv: Recv error: " << strerror(errno);
    throw exception::detail::RecvException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::network::Network::Send: Done";
  return sent;
}

}

max_stars_repo_name: chyla/slas

max_issues_repo_name: chyla/slas

max_forks_repo_name: chyla/slas


text:
//
// Copyright (c) 2009 Rutger ter Borg
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_NUMERIC_BINDINGS_DETAIL_LINEAR_ITERATOR_HPP
#define BOOST_NUMERIC_BINDINGS_DETAIL_LINEAR_ITERATOR_HPP

#include <boost/iterator/iterator_adaptor.hpp>

namespace boost {
namespace numeric {
namespace bindings {
namespace detail {

template< typename T, typename StrideType >
class linear_iterator: public boost::iterator_adaptor<
        linear_iterator<T, StrideType >,
        T*, use_default, random_access_traversal_tag > {
public:

    typedef mpl::int_<StrideType::value> stride_type;

    linear_iterator():
        linear_iterator::iterator_adaptor_(0) {}

    explicit linear_iterator( T* p, StrideType ignore ):
        linear_iterator::iterator_adaptor_(p) {}

private:
    friend class boost::iterator_core_access;

    void advance( int n ) {
        (this->base_reference()) += n * stride_type::value;
    }

    void decrement() {
        (this->base_reference()) -= stride_type::value;
    }

    void increment() {
        (this->base_reference()) += stride_type::value;
    }

};

template< typename T >
class linear_iterator< T, std::ptrdiff_t >: public boost::iterator_adaptor<
        linear_iterator< T, std::ptrdiff_t >,
        T*, use_default, random_access_traversal_tag > {
public:

    typedef std::ptrdiff_t stride_type;

    linear_iterator():
        linear_iterator::iterator_adaptor_(0),
        m_stride(0) {}

    explicit linear_iterator( T* p, std::ptrdiff_t stride ):
        linear_iterator::iterator_adaptor_(p),
        m_stride( stride ) {}

private:
    friend class boost::iterator_core_access;

    void advance( int n ) {
        (this->base_reference()) += n * m_stride;
    }

    void decrement() {
        (this->base_reference()) -= m_stride;
    }

    void increment() {
        (this->base_reference()) += m_stride;
    }

    std::ptrdiff_t m_stride;
};

} // namespace detail
} // namespace bindings
} // namespace numeric
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: ljktest/siconos

max_issues_repo_name: ljktest/siconos

max_forks_repo_name: ljktest/siconos


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_IEEE_FUNCTIONS_SATURATE_AT_HPP_INCLUDED
#define BOOST_SIMD_IEEE_FUNCTIONS_SATURATE_AT_HPP_INCLUDED

#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>

namespace boost { namespace simd
{
  namespace tag
  {
   /*!
     @brief eps generic tag

     Represents the saturate_at function in generic contexts.

     @par Models:
        Hierarchy
    **/
    template <class T>
    struct saturate_at_ : ext::elementwise_< saturate_at_<T> >
    {
      /// @brief Parent hierarchy
      typedef ext::elementwise_< saturate_at_<T> > parent;
      template<class... Args>
      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
      BOOST_AUTO_DECLTYPE_HEADER( dispatching( ext::adl_helper(), *(saturate_at_*)0, static_cast<Args&&>(args)... ) )
      {
        return dispatching( ext::adl_helper(), saturate_at_(), static_cast<Args&&>(args)... );
      }
    };
  }
  /*!
    Returns the saturated value of the first input relative to the symmetric
    interval defined by the template parameter which has to be the tag of
    a constant.

    @par Semantic:

    @code
    T r = saturate <Tag>(x)
    @endcode

    is similar to:

    @code
    if (a0 > Tag<T>()) r =  Tag<T>();
    else if  (a0 < -Tag<T>()) r = -Tag<T>() ;
    else r = a0;
    @endcode

    @param a0

    @return a value of same type as the inputs
  **/

  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL( tag::saturate_at_<A0>
                                            , saturate_at
                                            , (A1 const&)
                                            , 2
                                            )
} }

#endif


text:
#include <ddemux.h>
#include <boost/python.hpp>

using namespace boost::python;

void export_ddemux()
{
  class_<DDemux, bases<Element>, boost::shared_ptr<DDemux>, boost::noncopyable>
        ("DDemux", init<std::string, std::vector<ValuePtr>, unsigned>())
    .def("class_name",    &DDemux::class_name)
    .def("processing",    &DDemux::processing)
    .def("flow_code",     &DDemux::flow_code)
  ;
}


text:
/*
 * Copyright (c) 2007-2020 Texas A&M University System
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the
 *   distribution.
 * - Neither the name of the copyright holders nor the names of
 *   its contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * THE COPYRIGHT 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.
 */
#include <ctime>
#include <iostream>
#include <string>
#include <signal.h>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

#include <ibrdtn/api/Client.h>
#include <ibrdtn/api/FileBundle.h>
#include <ibrdtn/api/BLOBBundle.h>
#include <ibrcommon/net/tcpclient.h>
#include <ibrcommon/thread/Mutex.h>
#include <ibrcommon/thread/MutexLock.h>
#include <ibrcommon/data/BLOB.h>
#include <ibrcommon/Logger.h>

#include "../DistressNet.h"

using boost::asio::ip::udp;

dtn::api::Client* _client = NULL;
ibrcommon::tcpclient* _conn = NULL;
bool run = true;

void term( int signal )
{
	std::cout << "caught signal" << std::endl;
	if ( signal >= 1 )
	{
		if ( _client != NULL )
		{
			std::cout << "exiting..." << std::endl;
			run = false;
		}
	}
}

int main()
{
	std::cout << "btag faker server" << std::endl;

	signal( SIGINT, term );
	signal( SIGTERM, term );

	string file_source = "btagfaker";
	_conn = new ibrcommon::tcpclient;
	_conn->open( "127.0.0.1", 4550 );
	_client = new dtn::api::Client( file_source, *_conn, dtn::api::Client::MODE_SENDONLY );
	std::cout << "Created dtn client" << std::endl;
	_client->connect();

	std::cout << "Initialized" << std::endl;

	struct timeval now;

	char hostname[1024];
	hostname[1023] = '\0';
	gethostname( hostname, 1023 );

	int size = 1000000; //20kb
	int sleepu = 20;
// 	char filler[size];
// 	for (int i=0; i < size; i++)
// 		filler[i] = 'r';

	cout << "sending " << size << "B bundles every " << sleepu << " secs " << endl;
	while ( run == true )
	{
		ibrcommon::BLOB::Reference ref = ibrcommon::BLOB::create();
		stringstream data;

		btag_t btag;

		btag.mote_id = 99;
		strcpy( btag.address, "fake1" );
		strcpy( btag.task_force, "fake2" );

		btag.living = 99;
		btag.dead = 99;

		::gettimeofday( &now, 0 );
// 		data << "btag: ";
		data << "created " << ( now.tv_sec - 946684800 ) << " ";
		data << "at " << hostname << " ";
		data << "uniqid " << hostname << " ,,, " << ( now.tv_sec - 946684800 ) << ",,," << "btagfaker" << " ";
		data << "data: ";
		std::cout << "sending this: " << data.str() << endl;

		string datas = data.str();
		datas.resize( size, 'r' );
		( *ref.iostream() ) << datas;

// 		data << btag.mote_id << "---";
// 		data << btag.address_line_1 << "---";
// 		data << btag.address_line_2 << "---";
// 		data << btag.task_force << "---";
// 		data << btag.living << "---";
// 		data << btag.dead << "---";
// 		data << (int) btag.search_complete << "---";

// 		data << filler;

// 		(*ref.iostream()) << data.str();

		string file_destination = "dtn://router1.dtn/basestation";
		unsigned int lifetime = 1000;
		int priority = 2;
		dtn::api::BLOBBundle b( file_destination, ref );
		b.setLifetime( lifetime );
		*_client << b;
		std::cout << "sending to router1 " << endl;
		_client->flush();

// 		string file_destination1 = "dtn://router7.dtn/basestation";
// 		unsigned int lifetime1 = 1000;
// 		int priority1 = 2;
// 		dtn::api::BLOBBundle b1(file_destination1, ref);
// 		b1.setLifetime(lifetime1);
// 		*_client << b1;
// 		std::cout << "sending to router7 " << endl;
// 		_client->flush();

		sleep( sleepu );
	}

	_client->close();
	_conn->close();
	return 0;
}

max_stars_repo_name: ZareenaSameer/distressnet

max_issues_repo_name: ZareenaSameer/distressnet

max_forks_repo_name: ZareenaSameer/distressnet


text:
#include <boost/python/def.hpp>
#include <boost/python/list.hpp>
#include <boost/python/tuple.hpp>

#include <scitbx/array_family/versa.h>
#include <scitbx/array_family/accessors/flex_grid.h>
#include <scitbx/array_family/shared.h>
#include <scitbx/auto_array.h>
#include <boost/shared_array.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <vector>

/* silence warnings triggered by bad coding of the standard library
   on MacOS X, at least with XCode 3.2.2
 */
#pragma clang diagnostic ignored "-Wmismatched-tags"
#include <valarray>

namespace scitbx { namespace af { namespace boost_python {

namespace {

#define SCITBX_LOC_ST(S, T) \
    result.append(make_tuple(S, sizeof(T)));

#define SCITBX_LOC_T(T) SCITBX_LOC_ST(#T, T)

#define SCITBX_LOC_empty_container_sizes(T) \
  boost::python::list \
  empty_container_sizes_##T() \
  { \
    using namespace boost::python; \
    list result; \
    SCITBX_LOC_T(T) \
    SCITBX_LOC_T(af::ref<T>) \
    SCITBX_LOC_T(scitbx::auto_array<T>) \
    SCITBX_LOC_T(boost::shared_array<T>) \
    SCITBX_LOC_T(boost::ptr_vector<T>) \
    SCITBX_LOC_T(std::vector<T>) \
    SCITBX_LOC_T(af::shared<T>) \
    result.append( \
      make_tuple("af::shared [cumulative]", \
                  sizeof(af::shared<T>) + sizeof(af::sharing_handle))); \
    SCITBX_LOC_T(std::valarray<T>) \
    SCITBX_LOC_T(af::versa<T>) \
    typedef af::versa<T, af::flex_grid<> > versa_flex_grid; \
    SCITBX_LOC_ST("af::versa<" #T ", af::flex_grid<> >", versa_flex_grid) \
    result.append( \
      make_tuple("af::versa<" #T ", af::flex_grid<> > [cumulative]", \
                 sizeof(versa_flex_grid) + sizeof(af::sharing_handle))); \
    return result; \
  }

  SCITBX_LOC_empty_container_sizes(int)
  SCITBX_LOC_empty_container_sizes(double)

#undef SCITBX_LOC_empty_container_sizes
#undef SCITBX_LOC_T
#undef SCITBX_LOC_ST

} // namespace anonymous

  void
  wrap_empty_container_sizes()
  {
    using namespace boost::python;
    def("empty_container_sizes_int", empty_container_sizes_int);
    def("empty_container_sizes_double", empty_container_sizes_double);
  }

}}} // namespace scitbx::af::boost_python


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef IROHA_VISITOR_APPLY_FOR_ALL_HPP
#define IROHA_VISITOR_APPLY_FOR_ALL_HPP

#include <boost/variant/static_visitor.hpp>
#include <string>

namespace shared_model {
  namespace detail {

    /**
     * Class provides generic toString visitor for objects
     */
    class ToStringVisitor : public boost::static_visitor<std::string> {
     public:
      template <typename InputType>
      auto operator()(const InputType &operand) const {
        return operand.toString();
      }
    };

  }  // namespace detail
}  // namespace shared_model
#endif  // IROHA_VISITOR_APPLY_FOR_ALL_HPP

max_stars_repo_name: akshatkarani/iroha

max_issues_repo_name: akshatkarani/iroha

max_forks_repo_name: akshatkarani/iroha


text:
/* Copyright Institute of Sound and Vibration Research - All rights reserved */

#include "index_sequence.hpp"

#include <boost/bind.hpp>
#include <boost/spirit/include/qi.hpp>

#include <algorithm>
#include <ciso646>

namespace visr
{
namespace rbbl
{

IndexSequence::IndexSequence()
{
}

IndexSequence::IndexSequence( std::initializer_list<IndexType> const & val )
  : mIndices( val.begin(), val.end() )
{
}

IndexSequence::IndexSequence( std::string const & val )
{
  namespace qi = boost::spirit::qi;

  std::string::const_iterator first = val.begin();
  std::string::const_iterator last = val.end();

  /**
   * Internal object which is called by the spirit parser to hold the results of parsing.
   */
  struct ParseState
  {
  public:
    void push( int val )
    {
      mStack.push_back( val );
    }

    void finish()
    {
      switch( mStack.size() )
      {
      case 0:
        throw std::invalid_argument( "Internal parse error." );
      case 1:
      {
        int const val = mStack[0];
        if( val < 0 )
        {
          throw("IndexSequence: Indices must be greater or equal than zero.");
        }
        mContents.push_back( static_cast<IndexType>(val) );
        break;
      }
      case 2:
      {
        int const start = mStack[0];
        int const end = mStack[1];
        if( start < 0 or end < 0 )
        {
          throw("IndexSequence: The start and end values of a range must be greater or equal than zero.");
        }
        IndexType val = static_cast<IndexType>(mStack[0]);
        while( val <= static_cast<IndexType>(end) )
        {
          mContents.push_back( val++ );
        }
        break;
      }
      case 3:
      {
        int const start = mStack[0];
        int const inc = mStack[1];
        int const end = mStack[2];
        if( start < 0 or end < 0 )
        {
          throw("IndexSequence: The start and end values of a range must be greater or equal than zero.");
        }
        if( inc == 0 )
        {
          throw("IndexSequence: The increment of a range must not be zero.");
        }
        int val = start;
        if( inc > 0 )
        {
          while( val <= end )
          {
            mContents.push_back( val );
            val += inc;
          }
        }
        else // inc < 0
        {
          while( val >= end )
          {
            mContents.push_back( val );
            val += inc;
          }
        }
        break;
      }
      default:
        throw std::invalid_argument( "IndexSequence: Sequence of more than three colon-separated values." );
      }
      mStack.clear();
    }

    std::vector<int> mStack;
    ContainerType mContents;
  };
  ParseState state;

  auto const atom = boost::proto::deep_copy( ((qi::int_[boost::bind( &ParseState::push, &state, _1 )] % qi::char_( ":" ))[boost::bind( &ParseState::finish, &state )] % (qi::char_( ',' ))) | qi::eps );

  bool const parseRet = qi::phrase_parse( first, last, atom,
    qi::ascii::space );

  if( (not parseRet) or( first != last ) )
  {
    throw std::invalid_argument( "IndexSequence: Parsing of initialiser string failed." );
  }

  mIndices.swap( state.mContents );
}

void IndexSequence::clear()
{
  mIndices.clear();
}

} // namespace rbbl
} // namespace visr


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

/*
 * fsa_predictive_compression_test.cpp
 *
 *  Created on: Apr 10, 2015
 *      Author: hendrik
 */

#include <sstream>
#include <string>

#include <boost/test/unit_test.hpp>

#include "keyvi/compression/predictive_compression.h"

namespace keyvi {
namespace compression {

BOOST_AUTO_TEST_SUITE(PredictiveCompressionTests)

// todo: crashes on windows
#if not defined(_WIN32)

BOOST_AUTO_TEST_CASE(CompressAndUncompress) {
  std::istringstream corpus(
      "ht\x05"
      "tp://"
      "tt\x05"
      "ps://"
      "//\x04"
      "www."
      "th\x01"
      "e");

  auto compressor = PredictiveCompression(corpus);

  std::string input = "http://www.the-test.com";
  std::string output = compressor.Compress(input);
  std::string uncompressed = compressor.Uncompress(output);
  BOOST_CHECK_EQUAL(2 + 13, output.size());
  BOOST_CHECK_EQUAL(input, uncompressed);

  input = "aa";
  output = compressor.Compress(input);
  BOOST_CHECK_EQUAL(input, compressor.Uncompress(output));

  input = std::string("null\0http://www.\0-byte.com", 26);
  output = compressor.Compress(input);
  uncompressed = compressor.Uncompress(output);
  BOOST_CHECK_EQUAL(input, uncompressed);
  BOOST_CHECK_EQUAL(26, input.size());
  BOOST_CHECK_EQUAL(26, uncompressed.size());
}

BOOST_AUTO_TEST_CASE(CompressTooLongValue) {
  std::istringstream corpus(
      "ht\x05"
      "tp://"
      "tt\x05"
      "ps://"
      "//\x04"
      "www."
      "th\x14"
      "too_long_value");

  BOOST_CHECK_THROW(PredictiveCompression compressor(corpus), std::invalid_argument);
}

BOOST_AUTO_TEST_CASE(CompressIncomplete) {
  std::istringstream corpus(
      "ht\x05"
      "tp://"
      "tt\x05"
      "ps://"
      "//\x04"
      "www");

  BOOST_CHECK_THROW(PredictiveCompression compressor(corpus), std::istream::failure);
}
#endif

BOOST_AUTO_TEST_SUITE_END()

}  // namespace compression
}  // namespace keyvi